Merge from mainline
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob96b016151fcb30ef87d215141c119c2de435e885
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-2006, AdaCore                       o
11 @c                                                                            o
12 @c  GNAT is free software;  you can  redistribute it  and/or modify it under  o
13 @c  terms of the  GNU General Public License as published  by the Free Soft-  o
14 @c  ware  Foundation;  either version 2,  or (at your option) any later ver-  o
15 @c  sion.  GNAT is distributed in the hope that it will be useful, but WITH-  o
16 @c  OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY  o
17 @c  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License  o
18 @c  for  more details.  You should have  received  a copy of the GNU General  o
19 @c  Public License  distributed with GNAT;  see file COPYING.  If not, write  o
20 @c  to  the  Free Software Foundation,  51  Franklin  Street,  Fifth  Floor,  o
21 @c  Boston, MA 02110-1301, USA.                                               o
22 @c                                                                            o
23 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
27 @c                           GNAT_UGN Style Guide
29 @c  1. Always put a @noindent on the line before the first paragraph
30 @c     after any of these commands:
32 @c          @chapter
33 @c          @section
34 @c          @subsection
35 @c          @subsubsection
36 @c          @subsubsubsection
38 @c          @end smallexample
39 @c          @end itemize
40 @c          @end enumerate
42 @c  2. DO NOT use @example. Use @smallexample instead.
43 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
44 @c        context.  These can interfere with the readability of the texi
45 @c        source file.  Instead, use one of the following annotated
46 @c        @smallexample commands, and preprocess the texi file with the
47 @c        ada2texi tool (which generates appropriate highlighting):
48 @c        @smallexample @c ada
49 @c        @smallexample @c adanocomment
50 @c        @smallexample @c projectfile
51 @c     b) The "@c ada" markup will result in boldface for reserved words
52 @c        and italics for comments
53 @c     c) The "@c adanocomment" markup will result only in boldface for
54 @c        reserved words (comments are left alone)
55 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
56 @c        of reserved words include the new reserved words for project files
58 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
59 @c     command must be preceded by two empty lines
61 @c  4. The @item command should be on a line of its own if it is in an
62 @c     @itemize or @enumerate command.
64 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
65 @c     or "ali".
67 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
68 @c     cause the document build to fail.
70 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
71 @c     This command inhibits page breaks, so long examples in a @cartouche can
72 @c     lead to large, ugly patches of empty space on a page.
74 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
75 @c        or the unw flag set.  The unw flag covers topics for both Unix and
76 @c        Windows.
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
80 @ifset vms
81 @setfilename gnat_ugn_vms.info
82 @end ifset
84 @ifset unw
85 @setfilename gnat_ugn_unw.info
86 @end ifset
88 @set FSFEDITION
89 @set EDITION GNAT
91 @ifset unw
92 @set PLATFORM
93 @set FILE gnat_ugn_unw
94 @end ifset
96 @ifset vms
97 @set PLATFORM OpenVMS
98 @set FILE gnat_ugn_vms
99 @end ifset
101 @settitle @value{EDITION} User's Guide @value{PLATFORM}
102 @dircategory GNU Ada tools
103 @direntry
104 * @value{EDITION} User's Guide (@value{FILE}) @value{PLATFORM}
105 @end direntry
107 @include gcc-common.texi
109 @setchapternewpage odd
110 @syncodeindex fn cp
111 @c %**end of header
113 @copying
114 Copyright @copyright{} 1995-2005, Free Software Foundation
116 Permission is granted to copy, distribute and/or modify this document
117 under the terms of the GNU Free Documentation License, Version 1.2
118 or any later version published by the Free Software Foundation;
119 with the Invariant Sections being ``GNU Free Documentation License'', with the
120 Front-Cover Texts being
121 ``@value{EDITION} User's Guide'',
122 and with no Back-Cover Texts.
123 A copy of the license is included in the section entitled
124 ``GNU Free Documentation License''.
125 @end copying
127 @titlepage
129 @title @value{EDITION} User's Guide
131 @ifset vms
132 @sp 1
133 @flushright
134 @titlefont{@i{@value{PLATFORM}}}
135 @end flushright
136 @end ifset
138 @sp 2
140 @subtitle GNAT, The GNU Ada 95 Compiler
141 @subtitle GCC version @value{version-GCC}
143 @author AdaCore
145 @page
146 @vskip 0pt plus 1filll
148 @insertcopying
150 @end titlepage
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
159 @noindent
160 GNAT, The GNU Ada 95 Compiler@*
161 GCC version @value{version-GCC}@*
163 @noindent
164 AdaCore@*
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling Using gcc::
171 * Binding Using gnatbind::
172 * Linking Using gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files Using gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions Using gnatname::
178 * GNAT Project Manager::
179 * The Cross-Referencing Tools gnatxref and gnatfind::
180 * The GNAT Pretty-Printer gnatpp::
181 * The GNAT Metric Tool gnatmetric::
182 * File Name Krunching Using gnatkr::
183 * Preprocessing Using gnatprep::
184 @ifset vms
185 * The GNAT Run-Time Library Builder gnatlbr::
186 @end ifset
187 * The GNAT Library Browser gnatls::
188 * Cleaning Up Using gnatclean::
189 @ifclear vms
190 * GNAT and Libraries::
191 * Using the GNU make Utility::
192 @end ifclear
193 * Memory Management Issues::
194 * Stack Related Facilities::
195 * Verifying properties using gnatcheck::
196 * Creating Sample Bodies Using gnatstub::
197 * Other Utility Programs::
198 * Running and Debugging Ada Programs::
199 @ifset vms
200 * Compatibility with HP Ada::
201 @end ifset
202 * Platform-Specific Information for the Run-Time Libraries::
203 * Example of Binder Output File::
204 * Elaboration Order Handling in GNAT::
205 * Inline Assembler::
206 * Compatibility and Porting Guide::
207 @ifset unw
208 * Microsoft Windows Topics::
209 @end ifset
210 * GNU Free Documentation License::
211 * Index::
213  --- The Detailed Node Listing ---
215 About This Guide
217 * What This Guide Contains::
218 * What You Should Know before Reading This Guide::
219 * Related Information::
220 * Conventions::
222 Getting Started with GNAT
224 * Running GNAT::
225 * Running a Simple Ada Program::
226 * Running a Program with Multiple Units::
227 * Using the gnatmake Utility::
228 @ifset vms
229 * Editing with Emacs::
230 @end ifset
231 @ifclear vms
232 * Introduction to GPS::
233 * Introduction to Glide and GVD::
234 @end ifclear
236 The GNAT Compilation Model
238 * Source Representation::
239 * Foreign Language Representation::
240 * File Naming Rules::
241 * Using Other File Names::
242 * Alternative File Naming Schemes::
243 * Generating Object Files::
244 * Source Dependencies::
245 * The Ada Library Information Files::
246 * Binding an Ada Program::
247 * Mixed Language Programming::
248 @ifclear vms
249 * Building Mixed Ada & C++ Programs::
250 * Comparison between GNAT and C/C++ Compilation Models::
251 @end ifclear
252 * Comparison between GNAT and Conventional Ada Library Models::
253 @ifset vms
254 * Placement of temporary files::
255 @end ifset
257 Foreign Language Representation
259 * Latin-1::
260 * Other 8-Bit Codes::
261 * Wide Character Encodings::
263 Compiling Ada Programs With gcc
265 * Compiling Programs::
266 * Switches for gcc::
267 * Search Paths and the Run-Time Library (RTL)::
268 * Order of Compilation Issues::
269 * Examples::
271 Switches for gcc
273 * Output and Error Message Control::
274 * Warning Message Control::
275 * Debugging and Assertion Control::
276 * Validity Checking::
277 * Style Checking::
278 * Run-Time Checks::
279 * Using gcc for Syntax Checking::
280 * Using gcc for Semantic Checking::
281 * Compiling Different Versions of Ada::
282 * Character Set Control::
283 * File Naming Control::
284 * Subprogram Inlining Control::
285 * Auxiliary Output Control::
286 * Debugging Control::
287 * Exception Handling Control::
288 * Units to Sources Mapping Files::
289 * Integrated Preprocessing::
290 @ifset vms
291 * Return Codes::
292 @end ifset
294 Binding Ada Programs With gnatbind
296 * Running gnatbind::
297 * Switches for gnatbind::
298 * Command-Line Access::
299 * Search Paths for gnatbind::
300 * Examples of gnatbind Usage::
302 Switches for gnatbind
304 * Consistency-Checking Modes::
305 * Binder Error Message Control::
306 * Elaboration Control::
307 * Output Control::
308 * Binding with Non-Ada Main Programs::
309 * Binding Programs with No Main Subprogram::
311 Linking Using gnatlink
313 * Running gnatlink::
314 * Switches for gnatlink::
316 The GNAT Make Program gnatmake
318 * Running gnatmake::
319 * Switches for gnatmake::
320 * Mode Switches for gnatmake::
321 * Notes on the Command Line::
322 * How gnatmake Works::
323 * Examples of gnatmake Usage::
325 Improving Performance
326 * Performance Considerations::
327 * Reducing the Size of Ada Executables with gnatelim::
328 * Reducing the Size of Executables with unused subprogram/data elimination::
330 Performance Considerations
331 * Controlling Run-Time Checks::
332 * Use of Restrictions::
333 * Optimization Levels::
334 * Debugging Optimized Code::
335 * Inlining of Subprograms::
336 * Other Optimization Switches::
337 * Optimization and Strict Aliasing::
338 @ifset vms
339 * Coverage Analysis::
340 @end ifset
342 Reducing the Size of Ada Executables with gnatelim
343 * About gnatelim::
344 * Running gnatelim::
345 * Correcting the List of Eliminate Pragmas::
346 * Making Your Executables Smaller::
347 * Summary of the gnatelim Usage Cycle::
349 Reducing the Size of Executables with unused subprogram/data elimination
350 * About unused subprogram/data elimination::
351 * Compilation options::
353 Renaming Files Using gnatchop
355 * Handling Files with Multiple Units::
356 * Operating gnatchop in Compilation Mode::
357 * Command Line for gnatchop::
358 * Switches for gnatchop::
359 * Examples of gnatchop Usage::
361 Configuration Pragmas
363 * Handling of Configuration Pragmas::
364 * The Configuration Pragmas Files::
366 Handling Arbitrary File Naming Conventions Using gnatname
368 * Arbitrary File Naming Conventions::
369 * Running gnatname::
370 * Switches for gnatname::
371 * Examples of gnatname Usage::
373 GNAT Project Manager
375 * Introduction::
376 * Examples of Project Files::
377 * Project File Syntax::
378 * Objects and Sources in Project Files::
379 * Importing Projects::
380 * Project Extension::
381 * Project Hierarchy Extension::
382 * External References in Project Files::
383 * Packages in Project Files::
384 * Variables from Imported Projects::
385 * Naming Schemes::
386 * Library Projects::
387 * Stand-alone Library Projects::
388 * Switches Related to Project Files::
389 * Tools Supporting Project Files::
390 * An Extended Example::
391 * 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::
402 The GNAT Pretty-Printer gnatpp
404 * Switches for gnatpp::
405 * Formatting Rules::
407 The GNAT Metrics Tool gnatmetric
409 * Switches for gnatmetric::
411 File Name Krunching Using gnatkr
413 * About gnatkr::
414 * Using gnatkr::
415 * Krunching Method::
416 * Examples of gnatkr Usage::
418 Preprocessing Using gnatprep
420 * Using gnatprep::
421 * Switches for gnatprep::
422 * Form of Definitions File::
423 * Form of Input Text for gnatprep::
425 @ifset vms
426 The GNAT Run-Time Library Builder gnatlbr
428 * Running gnatlbr::
429 * Switches for gnatlbr::
430 * Examples of gnatlbr Usage::
431 @end ifset
433 The GNAT Library Browser gnatls
435 * Running gnatls::
436 * Switches for gnatls::
437 * Examples of gnatls Usage::
439 Cleaning Up Using gnatclean
441 * Running gnatclean::
442 * Switches for gnatclean::
443 @c * Examples of gnatclean Usage::
445 @ifclear vms
447 GNAT and Libraries
449 * Introduction to Libraries in GNAT::
450 * General Ada Libraries::
451 * Stand-alone Ada Libraries::
452 * Rebuilding the GNAT Run-Time Library::
454 Using the GNU make Utility
456 * Using gnatmake in a Makefile::
457 * Automatically Creating a List of Directories::
458 * Generating the Command Line Switches::
459 * Overcoming Command Line Length Limits::
460 @end ifclear
462 Memory Management Issues
464 * Some Useful Memory Pools::
465 * The GNAT Debug Pool Facility::
466 @ifclear vms
467 * The gnatmem Tool::
468 @end ifclear
470 Stack Related Facilities
472 * Stack Overflow Checking::
473 * Static Stack Usage Analysis::
474 * Dynamic Stack Usage Analysis::
476 Some Useful Memory Pools
478 The GNAT Debug Pool Facility
480 @ifclear vms
481 The gnatmem Tool
483 * Running gnatmem::
484 * Switches for gnatmem::
485 * Example of gnatmem Usage::
486 @end ifclear
488 Verifying properties using gnatcheck
490 * Format of the Report File::
491 * General gnatcheck Switches::
492 * gnatcheck Rule Options::
493 * Add the Results of Compiler Checks to gnatcheck Output::
495  Sample Bodies Using gnatstub
497 * Running gnatstub::
498 * Switches for gnatstub::
500 Other Utility Programs
502 * Using Other Utility Programs with GNAT::
503 * The External Symbol Naming Scheme of GNAT::
504 @ifclear vms
505 * Ada Mode for Glide::
506 @end ifclear
507 * Converting Ada Files to html with gnathtml::
509 Running and Debugging Ada Programs
511 * The GNAT Debugger GDB::
512 * Running GDB::
513 * Introduction to GDB Commands::
514 * Using Ada Expressions::
515 * Calling User-Defined Subprograms::
516 * Using the Next Command in a Function::
517 * Ada Exceptions::
518 * Ada Tasks::
519 * Debugging Generic Units::
520 * GNAT Abnormal Termination or Failure to Terminate::
521 * Naming Conventions for GNAT Source Files::
522 * Getting Internal Debugging Information::
523 * Stack Traceback::
525 @ifset vms
526 * LSE::
527 @end ifset
529 @ifset vms
530 Compatibility with HP Ada
532 * Ada 95 Compatibility::
533 * Differences in the Definition of Package System::
534 * Language-Related Features::
535 * The Package STANDARD::
536 * The Package SYSTEM::
537 * Tasking and Task-Related Features::
538 * Pragmas and Pragma-Related Features::
539 * Library of Predefined Units::
540 * Bindings::
541 * Main Program Definition::
542 * Implementation-Defined Attributes::
543 * Compiler and Run-Time Interfacing::
544 * Program Compilation and Library Management::
545 * Input-Output::
546 * Implementation Limits::
547 * Tools and Utilities::
549 Language-Related Features
551 * Integer Types and Representations::
552 * Floating-Point Types and Representations::
553 * Pragmas Float_Representation and Long_Float::
554 * Fixed-Point Types and Representations::
555 * Record and Array Component Alignment::
556 * Address Clauses::
557 * Other Representation Clauses::
559 Tasking and Task-Related Features
561 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
562 * Assigning Task IDs::
563 * Task IDs and Delays::
564 * Task-Related Pragmas::
565 * Scheduling and Task Priority::
566 * The Task Stack::
567 * External Interrupts::
569 Pragmas and Pragma-Related Features
571 * Restrictions on the Pragma INLINE::
572 * Restrictions on the Pragma INTERFACE::
573 * Restrictions on the Pragma SYSTEM_NAME::
575 Library of Predefined Units
577 * Changes to DECLIB::
579 Bindings
581 * Shared Libraries and Options Files::
582 * Interfaces to C::
583 @end ifset
585 Platform-Specific Information for the Run-Time Libraries
587 * Summary of Run-Time Configurations::
588 * Specifying a Run-Time Library::
589 * Choosing the Scheduling Policy::
590 * Solaris-Specific Considerations::
591 * Linux-Specific Considerations::
592 * AIX-Specific Considerations::
594 Example of Binder Output File
596 Elaboration Order Handling in GNAT
598 * Elaboration Code in Ada 95::
599 * Checking the Elaboration Order in Ada 95::
600 * Controlling the Elaboration Order in Ada 95::
601 * Controlling Elaboration in GNAT - Internal Calls::
602 * Controlling Elaboration in GNAT - External Calls::
603 * Default Behavior in GNAT - Ensuring Safety::
604 * Treatment of Pragma Elaborate::
605 * Elaboration Issues for Library Tasks::
606 * Mixing Elaboration Models::
607 * What to Do If the Default Elaboration Behavior Fails::
608 * Elaboration for Access-to-Subprogram Values::
609 * Summary of Procedures for Elaboration Control::
610 * Other Elaboration Order Considerations::
612 Inline Assembler
614 * Basic Assembler Syntax::
615 * A Simple Example of Inline Assembler::
616 * Output Variables in Inline Assembler::
617 * Input Variables in Inline Assembler::
618 * Inlining Inline Assembler Code::
619 * Other Asm Functionality::
621 Compatibility and Porting Guide
623 * Compatibility with Ada 83::
624 * Implementation-dependent characteristics::
625 @ifclear vms
626 @c This brief section is only in the non-VMS version
627 @c The complete chapter on HP Ada issues is in the VMS version
628 * Compatibility with HP Ada 83::
629 @end ifclear
630 * Compatibility with Other Ada 95 Systems::
631 * Representation Clauses::
632 @ifset vms
633 * Transitioning from Alpha to I64 OpenVMS::
634 @end ifset
636 @ifset unw
637 Microsoft Windows Topics
639 * Using GNAT on Windows::
640 * CONSOLE and WINDOWS subsystems::
641 * Temporary Files::
642 * Mixed-Language Programming on Windows::
643 * Windows Calling Conventions::
644 * Introduction to Dynamic Link Libraries (DLLs)::
645 * Using DLLs with GNAT::
646 * Building DLLs with GNAT::
647 * GNAT and Windows Resources::
648 * Debugging a DLL::
649 * Setting Stack Size from gnatlink::
650 * Setting Heap Size from gnatlink::
651 @end ifset
653 * Index::
654 @end menu
655 @end ifnottex
657 @node About This Guide
658 @unnumbered About This Guide
660 @noindent
661 @ifset vms
662 This guide describes the use of @value{EDITION},
663 a full language compiler for the Ada
664 95 programming language, implemented on OpenVMS for HP's Alpha and
665 Integrity server (I64) platforms.
666 @end ifset
667 @ifclear vms
668 This guide describes the use of @value{EDITION},
669 a compiler and software development
670 toolset for the full Ada 95 programming language.
671 @end ifclear
672 It describes the features of the compiler and tools, and details
673 how to use them to build Ada 95 applications.
675 @ifset PROEDITION
676 For ease of exposition, ``GNAT Pro'' will be referred to simply as
677 ``GNAT'' in the remainder of this document.
678 @end ifset
680 @menu
681 * What This Guide Contains::
682 * What You Should Know before Reading This Guide::
683 * Related Information::
684 * Conventions::
685 @end menu
687 @node What This Guide Contains
688 @unnumberedsec What This Guide Contains
690 @noindent
691 This guide contains the following chapters:
692 @itemize @bullet
694 @item
695 @ref{Getting Started with GNAT}, describes how to get started compiling
696 and running Ada programs with the GNAT Ada programming environment.
697 @item
698 @ref{The GNAT Compilation Model}, describes the compilation model used
699 by GNAT.
701 @item
702 @ref{Compiling Using gcc}, describes how to compile
703 Ada programs with @command{gcc}, the Ada compiler.
705 @item
706 @ref{Binding Using gnatbind}, describes how to
707 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
708 utility.
710 @item
711 @ref{Linking Using gnatlink},
712 describes @command{gnatlink}, a
713 program that provides for linking using the GNAT run-time library to
714 construct a program. @command{gnatlink} can also incorporate foreign language
715 object units into the executable.
717 @item
718 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
719 utility that automatically determines the set of sources
720 needed by an Ada compilation unit, and executes the necessary compilations
721 binding and link.
723 @item
724 @ref{Improving Performance}, shows various techniques for making your
725 Ada program run faster or take less space.
726 It discusses the effect of the compiler's optimization switch and
727 also describes the @command{gnatelim} tool and unused subprogram/data
728 elimination.
730 @item
731 @ref{Renaming Files Using gnatchop}, describes
732 @code{gnatchop}, a utility that allows you to preprocess a file that
733 contains Ada source code, and split it into one or more new files, one
734 for each compilation unit.
736 @item
737 @ref{Configuration Pragmas}, describes the configuration pragmas
738 handled by GNAT.
740 @item
741 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
742 shows how to override the default GNAT file naming conventions,
743 either for an individual unit or globally.
745 @item
746 @ref{GNAT Project Manager}, describes how to use project files
747 to organize large projects.
749 @item
750 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
751 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
752 way to navigate through sources.
754 @item
755 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
756 version of an Ada source file with control over casing, indentation,
757 comment placement, and other elements of program presentation style.
759 @item
760 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
761 metrics for an Ada source file, such as the number of types and subprograms,
762 and assorted complexity measures.
764 @item
765 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
766 file name krunching utility, used to handle shortened
767 file names on operating systems with a limit on the length of names.
769 @item
770 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
771 preprocessor utility that allows a single source file to be used to
772 generate multiple or parameterized source files, by means of macro
773 substitution.
775 @ifset vms
776 @item
777 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
778 a tool for rebuilding the GNAT run time with user-supplied
779 configuration pragmas.
780 @end ifset
782 @item
783 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
784 utility that displays information about compiled units, including dependences
785 on the corresponding sources files, and consistency of compilations.
787 @item
788 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
789 to delete files that are produced by the compiler, binder and linker.
791 @ifclear vms
792 @item
793 @ref{GNAT and Libraries}, describes the process of creating and using
794 Libraries with GNAT. It also describes how to recompile the GNAT run-time
795 library.
797 @item
798 @ref{Using the GNU make Utility}, describes some techniques for using
799 the GNAT toolset in Makefiles.
800 @end ifclear
802 @item
803 @ref{Memory Management Issues}, describes some useful predefined storage pools
804 and in particular the GNAT Debug Pool facility, which helps detect incorrect
805 memory references.
806 @ifclear vms
807 It also describes @command{gnatmem}, a utility that monitors dynamic
808 allocation and deallocation and helps detect ``memory leaks''.
809 @end ifclear
811 @item
812 @ref{Stack Related Facilities}, describes some useful tools associated with
813 stack checking and analysis.
815 @item
816 @ref{Verifying properties using gnatcheck}, discusses @code{gnatcheck},
817 a utility that checks Ada code against a set of rules.
819 @item
820 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
821 a utility that generates empty but compilable bodies for library units.
823 @item
824 @ref{Other Utility Programs}, discusses several other GNAT utilities,
825 including @code{gnathtml}.
827 @item
828 @ref{Running and Debugging Ada Programs}, describes how to run and debug
829 Ada programs.
831 @ifset vms
832 @item
833 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
834 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
835 developed by Digital Equipment Corporation and currently supported by HP.}
836 for OpenVMS Alpha. This product was formerly known as DEC Ada,
837 @cindex DEC Ada
838 and for
839 historical compatibility reasons, the relevant libraries still use the
840 DEC prefix.
841 @end ifset
843 @item
844 @ref{Platform-Specific Information for the Run-Time Libraries},
845 describes the various run-time
846 libraries supported by GNAT on various platforms and explains how to
847 choose a particular library.
849 @item
850 @ref{Example of Binder Output File}, shows the source code for the binder
851 output file for a sample program.
853 @item
854 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
855 you deal with elaboration order issues.
857 @item
858 @ref{Inline Assembler}, shows how to use the inline assembly facility
859 in an Ada program.
861 @item
862 @ref{Compatibility and Porting Guide}, includes sections on compatibility
863 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
864 in porting code from other environments.
866 @ifset unw
867 @item
868 @ref{Microsoft Windows Topics}, presents information relevant to the
869 Microsoft Windows platform.
870 @end ifset
871 @end itemize
873 @c *************************************************
874 @node What You Should Know before Reading This Guide
875 @c *************************************************
876 @unnumberedsec What You Should Know before Reading This Guide
878 @cindex Ada 95 Language Reference Manual
879 @noindent
880 This user's guide assumes that you are familiar with Ada 95 language, as
881 described in the International Standard ANSI/ISO/IEC-8652:1995, January
882 1995.
884 @node Related Information
885 @unnumberedsec Related Information
887 @noindent
888 For further information about related tools, refer to the following
889 documents:
891 @itemize @bullet
892 @item
893 @cite{GNAT Reference Manual}, which contains all reference
894 material for the GNAT implementation of Ada 95.
896 @ifset unw
897 @item
898 @cite{Using the GNAT Programming System}, which describes the GPS
899 integrated development environment.
901 @item
902 @cite{GNAT Programming System Tutorial}, which introduces the
903 main GPS features through examples.
904 @end ifset
906 @item
907 @cite{Ada 95 Language Reference Manual}, which contains all reference
908 material for the Ada 95 programming language.
910 @item
911 @cite{Debugging with GDB}
912 @ifset vms
913 , located in the GNU:[DOCS] directory,
914 @end ifset
915 contains all details on the use of the GNU source-level debugger.
917 @item
918 @cite{GNU Emacs Manual}
919 @ifset vms
920 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
921 @end ifset
922 contains full information on the extensible editor and programming
923 environment Emacs.
925 @end itemize
927 @c **************
928 @node Conventions
929 @unnumberedsec Conventions
930 @cindex Conventions
931 @cindex Typographical conventions
933 @noindent
934 Following are examples of the typographical and graphic conventions used
935 in this guide:
937 @itemize @bullet
938 @item
939 @code{Functions}, @code{utility program names}, @code{standard names},
940 and @code{classes}.
942 @item
943 @samp{Option flags}
945 @item
946 @file{File Names}, @file{button names}, and @file{field names}.
948 @item
949 @var{Variables}.
951 @item
952 @emph{Emphasis}.
954 @item
955 [optional information or parameters]
957 @item
958 Examples are described by text
959 @smallexample
960 and then shown this way.
961 @end smallexample
962 @end itemize
964 @noindent
965 Commands that are entered by the user are preceded in this manual by the
966 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
967 uses this sequence as a prompt, then the commands will appear exactly as
968 you see them in the manual. If your system uses some other prompt, then
969 the command will appear with the @code{$} replaced by whatever prompt
970 character you are using.
972 @ifset unw
973 Full file names are shown with the ``@code{/}'' character
974 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
975 If you are using GNAT on a Windows platform, please note that
976 the ``@code{\}'' character should be used instead.
977 @end ifset
979 @c ****************************
980 @node Getting Started with GNAT
981 @chapter Getting Started with GNAT
983 @noindent
984 This chapter describes some simple ways of using GNAT to build
985 executable Ada programs.
986 @ifset unw
987 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
988 show how to use the command line environment.
989 @ref{Introduction to Glide and GVD}, provides a brief
990 introduction to the visually-oriented IDE for GNAT.
991 Supplementing Glide on some platforms is GPS, the
992 GNAT Programming System, which offers a richer graphical
993 ``look and feel'', enhanced configurability, support for
994 development in other programming language, comprehensive
995 browsing features, and many other capabilities.
996 For information on GPS please refer to
997 @cite{Using the GNAT Programming System}.
998 @end ifset
1000 @menu
1001 * Running GNAT::
1002 * Running a Simple Ada Program::
1003 * Running a Program with Multiple Units::
1004 * Using the gnatmake Utility::
1005 @ifset vms
1006 * Editing with Emacs::
1007 @end ifset
1008 @ifclear vms
1009 * Introduction to GPS::
1010 * Introduction to Glide and GVD::
1011 @end ifclear
1012 @end menu
1014 @node Running GNAT
1015 @section Running GNAT
1017 @noindent
1018 Three steps are needed to create an executable file from an Ada source
1019 file:
1021 @enumerate
1022 @item
1023 The source file(s) must be compiled.
1024 @item
1025 The file(s) must be bound using the GNAT binder.
1026 @item
1027 All appropriate object files must be linked to produce an executable.
1028 @end enumerate
1030 @noindent
1031 All three steps are most commonly handled by using the @command{gnatmake}
1032 utility program that, given the name of the main program, automatically
1033 performs the necessary compilation, binding and linking steps.
1035 @node Running a Simple Ada Program
1036 @section Running a Simple Ada Program
1038 @noindent
1039 Any text editor may be used to prepare an Ada program.
1040 @ifclear vms
1041 If @code{Glide} is
1042 used, the optional Ada mode may be helpful in laying out the program.
1043 @end ifclear
1045 program text is a normal text file. We will suppose in our initial
1046 example that you have used your editor to prepare the following
1047 standard format text file:
1049 @smallexample @c ada
1050 @cartouche
1051 with Ada.Text_IO; use Ada.Text_IO;
1052 procedure Hello is
1053 begin
1054    Put_Line ("Hello WORLD!");
1055 end Hello;
1056 @end cartouche
1057 @end smallexample
1059 @noindent
1060 This file should be named @file{hello.adb}.
1061 With the normal default file naming conventions, GNAT requires
1062 that each file
1063 contain a single compilation unit whose file name is the
1064 unit name,
1065 with periods replaced by hyphens; the
1066 extension is @file{ads} for a
1067 spec and @file{adb} for a body.
1068 You can override this default file naming convention by use of the
1069 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1070 Alternatively, if you want to rename your files according to this default
1071 convention, which is probably more convenient if you will be using GNAT
1072 for all your compilations, then the @code{gnatchop} utility
1073 can be used to generate correctly-named source files
1074 (@pxref{Renaming Files Using gnatchop}).
1076 You can compile the program using the following command (@code{$} is used
1077 as the command prompt in the examples in this document):
1079 @smallexample
1080 $ gcc -c hello.adb
1081 @end smallexample
1083 @noindent
1084 @command{gcc} is the command used to run the compiler. This compiler is
1085 capable of compiling programs in several languages, including Ada 95 and
1086 C. It assumes that you have given it an Ada program if the file extension is
1087 either @file{.ads} or @file{.adb}, and it will then call
1088 the GNAT compiler to compile the specified file.
1090 @ifclear vms
1091 The @option{-c} switch is required. It tells @command{gcc} to only do a
1092 compilation. (For C programs, @command{gcc} can also do linking, but this
1093 capability is not used directly for Ada programs, so the @option{-c}
1094 switch must always be present.)
1095 @end ifclear
1097 This compile command generates a file
1098 @file{hello.o}, which is the object
1099 file corresponding to your Ada program. It also generates
1100 an ``Ada Library Information'' file @file{hello.ali},
1101 which contains additional information used to check
1102 that an Ada program is consistent.
1103 To build an executable file,
1104 use @code{gnatbind} to bind the program
1105 and @command{gnatlink} to link it. The
1106 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1107 @file{ALI} file, but the default extension of @file{.ali} can
1108 be omitted. This means that in the most common case, the argument
1109 is simply the name of the main program:
1111 @smallexample
1112 $ gnatbind hello
1113 $ gnatlink hello
1114 @end smallexample
1116 @noindent
1117 A simpler method of carrying out these steps is to use
1118 @command{gnatmake},
1119 a master program that invokes all the required
1120 compilation, binding and linking tools in the correct order. In particular,
1121 @command{gnatmake} automatically recompiles any sources that have been
1122 modified since they were last compiled, or sources that depend
1123 on such modified sources, so that ``version skew'' is avoided.
1124 @cindex Version skew (avoided by @command{gnatmake})
1126 @smallexample
1127 $ gnatmake hello.adb
1128 @end smallexample
1130 @noindent
1131 The result is an executable program called @file{hello}, which can be
1132 run by entering:
1134 @smallexample
1135 $ ^hello^RUN HELLO^
1136 @end smallexample
1138 @noindent
1139 assuming that the current directory is on the search path
1140 for executable programs.
1142 @noindent
1143 and, if all has gone well, you will see
1145 @smallexample
1146 Hello WORLD!
1147 @end smallexample
1149 @noindent
1150 appear in response to this command.
1152 @c ****************************************
1153 @node Running a Program with Multiple Units
1154 @section Running a Program with Multiple Units
1156 @noindent
1157 Consider a slightly more complicated example that has three files: a
1158 main program, and the spec and body of a package:
1160 @smallexample @c ada
1161 @cartouche
1162 @group
1163 package Greetings is
1164    procedure Hello;
1165    procedure Goodbye;
1166 end Greetings;
1168 with Ada.Text_IO; use Ada.Text_IO;
1169 package body Greetings is
1170    procedure Hello is
1171    begin
1172       Put_Line ("Hello WORLD!");
1173    end Hello;
1175    procedure Goodbye is
1176    begin
1177       Put_Line ("Goodbye WORLD!");
1178    end Goodbye;
1179 end Greetings;
1180 @end group
1182 @group
1183 with Greetings;
1184 procedure Gmain is
1185 begin
1186    Greetings.Hello;
1187    Greetings.Goodbye;
1188 end Gmain;
1189 @end group
1190 @end cartouche
1191 @end smallexample
1193 @noindent
1194 Following the one-unit-per-file rule, place this program in the
1195 following three separate files:
1197 @table @file
1198 @item greetings.ads
1199 spec of package @code{Greetings}
1201 @item greetings.adb
1202 body of package @code{Greetings}
1204 @item gmain.adb
1205 body of main program
1206 @end table
1208 @noindent
1209 To build an executable version of
1210 this program, we could use four separate steps to compile, bind, and link
1211 the program, as follows:
1213 @smallexample
1214 $ gcc -c gmain.adb
1215 $ gcc -c greetings.adb
1216 $ gnatbind gmain
1217 $ gnatlink gmain
1218 @end smallexample
1220 @noindent
1221 Note that there is no required order of compilation when using GNAT.
1222 In particular it is perfectly fine to compile the main program first.
1223 Also, it is not necessary to compile package specs in the case where
1224 there is an accompanying body; you only need to compile the body. If you want
1225 to submit these files to the compiler for semantic checking and not code
1226 generation, then use the
1227 @option{-gnatc} switch:
1229 @smallexample
1230 $ gcc -c greetings.ads -gnatc
1231 @end smallexample
1233 @noindent
1234 Although the compilation can be done in separate steps as in the
1235 above example, in practice it is almost always more convenient
1236 to use the @command{gnatmake} tool. All you need to know in this case
1237 is the name of the main program's source file. The effect of the above four
1238 commands can be achieved with a single one:
1240 @smallexample
1241 $ gnatmake gmain.adb
1242 @end smallexample
1244 @noindent
1245 In the next section we discuss the advantages of using @command{gnatmake} in
1246 more detail.
1248 @c *****************************
1249 @node Using the gnatmake Utility
1250 @section Using the @command{gnatmake} Utility
1252 @noindent
1253 If you work on a program by compiling single components at a time using
1254 @command{gcc}, you typically keep track of the units you modify. In order to
1255 build a consistent system, you compile not only these units, but also any
1256 units that depend on the units you have modified.
1257 For example, in the preceding case,
1258 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1259 you edit @file{greetings.ads}, you must recompile both
1260 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1261 units that depend on @file{greetings.ads}.
1263 @code{gnatbind} will warn you if you forget one of these compilation
1264 steps, so that it is impossible to generate an inconsistent program as a
1265 result of forgetting to do a compilation. Nevertheless it is tedious and
1266 error-prone to keep track of dependencies among units.
1267 One approach to handle the dependency-bookkeeping is to use a
1268 makefile. However, makefiles present maintenance problems of their own:
1269 if the dependencies change as you change the program, you must make
1270 sure that the makefile is kept up-to-date manually, which is also an
1271 error-prone process.
1273 The @command{gnatmake} utility takes care of these details automatically.
1274 Invoke it using either one of the following forms:
1276 @smallexample
1277 $ gnatmake gmain.adb
1278 $ gnatmake ^gmain^GMAIN^
1279 @end smallexample
1281 @noindent
1282 The argument is the name of the file containing the main program;
1283 you may omit the extension. @command{gnatmake}
1284 examines the environment, automatically recompiles any files that need
1285 recompiling, and binds and links the resulting set of object files,
1286 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1287 In a large program, it
1288 can be extremely helpful to use @command{gnatmake}, because working out by hand
1289 what needs to be recompiled can be difficult.
1291 Note that @command{gnatmake}
1292 takes into account all the Ada 95 rules that
1293 establish dependencies among units. These include dependencies that result
1294 from inlining subprogram bodies, and from
1295 generic instantiation. Unlike some other
1296 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1297 found by the compiler on a previous compilation, which may possibly
1298 be wrong when sources change. @command{gnatmake} determines the exact set of
1299 dependencies from scratch each time it is run.
1301 @ifset vms
1302 @node Editing with Emacs
1303 @section Editing with Emacs
1304 @cindex Emacs
1306 @noindent
1307 Emacs is an extensible self-documenting text editor that is available in a
1308 separate VMSINSTAL kit.
1310 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1311 click on the Emacs Help menu and run the Emacs Tutorial.
1312 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1313 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1315 Documentation on Emacs and other tools is available in Emacs under the
1316 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1317 use the middle mouse button to select a topic (e.g. Emacs).
1319 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1320 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1321 get to the Emacs manual.
1322 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1323 prompt.
1325 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1326 which is sufficiently extensible to provide for a complete programming
1327 environment and shell for the sophisticated user.
1328 @end ifset
1330 @ifclear vms
1331 @node Introduction to GPS
1332 @section Introduction to GPS
1333 @cindex GPS (GNAT Programming System)
1334 @cindex GNAT Programming System (GPS)
1335 @noindent
1336 Although the command line interface (@command{gnatmake}, etc.) alone
1337 is sufficient, a graphical Interactive Development
1338 Environment can make it easier for you to compose, navigate, and debug
1339 programs.  This section describes the main features of GPS
1340 (``GNAT Programming System''), the GNAT graphical IDE.
1341 You will see how to use GPS to build and debug an executable, and
1342 you will also learn some of the basics of the GNAT ``project'' facility.
1344 GPS enables you to do much more than is presented here;
1345 e.g., you can produce a call graph, interface to a third-party
1346 Version Control System, and inspect the generated assembly language
1347 for a program.
1348 Indeed, GPS also supports languages other than Ada.
1349 Such additional information, and an explanation of all of the GPS menu
1350 items. may be found in the on-line help, which includes
1351 a user's guide and a tutorial (these are also accessible from the GNAT
1352 startup menu).
1354 @menu
1355 * Building a New Program with GPS::
1356 * Simple Debugging with GPS::
1357 @end menu
1359 @node Building a New Program with GPS
1360 @subsection Building a New Program with GPS
1361 @noindent
1362 GPS invokes the GNAT compilation tools using information
1363 contained in a @emph{project} (also known as a @emph{project file}):
1364 a collection of properties such
1365 as source directories, identities of main subprograms, tool switches, etc.,
1366 and their associated values.
1367 See @ref{GNAT Project Manager} for details.
1368 In order to run GPS, you will need to either create a new project
1369 or else open an existing one.
1371 This section will explain how you can use GPS to create a project,
1372 to associate Ada source files with a project, and to build and run
1373 programs.
1375 @enumerate
1376 @item @emph{Creating a project}
1378 Invoke GPS, either from the command line or the platform's IDE.
1379 After it starts, GPS will display a ``Welcome'' screen with three
1380 radio buttons:
1382 @itemize @bullet
1383 @item
1384 @code{Start with default project in directory}
1386 @item
1387 @code{Create new project with wizard}
1389 @item
1390 @code{Open existing project}
1391 @end itemize
1393 @noindent
1394 Select @code{Create new project with wizard} and press @code{OK}.
1395 A new window will appear.  In the text box labeled with
1396 @code{Enter the name of the project to create}, type @file{sample}
1397 as the project name.
1398 In the next box, browse to choose the directory in which you
1399 would like to create the project file.
1400 After selecting an appropriate directory, press @code{Forward}.
1402 A window will appear with the title
1403 @code{Version Control System Configuration}.
1404 Simply press @code{Forward}.
1406 A window will appear with the title
1407 @code{Please select the source directories for this project}.
1408 The directory that you specified for the project file will be selected
1409 by default as the one to use for sources; simply press @code{Forward}.
1411 A window will appear with the title
1412 @code{Please select the build directory for this project}.
1413 The directory that you specified for the project file will be selected
1414 by default for object files and executables;
1415 simply press @code{Forward}.
1417 A window will appear with the title
1418 @code{Please select the main units for this project}.
1419 You will supply this information later, after creating the source file.
1420 Simply press @code{Forward} for now.
1422 A window will appear with the title
1423 @code{Please select the switches to build the project}.
1424 Press @code{Apply}.  This will create a project file named
1425 @file{sample.prj} in the directory that you had specified.
1427 @item @emph{Creating and saving the source file}
1429 After you create the new project, a GPS window will appear, which is
1430 partitioned into two main sections:
1432 @itemize @bullet
1433 @item
1434 A @emph{Workspace area}, initially greyed out, which you will use for
1435 creating and editing source files
1437 @item
1438 Directly below, a @emph{Messages area}, which initially displays a
1439 ``Welcome'' message.
1440 (If the Messages area is not visible, drag its border upward to expand it.)
1441 @end itemize
1443 @noindent
1444 Select @code{File} on the menu bar, and then the @code{New} command.
1445 The Workspace area will become white, and you can now
1446 enter the source program explicitly.
1447 Type the following text
1449 @smallexample @c ada
1450 @group
1451 with Ada.Text_IO; use Ada.Text_IO;
1452 procedure Hello is
1453 begin
1454   Put_Line("Hello from GPS!");
1455 end Hello;
1456 @end group
1457 @end smallexample
1459 @noindent
1460 Select @code{File}, then @code{Save As}, and enter the source file name
1461 @file{hello.adb}.
1462 The file will be saved in the same directory you specified as the
1463 location of the default project file.
1465 @item @emph{Updating the project file}
1467 You need to add the new source file to the project.
1468 To do this, select
1469 the @code{Project} menu and then @code{Edit project properties}.
1470 Click the @code{Main files} tab on the left, and then the
1471 @code{Add} button.
1472 Choose @file{hello.adb} from the list, and press @code{Open}.
1473 The project settings window will reflect this action.
1474 Click @code{OK}.
1476 @item @emph{Building and running the program}
1478 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1479 and select @file{hello.adb}.
1480 The Messages window will display the resulting invocations of @command{gcc},
1481 @command{gnatbind}, and @command{gnatlink}
1482 (reflecting the default switch settings from the
1483 project file that you created) and then a ``successful compilation/build''
1484 message.
1486 To run the program, choose the @code{Build} menu, then @code{Run}, and
1487 select @command{hello}.
1488 An @emph{Arguments Selection} window will appear.
1489 There are no command line arguments, so just click @code{OK}.
1491 The Messages window will now display the program's output (the string
1492 @code{Hello from GPS}), and at the bottom of the GPS window a status
1493 update is displayed (@code{Run: hello}).
1494 Close the GPS window (or select @code{File}, then @code{Exit}) to
1495 terminate this GPS session.
1496 @end enumerate
1498 @node Simple Debugging with GPS
1499 @subsection Simple Debugging with GPS
1500 @noindent
1501 This section illustrates basic debugging techniques (setting breakpoints,
1502 examining/modifying variables, single stepping).
1504 @enumerate
1505 @item @emph{Opening a project}
1507 Start GPS and select @code{Open existing project}; browse to
1508 specify the project file @file{sample.prj} that you had created in the
1509 earlier example.
1511 @item @emph{Creating a source file}
1513 Select @code{File}, then @code{New}, and type in the following program:
1515 @smallexample @c ada
1516 @group
1517 with Ada.Text_IO; use Ada.Text_IO;
1518 procedure Example is
1519    Line : String (1..80);
1520    N    : Natural;
1521 begin
1522    Put_Line("Type a line of text at each prompt; an empty line to exit");
1523    loop
1524       Put(": ");
1525       Get_Line (Line, N);
1526       Put_Line (Line (1..N) );
1527       exit when N=0;
1528    end loop;
1529 end Example;
1530 @end group
1531 @end smallexample
1533 @noindent
1534 Select @code{File}, then @code{Save as}, and enter the file name
1535 @file{example.adb}.
1537 @item @emph{Updating the project file}
1539 Add @code{Example} as a new main unit for the project:
1540 @enumerate a
1541 @item
1542 Select @code{Project}, then @code{Edit Project Properties}.
1544 @item
1545 Select the @code{Main files} tab, click @code{Add}, then
1546 select the file @file{example.adb} from the list, and
1547 click @code{Open}.
1548 You will see the file name appear in the list of main units
1550 @item
1551 Click @code{OK}
1552 @end enumerate
1554 @item @emph{Building/running the executable}
1556 To build the executable
1557 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1559 Run the program to see its effect (in the Messages area).
1560 Each line that you enter is displayed; an empty line will
1561 cause the loop to exit and the program to terminate.
1563 @item @emph{Debugging the program}
1565 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1566 which are required for debugging, are on by default when you create
1567 a new project.
1568 Thus unless you intentionally remove these settings, you will be able
1569 to debug any program that you develop using GPS.
1571 @enumerate a
1572 @item @emph{Initializing}
1574 Select @code{Debug}, then @code{Initialize}, then @file{example}
1576 @item @emph{Setting a breakpoint}
1578 After performing the initialization step, you will observe a small
1579 icon to the right of each line number.
1580 This serves as a toggle for breakpoints; clicking the icon will
1581 set a breakpoint at the corresponding line (the icon will change to
1582 a red circle with an ``x''), and clicking it again
1583 will remove the breakpoint / reset the icon.
1585 For purposes of this example, set a breakpoint at line 10 (the
1586 statement @code{Put_Line@ (Line@ (1..N));}
1588 @item @emph{Starting program execution}
1590 Select @code{Debug}, then @code{Run}.  When the
1591 @code{Program Arguments} window appears, click @code{OK}.
1592 A console window will appear; enter some line of text,
1593 e.g. @code{abcde}, at the prompt.
1594 The program will pause execution when it gets to the
1595 breakpoint, and the corresponding line is highlighted.
1597 @item @emph{Examining a variable}
1599 Move the mouse over one of the occurrences of the variable @code{N}.
1600 You will see the value (5) displayed, in ``tool tip'' fashion.
1601 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1602 You will see information about @code{N} appear in the @code{Debugger Data}
1603 pane, showing the value as 5.
1605 @item @emph{Assigning a new value to a variable}
1607 Right click on the @code{N} in the @code{Debugger Data} pane, and
1608 select @code{Set value of N}.
1609 When the input window appears, enter the value @code{4} and click
1610 @code{OK}.
1611 This value does not automatically appear in the @code{Debugger Data}
1612 pane; to see it, right click again on the @code{N} in the
1613 @code{Debugger Data} pane and select @code{Update value}.
1614 The new value, 4, will appear in red.
1616 @item @emph{Single stepping}
1618 Select @code{Debug}, then @code{Next}.
1619 This will cause the next statement to be executed, in this case the
1620 call of @code{Put_Line} with the string slice.
1621 Notice in the console window that the displayed string is simply
1622 @code{abcd} and not @code{abcde} which you had entered.
1623 This is because the upper bound of the slice is now 4 rather than 5.
1625 @item @emph{Removing a breakpoint}
1627 Toggle the breakpoint icon at line 10.
1629 @item @emph{Resuming execution from a breakpoint}
1631 Select @code{Debug}, then @code{Continue}.
1632 The program will reach the next iteration of the loop, and
1633 wait for input after displaying the prompt.
1634 This time, just hit the @kbd{Enter} key.
1635 The value of @code{N} will be 0, and the program will terminate.
1636 The console window will disappear.
1637 @end enumerate
1638 @end enumerate
1640 @node Introduction to Glide and GVD
1641 @section Introduction to Glide and GVD
1642 @cindex Glide
1643 @cindex GVD
1644 @noindent
1645 This section describes the main features of Glide,
1646 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1647 the GNU Visual Debugger.
1648 These tools may be present in addition to, or in place of, GPS on some
1649 platforms.
1650 Additional information on Glide and GVD may be found
1651 in the on-line help for these tools.
1653 @menu
1654 * Building a New Program with Glide::
1655 * Simple Debugging with GVD::
1656 * Other Glide Features::
1657 @end menu
1659 @node Building a New Program with Glide
1660 @subsection Building a New Program with Glide
1661 @noindent
1662 The simplest way to invoke Glide is to enter @command{glide}
1663 at the command prompt.  It will generally be useful to issue this
1664 as a background command, thus allowing you to continue using
1665 your command window for other purposes while Glide is running:
1667 @smallexample
1668 $ glide&
1669 @end smallexample
1671 @noindent
1672 Glide will start up with an initial screen displaying the top-level menu items
1673 as well as some other information.  The menu selections are as follows
1674 @itemize @bullet
1675 @item @code{Buffers}
1676 @item @code{Files}
1677 @item @code{Tools}
1678 @item @code{Edit}
1679 @item @code{Search}
1680 @item @code{Mule}
1681 @item @code{Glide}
1682 @item @code{Help}
1683 @end itemize
1685 @noindent
1686 For this introductory example, you will need to create a new Ada source file.
1687 First, select the @code{Files} menu.  This will pop open a menu with around
1688 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1689 Depending on the platform, you may see a pop-up window where you can browse
1690 to an appropriate directory and then enter the file name, or else simply
1691 see a line at the bottom of the Glide window where you can likewise enter
1692 the file name.  Note that in Glide, when you attempt to open a non-existent
1693 file, the effect is to create a file with that name.  For this example enter
1694 @file{hello.adb} as the name of the file.
1696 A new buffer will now appear, occupying the entire Glide window,
1697 with the file name at the top.  The menu selections are slightly different
1698 from the ones you saw on the opening screen; there is an @code{Entities} item,
1699 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1700 the file extension to identify the source language, so @file{adb} indicates
1701 an Ada source file.
1703 You will enter some of the source program lines explicitly,
1704 and use the syntax-oriented template mechanism to enter other lines.
1705 First, type the following text:
1706 @smallexample
1707 with Ada.Text_IO; use Ada.Text_IO;
1708 procedure Hello is
1709 begin
1710 @end smallexample
1712 @noindent
1713 Observe that Glide uses different colors to distinguish reserved words from
1714 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1715 automatically indented in anticipation of declarations.  When you enter
1716 @code{begin}, Glide recognizes that there are no declarations and thus places
1717 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1718 indented, where the statement(s) will be placed.
1720 The main part of the program will be a @code{for} loop.  Instead of entering
1721 the text explicitly, however, use a statement template.  Select the @code{Ada}
1722 item on the top menu bar, move the mouse to the @code{Statements} item,
1723 and you will see a large selection of alternatives.  Choose @code{for loop}.
1724 You will be prompted (at the bottom of the buffer) for a loop name;
1725 simply press the @key{Enter} key since a loop name is not needed.
1726 You should see the beginning of a @code{for} loop appear in the source
1727 program window.  You will now be prompted for the name of the loop variable;
1728 enter a line with the identifier @code{ind} (lower case).  Note that,
1729 by default, Glide capitalizes the name (you can override such behavior
1730 if you wish, although this is outside the scope of this introduction).
1731 Next, Glide prompts you for the loop range; enter a line containing
1732 @code{1..5} and you will see this also appear in the source program,
1733 together with the remaining elements of the @code{for} loop syntax.
1735 Next enter the statement (with an intentional error, a missing semicolon)
1736 that will form the body of the loop:
1737 @smallexample
1738 Put_Line("Hello, World" & Integer'Image(I))
1739 @end smallexample
1741 @noindent
1742 Finally, type @code{end Hello;} as the last line in the program.
1743 Now save the file: choose the @code{File} menu item, and then the
1744 @code{Save buffer} selection.  You will see a message at the bottom
1745 of the buffer confirming that the file has been saved.
1747 You are now ready to attempt to build the program.  Select the @code{Ada}
1748 item from the top menu bar.  Although we could choose simply to compile
1749 the file, we will instead attempt to do a build (which invokes
1750 @command{gnatmake}) since, if the compile is successful, we want to build
1751 an executable.  Thus select @code{Ada build}.  This will fail because of the
1752 compilation error, and you will notice that the Glide window has been split:
1753 the top window contains the source file, and the bottom window contains the
1754 output from the GNAT tools. Glide allows you to navigate from a compilation
1755 error to the source file position corresponding to the error: click the
1756 middle mouse button (or simultaneously press the left and right buttons,
1757 on a two-button mouse) on the diagnostic line in the tool window.  The
1758 focus will shift to the source window, and the cursor will be positioned
1759 on the character at which the error was detected.
1761 Correct the error: type in a semicolon to terminate the statement.
1762 Although you can again save the file explicitly, you can also simply invoke
1763 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1764 This time the build will succeed; the tool output window shows you the
1765 options that are supplied by default.  The GNAT tools' output (e.g.
1766 object and ALI files, executable) will go in the directory from which
1767 Glide was launched.
1769 To execute the program, choose @code{Ada} and then @code{Run}.
1770 You should see the program's output displayed in the bottom window:
1772 @smallexample
1773 Hello, world 1
1774 Hello, world 2
1775 Hello, world 3
1776 Hello, world 4
1777 Hello, world 5
1778 @end smallexample
1780 @node Simple Debugging with GVD
1781 @subsection Simple Debugging with GVD
1783 @noindent
1784 This section describes how to set breakpoints, examine/modify variables,
1785 and step through execution.
1787 In order to enable debugging, you need to pass the @option{-g} switch
1788 to both the compiler and to @command{gnatlink}.  If you are using
1789 the command line, passing @option{-g} to @command{gnatmake} will have
1790 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1791 by issuing the command:
1793 @smallexample
1794 $ gvd hello
1795 @end smallexample
1797 @noindent
1798 If you are using Glide, then @option{-g} is passed to the relevant tools
1799 by default when you do a build.  Start the debugger by selecting the
1800 @code{Ada} menu item, and then @code{Debug}.
1802 GVD comes up in a multi-part window.  One pane shows the names of files
1803 comprising your executable; another pane shows the source code of the current
1804 unit (initially your main subprogram), another pane shows the debugger output
1805 and user interactions, and the fourth pane (the data canvas at the top
1806 of the window) displays data objects that you have selected.
1808 To the left of the source file pane, you will notice green dots adjacent
1809 to some lines.  These are lines for which object code exists and where
1810 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1811 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1812 in a red circle.  Clicking the circle toggles the breakpoint off,
1813 and the red circle is replaced by the green dot.
1815 For this example, set a breakpoint at the statement where @code{Put_Line}
1816 is invoked.
1818 Start program execution by selecting the @code{Run} button on the top menu bar.
1819 (The @code{Start} button will also start your program, but it will
1820 cause program execution to break at the entry to your main subprogram.)
1821 Evidence of reaching the breakpoint will appear: the source file line will be
1822 highlighted, and the debugger interactions pane will display
1823 a relevant message.
1825 You can examine the values of variables in several ways.  Move the mouse
1826 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1827 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1828 and select @code{Display Ind}; a box showing the variable's name and value
1829 will appear in the data canvas.
1831 Although a loop index is a constant with respect to Ada semantics,
1832 you can change its value in the debugger.  Right-click in the box
1833 for @code{Ind}, and select the @code{Set Value of Ind} item.
1834 Enter @code{2} as the new value, and press @command{OK}.
1835 The box for @code{Ind} shows the update.
1837 Press the @code{Step} button on the top menu bar; this will step through
1838 one line of program text (the invocation of @code{Put_Line}), and you can
1839 observe the effect of having modified @code{Ind} since the value displayed
1840 is @code{2}.
1842 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1843 button.  You will see the remaining output lines displayed in the debugger
1844 interaction window, along with a message confirming normal program
1845 termination.
1847 @node Other Glide Features
1848 @subsection Other Glide Features
1850 @noindent
1851 You may have observed that some of the menu selections contain abbreviations;
1852 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1853 These are @emph{shortcut keys} that you can use instead of selecting
1854 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1855 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1856 of selecting @code{Files} and then @code{Open file...}.
1858 To abort a Glide command, type @key{Ctrl-g}.
1860 If you want Glide to start with an existing source file, you can either
1861 launch Glide as above and then open the file via @code{Files} @result{}
1862 @code{Open file...}, or else simply pass the name of the source file
1863 on the command line:
1865 @smallexample
1866 $ glide hello.adb&
1867 @end smallexample
1869 @noindent
1870 While you are using Glide, a number of @emph{buffers} exist.
1871 You create some explicitly; e.g., when you open/create a file.
1872 Others arise as an effect of the commands that you issue; e.g., the buffer
1873 containing the output of the tools invoked during a build.  If a buffer
1874 is hidden, you can bring it into a visible window by first opening
1875 the @code{Buffers} menu and then selecting the desired entry.
1877 If a buffer occupies only part of the Glide screen and you want to expand it
1878 to fill the entire screen, then click in the buffer and then select
1879 @code{Files} @result{} @code{One Window}.
1881 If a window is occupied by one buffer and you want to split the window
1882 to bring up a second buffer, perform the following steps:
1883 @itemize @bullet
1884 @item Select @code{Files} @result{} @code{Split Window};
1885 this will produce two windows each of which holds the original buffer
1886 (these are not copies, but rather different views of the same buffer contents)
1888 @item With the focus in one of the windows,
1889 select the desired buffer from the @code{Buffers} menu
1890 @end itemize
1892 @noindent
1893 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1894 @end ifclear
1896 @node The GNAT Compilation Model
1897 @chapter The GNAT Compilation Model
1898 @cindex GNAT compilation model
1899 @cindex Compilation model
1901 @menu
1902 * Source Representation::
1903 * Foreign Language Representation::
1904 * File Naming Rules::
1905 * Using Other File Names::
1906 * Alternative File Naming Schemes::
1907 * Generating Object Files::
1908 * Source Dependencies::
1909 * The Ada Library Information Files::
1910 * Binding an Ada Program::
1911 * Mixed Language Programming::
1912 @ifclear vms
1913 * Building Mixed Ada & C++ Programs::
1914 * Comparison between GNAT and C/C++ Compilation Models::
1915 @end ifclear
1916 * Comparison between GNAT and Conventional Ada Library Models::
1917 @ifset vms
1918 * Placement of temporary files::
1919 @end ifset
1920 @end menu
1922 @noindent
1923 This chapter describes the compilation model used by GNAT. Although
1924 similar to that used by other languages, such as C and C++, this model
1925 is substantially different from the traditional Ada compilation models,
1926 which are based on a library. The model is initially described without
1927 reference to the library-based model. If you have not previously used an
1928 Ada compiler, you need only read the first part of this chapter. The
1929 last section describes and discusses the differences between the GNAT
1930 model and the traditional Ada compiler models. If you have used other
1931 Ada compilers, this section will help you to understand those
1932 differences, and the advantages of the GNAT model.
1934 @node Source Representation
1935 @section Source Representation
1936 @cindex Latin-1
1938 @noindent
1939 Ada source programs are represented in standard text files, using
1940 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1941 7-bit ASCII set, plus additional characters used for
1942 representing foreign languages (@pxref{Foreign Language Representation}
1943 for support of non-USA character sets). The format effector characters
1944 are represented using their standard ASCII encodings, as follows:
1946 @table @code
1947 @item VT
1948 @findex VT
1949 Vertical tab, @code{16#0B#}
1951 @item HT
1952 @findex HT
1953 Horizontal tab, @code{16#09#}
1955 @item CR
1956 @findex CR
1957 Carriage return, @code{16#0D#}
1959 @item LF
1960 @findex LF
1961 Line feed, @code{16#0A#}
1963 @item FF
1964 @findex FF
1965 Form feed, @code{16#0C#}
1966 @end table
1968 @noindent
1969 Source files are in standard text file format. In addition, GNAT will
1970 recognize a wide variety of stream formats, in which the end of
1971 physical lines is marked by any of the following sequences:
1972 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1973 in accommodating files that are imported from other operating systems.
1975 @cindex End of source file
1976 @cindex Source file, end
1977 @findex SUB
1978 The end of a source file is normally represented by the physical end of
1979 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1980 recognized as signalling the end of the source file. Again, this is
1981 provided for compatibility with other operating systems where this
1982 code is used to represent the end of file.
1984 Each file contains a single Ada compilation unit, including any pragmas
1985 associated with the unit. For example, this means you must place a
1986 package declaration (a package @dfn{spec}) and the corresponding body in
1987 separate files. An Ada @dfn{compilation} (which is a sequence of
1988 compilation units) is represented using a sequence of files. Similarly,
1989 you will place each subunit or child unit in a separate file.
1991 @node Foreign Language Representation
1992 @section Foreign Language Representation
1994 @noindent
1995 GNAT supports the standard character sets defined in Ada 95 as well as
1996 several other non-standard character sets for use in localized versions
1997 of the compiler (@pxref{Character Set Control}).
1998 @menu
1999 * Latin-1::
2000 * Other 8-Bit Codes::
2001 * Wide Character Encodings::
2002 @end menu
2004 @node Latin-1
2005 @subsection Latin-1
2006 @cindex Latin-1
2008 @noindent
2009 The basic character set is Latin-1. This character set is defined by ISO
2010 standard 8859, part 1. The lower half (character codes @code{16#00#}
2011 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
2012 is used to represent additional characters. These include extended letters
2013 used by European languages, such as French accents, the vowels with umlauts
2014 used in German, and the extra letter A-ring used in Swedish.
2016 @findex Ada.Characters.Latin_1
2017 For a complete list of Latin-1 codes and their encodings, see the source
2018 file of library unit @code{Ada.Characters.Latin_1} in file
2019 @file{a-chlat1.ads}.
2020 You may use any of these extended characters freely in character or
2021 string literals. In addition, the extended characters that represent
2022 letters can be used in identifiers.
2024 @node Other 8-Bit Codes
2025 @subsection Other 8-Bit Codes
2027 @noindent
2028 GNAT also supports several other 8-bit coding schemes:
2030 @table @asis
2031 @item ISO 8859-2 (Latin-2)
2032 @cindex Latin-2
2033 @cindex ISO 8859-2
2034 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2035 equivalence.
2037 @item ISO 8859-3 (Latin-3)
2038 @cindex Latin-3
2039 @cindex ISO 8859-3
2040 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2041 equivalence.
2043 @item ISO 8859-4 (Latin-4)
2044 @cindex Latin-4
2045 @cindex ISO 8859-4
2046 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2047 equivalence.
2049 @item ISO 8859-5 (Cyrillic)
2050 @cindex ISO 8859-5
2051 @cindex Cyrillic
2052 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2053 lowercase equivalence.
2055 @item ISO 8859-15 (Latin-9)
2056 @cindex ISO 8859-15
2057 @cindex Latin-9
2058 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2059 lowercase equivalence
2061 @item IBM PC (code page 437)
2062 @cindex code page 437
2063 This code page is the normal default for PCs in the U.S. It corresponds
2064 to the original IBM PC character set. This set has some, but not all, of
2065 the extended Latin-1 letters, but these letters do not have the same
2066 encoding as Latin-1. In this mode, these letters are allowed in
2067 identifiers with uppercase and lowercase equivalence.
2069 @item IBM PC (code page 850)
2070 @cindex code page 850
2071 This code page is a modification of 437 extended to include all the
2072 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2073 mode, all these letters are allowed in identifiers with uppercase and
2074 lowercase equivalence.
2076 @item Full Upper 8-bit
2077 Any character in the range 80-FF allowed in identifiers, and all are
2078 considered distinct. In other words, there are no uppercase and lowercase
2079 equivalences in this range. This is useful in conjunction with
2080 certain encoding schemes used for some foreign character sets (e.g.
2081 the typical method of representing Chinese characters on the PC).
2083 @item No Upper-Half
2084 No upper-half characters in the range 80-FF are allowed in identifiers.
2085 This gives Ada 83 compatibility for identifier names.
2086 @end table
2088 @noindent
2089 For precise data on the encodings permitted, and the uppercase and lowercase
2090 equivalences that are recognized, see the file @file{csets.adb} in
2091 the GNAT compiler sources. You will need to obtain a full source release
2092 of GNAT to obtain this file.
2094 @node Wide Character Encodings
2095 @subsection Wide Character Encodings
2097 @noindent
2098 GNAT allows wide character codes to appear in character and string
2099 literals, and also optionally in identifiers, by means of the following
2100 possible encoding schemes:
2102 @table @asis
2104 @item Hex Coding
2105 In this encoding, a wide character is represented by the following five
2106 character sequence:
2108 @smallexample
2109 ESC a b c d
2110 @end smallexample
2112 @noindent
2113 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2114 characters (using uppercase letters) of the wide character code. For
2115 example, ESC A345 is used to represent the wide character with code
2116 @code{16#A345#}.
2117 This scheme is compatible with use of the full Wide_Character set.
2119 @item Upper-Half Coding
2120 @cindex Upper-Half Coding
2121 The wide character with encoding @code{16#abcd#} where the upper bit is on
2122 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2123 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2124 character, but is not required to be in the upper half. This method can
2125 be also used for shift-JIS or EUC, where the internal coding matches the
2126 external coding.
2128 @item Shift JIS Coding
2129 @cindex Shift JIS Coding
2130 A wide character is represented by a two-character sequence,
2131 @code{16#ab#} and
2132 @code{16#cd#}, with the restrictions described for upper-half encoding as
2133 described above. The internal character code is the corresponding JIS
2134 character according to the standard algorithm for Shift-JIS
2135 conversion. Only characters defined in the JIS code set table can be
2136 used with this encoding method.
2138 @item EUC Coding
2139 @cindex EUC Coding
2140 A wide character is represented by a two-character sequence
2141 @code{16#ab#} and
2142 @code{16#cd#}, with both characters being in the upper half. The internal
2143 character code is the corresponding JIS character according to the EUC
2144 encoding algorithm. Only characters defined in the JIS code set table
2145 can be used with this encoding method.
2147 @item UTF-8 Coding
2148 A wide character is represented using
2149 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2150 10646-1/Am.2. Depending on the character value, the representation
2151 is a one, two, or three byte sequence:
2152 @smallexample
2153 @iftex
2154 @leftskip=.7cm
2155 @end iftex
2156 16#0000#-16#007f#: 2#0xxxxxxx#
2157 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2158 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2160 @end smallexample
2162 @noindent
2163 where the xxx bits correspond to the left-padded bits of the
2164 16-bit character value. Note that all lower half ASCII characters
2165 are represented as ASCII bytes and all upper half characters and
2166 other wide characters are represented as sequences of upper-half
2167 (The full UTF-8 scheme allows for encoding 31-bit characters as
2168 6-byte sequences, but in this implementation, all UTF-8 sequences
2169 of four or more bytes length will be treated as illegal).
2170 @item Brackets Coding
2171 In this encoding, a wide character is represented by the following eight
2172 character sequence:
2174 @smallexample
2175 [ " a b c d " ]
2176 @end smallexample
2178 @noindent
2179 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2180 characters (using uppercase letters) of the wide character code. For
2181 example, [``A345''] is used to represent the wide character with code
2182 @code{16#A345#}. It is also possible (though not required) to use the
2183 Brackets coding for upper half characters. For example, the code
2184 @code{16#A3#} can be represented as @code{[``A3'']}.
2186 This scheme is compatible with use of the full Wide_Character set,
2187 and is also the method used for wide character encoding in the standard
2188 ACVC (Ada Compiler Validation Capability) test suite distributions.
2190 @end table
2192 @noindent
2193 Note: Some of these coding schemes do not permit the full use of the
2194 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2195 use of the upper half of the Latin-1 set.
2197 @node File Naming Rules
2198 @section File Naming Rules
2200 @noindent
2201 The default file name is determined by the name of the unit that the
2202 file contains. The name is formed by taking the full expanded name of
2203 the unit and replacing the separating dots with hyphens and using
2204 ^lowercase^uppercase^ for all letters.
2206 An exception arises if the file name generated by the above rules starts
2207 with one of the characters
2208 @ifset vms
2209 A,G,I, or S,
2210 @end ifset
2211 @ifclear vms
2212 a,g,i, or s,
2213 @end ifclear
2214 and the second character is a
2215 minus. In this case, the character ^tilde^dollar sign^ is used in place
2216 of the minus. The reason for this special rule is to avoid clashes with
2217 the standard names for child units of the packages System, Ada,
2218 Interfaces, and GNAT, which use the prefixes
2219 @ifset vms
2220 S- A- I- and G-
2221 @end ifset
2222 @ifclear vms
2223 s- a- i- and g-
2224 @end ifclear
2225 respectively.
2227 The file extension is @file{.ads} for a spec and
2228 @file{.adb} for a body. The following list shows some
2229 examples of these rules.
2231 @table @file
2232 @item main.ads
2233 Main (spec)
2234 @item main.adb
2235 Main (body)
2236 @item arith_functions.ads
2237 Arith_Functions (package spec)
2238 @item arith_functions.adb
2239 Arith_Functions (package body)
2240 @item func-spec.ads
2241 Func.Spec (child package spec)
2242 @item func-spec.adb
2243 Func.Spec (child package body)
2244 @item main-sub.adb
2245 Sub (subunit of Main)
2246 @item ^a~bad.adb^A$BAD.ADB^
2247 A.Bad (child package body)
2248 @end table
2250 @noindent
2251 Following these rules can result in excessively long
2252 file names if corresponding
2253 unit names are long (for example, if child units or subunits are
2254 heavily nested). An option is available to shorten such long file names
2255 (called file name ``krunching''). This may be particularly useful when
2256 programs being developed with GNAT are to be used on operating systems
2257 with limited file name lengths. @xref{Using gnatkr}.
2259 Of course, no file shortening algorithm can guarantee uniqueness over
2260 all possible unit names; if file name krunching is used, it is your
2261 responsibility to ensure no name clashes occur. Alternatively you
2262 can specify the exact file names that you want used, as described
2263 in the next section. Finally, if your Ada programs are migrating from a
2264 compiler with a different naming convention, you can use the gnatchop
2265 utility to produce source files that follow the GNAT naming conventions.
2266 (For details @pxref{Renaming Files Using gnatchop}.)
2268 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2269 systems, case is not significant. So for example on @code{Windows XP}
2270 if the canonical name is @code{main-sub.adb}, you can use the file name
2271 @code{Main-Sub.adb} instead. However, case is significant for other
2272 operating systems, so for example, if you want to use other than
2273 canonically cased file names on a Unix system, you need to follow
2274 the procedures described in the next section.
2276 @node Using Other File Names
2277 @section Using Other File Names
2278 @cindex File names
2280 @noindent
2281 In the previous section, we have described the default rules used by
2282 GNAT to determine the file name in which a given unit resides. It is
2283 often convenient to follow these default rules, and if you follow them,
2284 the compiler knows without being explicitly told where to find all
2285 the files it needs.
2287 However, in some cases, particularly when a program is imported from
2288 another Ada compiler environment, it may be more convenient for the
2289 programmer to specify which file names contain which units. GNAT allows
2290 arbitrary file names to be used by means of the Source_File_Name pragma.
2291 The form of this pragma is as shown in the following examples:
2292 @cindex Source_File_Name pragma
2294 @smallexample @c ada
2295 @cartouche
2296 pragma Source_File_Name (My_Utilities.Stacks,
2297   Spec_File_Name => "myutilst_a.ada");
2298 pragma Source_File_name (My_Utilities.Stacks,
2299   Body_File_Name => "myutilst.ada");
2300 @end cartouche
2301 @end smallexample
2303 @noindent
2304 As shown in this example, the first argument for the pragma is the unit
2305 name (in this example a child unit). The second argument has the form
2306 of a named association. The identifier
2307 indicates whether the file name is for a spec or a body;
2308 the file name itself is given by a string literal.
2310 The source file name pragma is a configuration pragma, which means that
2311 normally it will be placed in the @file{gnat.adc}
2312 file used to hold configuration
2313 pragmas that apply to a complete compilation environment.
2314 For more details on how the @file{gnat.adc} file is created and used
2315 see @ref{Handling of Configuration Pragmas}.
2316 @cindex @file{gnat.adc}
2318 @ifclear vms
2319 GNAT allows completely arbitrary file names to be specified using the
2320 source file name pragma. However, if the file name specified has an
2321 extension other than @file{.ads} or @file{.adb} it is necessary to use
2322 a special syntax when compiling the file. The name in this case must be
2323 preceded by the special sequence @code{-x} followed by a space and the name
2324 of the language, here @code{ada}, as in:
2326 @smallexample
2327 $ gcc -c -x ada peculiar_file_name.sim
2328 @end smallexample
2329 @end ifclear
2331 @noindent
2332 @command{gnatmake} handles non-standard file names in the usual manner (the
2333 non-standard file name for the main program is simply used as the
2334 argument to gnatmake). Note that if the extension is also non-standard,
2335 then it must be included in the gnatmake command, it may not be omitted.
2337 @node Alternative File Naming Schemes
2338 @section Alternative File Naming Schemes
2339 @cindex File naming schemes, alternative
2340 @cindex File names
2342 In the previous section, we described the use of the @code{Source_File_Name}
2343 pragma to allow arbitrary names to be assigned to individual source files.
2344 However, this approach requires one pragma for each file, and especially in
2345 large systems can result in very long @file{gnat.adc} files, and also create
2346 a maintenance problem.
2348 GNAT also provides a facility for specifying systematic file naming schemes
2349 other than the standard default naming scheme previously described. An
2350 alternative scheme for naming is specified by the use of
2351 @code{Source_File_Name} pragmas having the following format:
2352 @cindex Source_File_Name pragma
2354 @smallexample @c ada
2355 pragma Source_File_Name (
2356    Spec_File_Name  => FILE_NAME_PATTERN
2357  [,Casing          => CASING_SPEC]
2358  [,Dot_Replacement => STRING_LITERAL]);
2360 pragma Source_File_Name (
2361    Body_File_Name  => FILE_NAME_PATTERN
2362  [,Casing          => CASING_SPEC]
2363  [,Dot_Replacement => STRING_LITERAL]);
2365 pragma Source_File_Name (
2366    Subunit_File_Name  => FILE_NAME_PATTERN
2367  [,Casing             => CASING_SPEC]
2368  [,Dot_Replacement    => STRING_LITERAL]);
2370 FILE_NAME_PATTERN ::= STRING_LITERAL
2371 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2372 @end smallexample
2374 @noindent
2375 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2376 It contains a single asterisk character, and the unit name is substituted
2377 systematically for this asterisk. The optional parameter
2378 @code{Casing} indicates
2379 whether the unit name is to be all upper-case letters, all lower-case letters,
2380 or mixed-case. If no
2381 @code{Casing} parameter is used, then the default is all
2382 ^lower-case^upper-case^.
2384 The optional @code{Dot_Replacement} string is used to replace any periods
2385 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2386 argument is used then separating dots appear unchanged in the resulting
2387 file name.
2388 Although the above syntax indicates that the
2389 @code{Casing} argument must appear
2390 before the @code{Dot_Replacement} argument, but it
2391 is also permissible to write these arguments in the opposite order.
2393 As indicated, it is possible to specify different naming schemes for
2394 bodies, specs, and subunits. Quite often the rule for subunits is the
2395 same as the rule for bodies, in which case, there is no need to give
2396 a separate @code{Subunit_File_Name} rule, and in this case the
2397 @code{Body_File_name} rule is used for subunits as well.
2399 The separate rule for subunits can also be used to implement the rather
2400 unusual case of a compilation environment (e.g. a single directory) which
2401 contains a subunit and a child unit with the same unit name. Although
2402 both units cannot appear in the same partition, the Ada Reference Manual
2403 allows (but does not require) the possibility of the two units coexisting
2404 in the same environment.
2406 The file name translation works in the following steps:
2408 @itemize @bullet
2410 @item
2411 If there is a specific @code{Source_File_Name} pragma for the given unit,
2412 then this is always used, and any general pattern rules are ignored.
2414 @item
2415 If there is a pattern type @code{Source_File_Name} pragma that applies to
2416 the unit, then the resulting file name will be used if the file exists. If
2417 more than one pattern matches, the latest one will be tried first, and the
2418 first attempt resulting in a reference to a file that exists will be used.
2420 @item
2421 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2422 for which the corresponding file exists, then the standard GNAT default
2423 naming rules are used.
2425 @end itemize
2427 @noindent
2428 As an example of the use of this mechanism, consider a commonly used scheme
2429 in which file names are all lower case, with separating periods copied
2430 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2431 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2432 two pragmas appear:
2434 @smallexample @c ada
2435 pragma Source_File_Name
2436   (Spec_File_Name => "*.1.ada");
2437 pragma Source_File_Name
2438   (Body_File_Name => "*.2.ada");
2439 @end smallexample
2441 @noindent
2442 The default GNAT scheme is actually implemented by providing the following
2443 default pragmas internally:
2445 @smallexample @c ada
2446 pragma Source_File_Name
2447   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2448 pragma Source_File_Name
2449   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2450 @end smallexample
2452 @noindent
2453 Our final example implements a scheme typically used with one of the
2454 Ada 83 compilers, where the separator character for subunits was ``__''
2455 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2456 by adding @file{.ADA}, and subunits by
2457 adding @file{.SEP}. All file names were
2458 upper case. Child units were not present of course since this was an
2459 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2460 the same double underscore separator for child units.
2462 @smallexample @c ada
2463 pragma Source_File_Name
2464   (Spec_File_Name => "*_.ADA",
2465    Dot_Replacement => "__",
2466    Casing = Uppercase);
2467 pragma Source_File_Name
2468   (Body_File_Name => "*.ADA",
2469    Dot_Replacement => "__",
2470    Casing = Uppercase);
2471 pragma Source_File_Name
2472   (Subunit_File_Name => "*.SEP",
2473    Dot_Replacement => "__",
2474    Casing = Uppercase);
2475 @end smallexample
2477 @node Generating Object Files
2478 @section Generating Object Files
2480 @noindent
2481 An Ada program consists of a set of source files, and the first step in
2482 compiling the program is to generate the corresponding object files.
2483 These are generated by compiling a subset of these source files.
2484 The files you need to compile are the following:
2486 @itemize @bullet
2487 @item
2488 If a package spec has no body, compile the package spec to produce the
2489 object file for the package.
2491 @item
2492 If a package has both a spec and a body, compile the body to produce the
2493 object file for the package. The source file for the package spec need
2494 not be compiled in this case because there is only one object file, which
2495 contains the code for both the spec and body of the package.
2497 @item
2498 For a subprogram, compile the subprogram body to produce the object file
2499 for the subprogram. The spec, if one is present, is as usual in a
2500 separate file, and need not be compiled.
2502 @item
2503 @cindex Subunits
2504 In the case of subunits, only compile the parent unit. A single object
2505 file is generated for the entire subunit tree, which includes all the
2506 subunits.
2508 @item
2509 Compile child units independently of their parent units
2510 (though, of course, the spec of all the ancestor unit must be present in order
2511 to compile a child unit).
2513 @item
2514 @cindex Generics
2515 Compile generic units in the same manner as any other units. The object
2516 files in this case are small dummy files that contain at most the
2517 flag used for elaboration checking. This is because GNAT always handles generic
2518 instantiation by means of macro expansion. However, it is still necessary to
2519 compile generic units, for dependency checking and elaboration purposes.
2520 @end itemize
2522 @noindent
2523 The preceding rules describe the set of files that must be compiled to
2524 generate the object files for a program. Each object file has the same
2525 name as the corresponding source file, except that the extension is
2526 @file{.o} as usual.
2528 You may wish to compile other files for the purpose of checking their
2529 syntactic and semantic correctness. For example, in the case where a
2530 package has a separate spec and body, you would not normally compile the
2531 spec. However, it is convenient in practice to compile the spec to make
2532 sure it is error-free before compiling clients of this spec, because such
2533 compilations will fail if there is an error in the spec.
2535 GNAT provides an option for compiling such files purely for the
2536 purposes of checking correctness; such compilations are not required as
2537 part of the process of building a program. To compile a file in this
2538 checking mode, use the @option{-gnatc} switch.
2540 @node Source Dependencies
2541 @section Source Dependencies
2543 @noindent
2544 A given object file clearly depends on the source file which is compiled
2545 to produce it. Here we are using @dfn{depends} in the sense of a typical
2546 @code{make} utility; in other words, an object file depends on a source
2547 file if changes to the source file require the object file to be
2548 recompiled.
2549 In addition to this basic dependency, a given object may depend on
2550 additional source files as follows:
2552 @itemize @bullet
2553 @item
2554 If a file being compiled @code{with}'s a unit @var{X}, the object file
2555 depends on the file containing the spec of unit @var{X}. This includes
2556 files that are @code{with}'ed implicitly either because they are parents
2557 of @code{with}'ed child units or they are run-time units required by the
2558 language constructs used in a particular unit.
2560 @item
2561 If a file being compiled instantiates a library level generic unit, the
2562 object file depends on both the spec and body files for this generic
2563 unit.
2565 @item
2566 If a file being compiled instantiates a generic unit defined within a
2567 package, the object file depends on the body file for the package as
2568 well as the spec file.
2570 @item
2571 @findex Inline
2572 @cindex @option{-gnatn} switch
2573 If a file being compiled contains a call to a subprogram for which
2574 pragma @code{Inline} applies and inlining is activated with the
2575 @option{-gnatn} switch, the object file depends on the file containing the
2576 body of this subprogram as well as on the file containing the spec. Note
2577 that for inlining to actually occur as a result of the use of this switch,
2578 it is necessary to compile in optimizing mode.
2580 @cindex @option{-gnatN} switch
2581 The use of @option{-gnatN} activates a more extensive inlining optimization
2582 that is performed by the front end of the compiler. This inlining does
2583 not require that the code generation be optimized. Like @option{-gnatn},
2584 the use of this switch generates additional dependencies.
2585 Note that
2586 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2587 to specify both options.
2589 @item
2590 If an object file O  depends on the proper body of a subunit through inlining
2591 or instantiation, it depends on the parent unit of the subunit. This means that
2592 any modification of the parent unit or one of its subunits affects the
2593 compilation of O.
2595 @item
2596 The object file for a parent unit depends on all its subunit body files.
2598 @item
2599 The previous two rules meant that for purposes of computing dependencies and
2600 recompilation, a body and all its subunits are treated as an indivisible whole.
2602 @noindent
2603 These rules are applied transitively: if unit @code{A} @code{with}'s
2604 unit @code{B}, whose elaboration calls an inlined procedure in package
2605 @code{C}, the object file for unit @code{A} will depend on the body of
2606 @code{C}, in file @file{c.adb}.
2608 The set of dependent files described by these rules includes all the
2609 files on which the unit is semantically dependent, as described in the
2610 Ada 95 Language Reference Manual. However, it is a superset of what the
2611 ARM describes, because it includes generic, inline, and subunit dependencies.
2613 An object file must be recreated by recompiling the corresponding source
2614 file if any of the source files on which it depends are modified. For
2615 example, if the @code{make} utility is used to control compilation,
2616 the rule for an Ada object file must mention all the source files on
2617 which the object file depends, according to the above definition.
2618 The determination of the necessary
2619 recompilations is done automatically when one uses @command{gnatmake}.
2620 @end itemize
2622 @node The Ada Library Information Files
2623 @section The Ada Library Information Files
2624 @cindex Ada Library Information files
2625 @cindex @file{ALI} files
2627 @noindent
2628 Each compilation actually generates two output files. The first of these
2629 is the normal object file that has a @file{.o} extension. The second is a
2630 text file containing full dependency information. It has the same
2631 name as the source file, but an @file{.ali} extension.
2632 This file is known as the Ada Library Information (@file{ALI}) file.
2633 The following information is contained in the @file{ALI} file.
2635 @itemize @bullet
2636 @item
2637 Version information (indicates which version of GNAT was used to compile
2638 the unit(s) in question)
2640 @item
2641 Main program information (including priority and time slice settings,
2642 as well as the wide character encoding used during compilation).
2644 @item
2645 List of arguments used in the @command{gcc} command for the compilation
2647 @item
2648 Attributes of the unit, including configuration pragmas used, an indication
2649 of whether the compilation was successful, exception model used etc.
2651 @item
2652 A list of relevant restrictions applying to the unit (used for consistency)
2653 checking.
2655 @item
2656 Categorization information (e.g. use of pragma @code{Pure}).
2658 @item
2659 Information on all @code{with}'ed units, including presence of
2660 @code{Elaborate} or @code{Elaborate_All} pragmas.
2662 @item
2663 Information from any @code{Linker_Options} pragmas used in the unit
2665 @item
2666 Information on the use of @code{Body_Version} or @code{Version}
2667 attributes in the unit.
2669 @item
2670 Dependency information. This is a list of files, together with
2671 time stamp and checksum information. These are files on which
2672 the unit depends in the sense that recompilation is required
2673 if any of these units are modified.
2675 @item
2676 Cross-reference data. Contains information on all entities referenced
2677 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2678 provide cross-reference information.
2680 @end itemize
2682 @noindent
2683 For a full detailed description of the format of the @file{ALI} file,
2684 see the source of the body of unit @code{Lib.Writ}, contained in file
2685 @file{lib-writ.adb} in the GNAT compiler sources.
2687 @node Binding an Ada Program
2688 @section Binding an Ada Program
2690 @noindent
2691 When using languages such as C and C++, once the source files have been
2692 compiled the only remaining step in building an executable program
2693 is linking the object modules together. This means that it is possible to
2694 link an inconsistent version of a program, in which two units have
2695 included different versions of the same header.
2697 The rules of Ada do not permit such an inconsistent program to be built.
2698 For example, if two clients have different versions of the same package,
2699 it is illegal to build a program containing these two clients.
2700 These rules are enforced by the GNAT binder, which also determines an
2701 elaboration order consistent with the Ada rules.
2703 The GNAT binder is run after all the object files for a program have
2704 been created. It is given the name of the main program unit, and from
2705 this it determines the set of units required by the program, by reading the
2706 corresponding ALI files. It generates error messages if the program is
2707 inconsistent or if no valid order of elaboration exists.
2709 If no errors are detected, the binder produces a main program, in Ada by
2710 default, that contains calls to the elaboration procedures of those
2711 compilation unit that require them, followed by
2712 a call to the main program. This Ada program is compiled to generate the
2713 object file for the main program. The name of
2714 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2715 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2716 main program unit.
2718 Finally, the linker is used to build the resulting executable program,
2719 using the object from the main program from the bind step as well as the
2720 object files for the Ada units of the program.
2722 @node Mixed Language Programming
2723 @section Mixed Language Programming
2724 @cindex Mixed Language Programming
2726 @noindent
2727 This section describes how to develop a mixed-language program,
2728 specifically one that comprises units in both Ada and C.
2730 @menu
2731 * Interfacing to C::
2732 * Calling Conventions::
2733 @end menu
2735 @node Interfacing to C
2736 @subsection Interfacing to C
2737 @noindent
2738 Interfacing Ada with a foreign language such as C involves using
2739 compiler directives to import and/or export entity definitions in each
2740 language---using @code{extern} statements in C, for instance, and the
2741 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2742 a full treatment of these topics, read Appendix B, section 1 of the Ada
2743 95 Language Reference Manual.
2745 There are two ways to build a program using GNAT that contains some Ada
2746 sources and some foreign language sources, depending on whether or not
2747 the main subprogram is written in Ada.  Here is a source example with
2748 the main subprogram in Ada:
2750 @smallexample
2751 /* file1.c */
2752 #include <stdio.h>
2754 void print_num (int num)
2756   printf ("num is %d.\n", num);
2757   return;
2760 /* file2.c */
2762 /* num_from_Ada is declared in my_main.adb */
2763 extern int num_from_Ada;
2765 int get_num (void)
2767   return num_from_Ada;
2769 @end smallexample
2771 @smallexample @c ada
2772 --  my_main.adb
2773 procedure My_Main is
2775    --  Declare then export an Integer entity called num_from_Ada
2776    My_Num : Integer := 10;
2777    pragma Export (C, My_Num, "num_from_Ada");
2779    --  Declare an Ada function spec for Get_Num, then use
2780    --  C function get_num for the implementation.
2781    function Get_Num return Integer;
2782    pragma Import (C, Get_Num, "get_num");
2784    --  Declare an Ada procedure spec for Print_Num, then use
2785    --  C function print_num for the implementation.
2786    procedure Print_Num (Num : Integer);
2787    pragma Import (C, Print_Num, "print_num");
2789 begin
2790    Print_Num (Get_Num);
2791 end My_Main;
2792 @end smallexample
2794 @enumerate
2795 @item
2796 To build this example, first compile the foreign language files to
2797 generate object files:
2798 @smallexample
2799 ^gcc -c file1.c^gcc -c FILE1.C^
2800 ^gcc -c file2.c^gcc -c FILE2.C^
2801 @end smallexample
2803 @item
2804 Then, compile the Ada units to produce a set of object files and ALI
2805 files:
2806 @smallexample
2807 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2808 @end smallexample
2810 @item
2811 Run the Ada binder on the Ada main program:
2812 @smallexample
2813 gnatbind my_main.ali
2814 @end smallexample
2816 @item
2817 Link the Ada main program, the Ada objects and the other language
2818 objects:
2819 @smallexample
2820 gnatlink my_main.ali file1.o file2.o
2821 @end smallexample
2822 @end enumerate
2824 The last three steps can be grouped in a single command:
2825 @smallexample
2826 gnatmake my_main.adb -largs file1.o file2.o
2827 @end smallexample
2829 @cindex Binder output file
2830 @noindent
2831 If the main program is in a language other than Ada, then you may have
2832 more than one entry point into the Ada subsystem. You must use a special
2833 binder option to generate callable routines that initialize and
2834 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2835 Calls to the initialization and finalization routines must be inserted
2836 in the main program, or some other appropriate point in the code. The
2837 call to initialize the Ada units must occur before the first Ada
2838 subprogram is called, and the call to finalize the Ada units must occur
2839 after the last Ada subprogram returns. The binder will place the
2840 initialization and finalization subprograms into the
2841 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2842 sources.  To illustrate, we have the following example:
2844 @smallexample
2845 /* main.c */
2846 extern void adainit (void);
2847 extern void adafinal (void);
2848 extern int add (int, int);
2849 extern int sub (int, int);
2851 int main (int argc, char *argv[])
2853   int a = 21, b = 7;
2855   adainit();
2857   /* Should print "21 + 7 = 28" */
2858   printf ("%d + %d = %d\n", a, b, add (a, b));
2859   /* Should print "21 - 7 = 14" */
2860   printf ("%d - %d = %d\n", a, b, sub (a, b));
2862   adafinal();
2864 @end smallexample
2866 @smallexample @c ada
2867 --  unit1.ads
2868 package Unit1 is
2869    function Add (A, B : Integer) return Integer;
2870    pragma Export (C, Add, "add");
2871 end Unit1;
2873 --  unit1.adb
2874 package body Unit1 is
2875    function Add (A, B : Integer) return Integer is
2876    begin
2877       return A + B;
2878    end Add;
2879 end Unit1;
2881 --  unit2.ads
2882 package Unit2 is
2883    function Sub (A, B : Integer) return Integer;
2884    pragma Export (C, Sub, "sub");
2885 end Unit2;
2887 --  unit2.adb
2888 package body Unit2 is
2889    function Sub (A, B : Integer) return Integer is
2890    begin
2891       return A - B;
2892    end Sub;
2893 end Unit2;
2894 @end smallexample
2896 @enumerate
2897 @item
2898 The build procedure for this application is similar to the last
2899 example's.  First, compile the foreign language files to generate object
2900 files:
2901 @smallexample
2902 ^gcc -c main.c^gcc -c main.c^
2903 @end smallexample
2905 @item
2906 Next, compile the Ada units to produce a set of object files and ALI
2907 files:
2908 @smallexample
2909 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2910 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2911 @end smallexample
2913 @item
2914 Run the Ada binder on every generated ALI file.  Make sure to use the
2915 @option{-n} option to specify a foreign main program:
2916 @smallexample
2917 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2918 @end smallexample
2920 @item
2921 Link the Ada main program, the Ada objects and the foreign language
2922 objects. You need only list the last ALI file here:
2923 @smallexample
2924 gnatlink unit2.ali main.o -o exec_file
2925 @end smallexample
2927 This procedure yields a binary executable called @file{exec_file}.
2928 @end enumerate
2930 @node Calling Conventions
2931 @subsection Calling Conventions
2932 @cindex Foreign Languages
2933 @cindex Calling Conventions
2934 GNAT follows standard calling sequence conventions and will thus interface
2935 to any other language that also follows these conventions. The following
2936 Convention identifiers are recognized by GNAT:
2938 @table @code
2939 @cindex Interfacing to Ada
2940 @cindex Other Ada compilers
2941 @cindex Convention Ada
2942 @item Ada
2943 This indicates that the standard Ada calling sequence will be
2944 used and all Ada data items may be passed without any limitations in the
2945 case where GNAT is used to generate both the caller and callee. It is also
2946 possible to mix GNAT generated code and code generated by another Ada
2947 compiler. In this case, the data types should be restricted to simple
2948 cases, including primitive types. Whether complex data types can be passed
2949 depends on the situation. Probably it is safe to pass simple arrays, such
2950 as arrays of integers or floats. Records may or may not work, depending
2951 on whether both compilers lay them out identically. Complex structures
2952 involving variant records, access parameters, tasks, or protected types,
2953 are unlikely to be able to be passed.
2955 Note that in the case of GNAT running
2956 on a platform that supports HP Ada 83, a higher degree of compatibility
2957 can be guaranteed, and in particular records are layed out in an identical
2958 manner in the two compilers. Note also that if output from two different
2959 compilers is mixed, the program is responsible for dealing with elaboration
2960 issues. Probably the safest approach is to write the main program in the
2961 version of Ada other than GNAT, so that it takes care of its own elaboration
2962 requirements, and then call the GNAT-generated adainit procedure to ensure
2963 elaboration of the GNAT components. Consult the documentation of the other
2964 Ada compiler for further details on elaboration.
2966 However, it is not possible to mix the tasking run time of GNAT and
2967 HP Ada 83, All the tasking operations must either be entirely within
2968 GNAT compiled sections of the program, or entirely within HP Ada 83
2969 compiled sections of the program.
2971 @cindex Interfacing to Assembly
2972 @cindex Convention Assembler
2973 @item Assembler
2974 Specifies assembler as the convention. In practice this has the
2975 same effect as convention Ada (but is not equivalent in the sense of being
2976 considered the same convention).
2978 @cindex Convention Asm
2979 @findex Asm
2980 @item Asm
2981 Equivalent to Assembler.
2983 @cindex Interfacing to COBOL
2984 @cindex Convention COBOL
2985 @findex COBOL
2986 @item COBOL
2987 Data will be passed according to the conventions described
2988 in section B.4 of the Ada 95 Reference Manual.
2990 @findex C
2991 @cindex Interfacing to C
2992 @cindex Convention C
2993 @item C
2994 Data will be passed according to the conventions described
2995 in section B.3 of the Ada 95 Reference Manual.
2997 A note on interfacing to a C ``varargs'' function:
2998 @findex C varargs function
2999 @cindex Interfacing to C varargs function
3000 @cindex varargs function interfaces
3002 @itemize @bullet
3003 @item
3004 In C, @code{varargs} allows a function to take a variable number of
3005 arguments. There is no direct equivalent in this to Ada. One
3006 approach that can be used is to create a C wrapper for each
3007 different profile and then interface to this C wrapper. For
3008 example, to print an @code{int} value using @code{printf},
3009 create a C function @code{printfi} that takes two arguments, a
3010 pointer to a string and an int, and calls @code{printf}.
3011 Then in the Ada program, use pragma @code{Import} to
3012 interface to @code{printfi}.
3014 @item
3015 It may work on some platforms to directly interface to
3016 a @code{varargs} function by providing a specific Ada profile
3017 for a a particular call. However, this does not work on
3018 all platforms, since there is no guarantee that the
3019 calling sequence for a two argument normal C function
3020 is the same as for calling a @code{varargs} C function with
3021 the same two arguments.
3022 @end itemize
3024 @cindex Convention Default
3025 @findex Default
3026 @item Default
3027 Equivalent to C.
3029 @cindex Convention External
3030 @findex External
3031 @item External
3032 Equivalent to C.
3034 @ifclear vms
3035 @findex C++
3036 @cindex Interfacing to C++
3037 @cindex Convention C++
3038 @item CPP
3039 This stands for C++. For most purposes this is identical to C.
3040 See the separate description of the specialized GNAT pragmas relating to
3041 C++ interfacing for further details.
3042 @end ifclear
3044 @findex Fortran
3045 @cindex Interfacing to Fortran
3046 @cindex Convention Fortran
3047 @item Fortran
3048 Data will be passed according to the conventions described
3049 in section B.5 of the Ada 95 Reference Manual.
3051 @item Intrinsic
3052 This applies to an intrinsic operation, as defined in the Ada 95
3053 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3054 this means that the body of the subprogram is provided by the compiler itself,
3055 usually by means of an efficient code sequence, and that the user does not
3056 supply an explicit body for it. In an application program, the pragma can
3057 only be applied to the following two sets of names, which the GNAT compiler
3058 recognizes.
3060 @itemize @bullet
3061 @item
3062 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
3063 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
3064 two formal parameters. The
3065 first one must be a signed integer type or a modular type with a binary
3066 modulus, and the second parameter must be of type Natural.
3067 The return type must be the same as the type of the first argument. The size
3068 of this type can only be 8, 16, 32, or 64.
3069 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3070 The corresponding operator declaration must have parameters and result type
3071 that have the same root numeric type (for example, all three are long_float
3072 types). This simplifies the definition of operations that use type checking
3073 to perform dimensional checks:
3075 @smallexample @c ada
3076 type Distance is new Long_Float;
3077 type Time     is new Long_Float;
3078 type Velocity is new Long_Float;
3079 function "/" (D : Distance; T : Time)
3080   return Velocity;
3081 pragma Import (Intrinsic, "/");
3082 @end smallexample
3084 @noindent
3085 This common idiom is often programmed with a generic definition and an
3086 explicit body. The pragma makes it simpler to introduce such declarations.
3087 It incurs no overhead in compilation time or code size, because it is
3088 implemented as a single machine instruction.
3089 @end itemize
3090 @noindent
3092 @ifset unw
3093 @findex Stdcall
3094 @cindex Convention Stdcall
3095 @item Stdcall
3096 This is relevant only to Windows XP/2000/NT/95 implementations of GNAT,
3097 and specifies that the @code{Stdcall} calling sequence will be used,
3098 as defined by the NT API. Nevertheless, to ease building
3099 cross-platform bindings this convention will be handled as a @code{C} calling
3100 convention on non Windows platforms.
3102 @findex DLL
3103 @cindex Convention DLL
3104 @item DLL
3105 This is equivalent to @code{Stdcall}.
3107 @findex Win32
3108 @cindex Convention Win32
3109 @item Win32
3110 This is equivalent to @code{Stdcall}.
3111 @end ifset
3113 @findex Stubbed
3114 @cindex Convention Stubbed
3115 @item Stubbed
3116 This is a special convention that indicates that the compiler
3117 should provide a stub body that raises @code{Program_Error}.
3118 @end table
3120 @noindent
3121 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3122 that can be used to parametrize conventions and allow additional synonyms
3123 to be specified. For example if you have legacy code in which the convention
3124 identifier Fortran77 was used for Fortran, you can use the configuration
3125 pragma:
3127 @smallexample @c ada
3128 pragma Convention_Identifier (Fortran77, Fortran);
3129 @end smallexample
3131 @noindent
3132 And from now on the identifier Fortran77 may be used as a convention
3133 identifier (for example in an @code{Import} pragma) with the same
3134 meaning as Fortran.
3136 @ifclear vms
3137 @node Building Mixed Ada & C++ Programs
3138 @section Building Mixed Ada and C++ Programs
3140 @noindent
3141 A programmer inexperienced with mixed-language development may find that
3142 building an application containing both Ada and C++ code can be a
3143 challenge. As a matter of fact, interfacing with C++ has not been
3144 standardized in the Ada 95 Reference Manual due to the immaturity of --
3145 and lack of standards for -- C++ at the time. This section gives a few
3146 hints that should make this task easier. The first section addresses
3147 the differences regarding interfacing with C. The second section
3148 looks into the delicate problem of linking the complete application from
3149 its Ada and C++ parts. The last section gives some hints on how the GNAT
3150 run time can be adapted in order to allow inter-language dispatching
3151 with a new C++ compiler.
3153 @menu
3154 * Interfacing to C++::
3155 * Linking a Mixed C++ & Ada Program::
3156 * A Simple Example::
3157 * Adapting the Run Time to a New C++ Compiler::
3158 @end menu
3160 @node Interfacing to C++
3161 @subsection Interfacing to C++
3163 @noindent
3164 GNAT supports interfacing with C++ compilers generating code that is
3165 compatible with the standard Application Binary Interface of the given
3166 platform.
3168 @noindent
3169 Interfacing can be done at 3 levels: simple data, subprograms, and
3170 classes. In the first two cases, GNAT offers a specific @var{Convention
3171 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3172 the names of subprograms, and currently, GNAT does not provide any help
3173 to solve the demangling problem. This problem can be addressed in two
3174 ways:
3175 @itemize @bullet
3176 @item
3177 by modifying the C++ code in order to force a C convention using
3178 the @code{extern "C"} syntax.
3180 @item
3181 by figuring out the mangled name and use it as the Link_Name argument of
3182 the pragma import.
3183 @end itemize
3185 @noindent
3186 Interfacing at the class level can be achieved by using the GNAT specific
3187 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3188 Reference Manual for additional information.
3190 @node Linking a Mixed C++ & Ada Program
3191 @subsection Linking a Mixed C++ & Ada Program
3193 @noindent
3194 Usually the linker of the C++ development system must be used to link
3195 mixed applications because most C++ systems will resolve elaboration
3196 issues (such as calling constructors on global class instances)
3197 transparently during the link phase. GNAT has been adapted to ease the
3198 use of a foreign linker for the last phase. Three cases can be
3199 considered:
3200 @enumerate
3202 @item
3203 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3204 The C++ linker can simply be called by using the C++ specific driver
3205 called @code{c++}. Note that this setup is not very common because it
3206 may involve recompiling the whole GCC tree from sources, which makes it
3207 harder to upgrade the compilation system for one language without
3208 destabilizing the other.
3210 @smallexample
3211 $ c++ -c file1.C
3212 $ c++ -c file2.C
3213 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3214 @end smallexample
3216 @item
3217 Using GNAT and G++ from two different GCC installations: If both
3218 compilers are on the PATH, the previous method may be used. It is
3219 important to note that environment variables such as C_INCLUDE_PATH,
3220 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3221 at the same time and may make one of the two compilers operate
3222 improperly if set during invocation of the wrong compiler.  It is also
3223 very important that the linker uses the proper @file{libgcc.a} GCC
3224 library -- that is, the one from the C++ compiler installation. The
3225 implicit link command as suggested in the gnatmake command from the
3226 former example can be replaced by an explicit link command with the
3227 full-verbosity option in order to verify which library is used:
3228 @smallexample
3229 $ gnatbind ada_unit
3230 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3231 @end smallexample
3232 If there is a problem due to interfering environment variables, it can
3233 be worked around by using an intermediate script. The following example
3234 shows the proper script to use when GNAT has not been installed at its
3235 default location and g++ has been installed at its default location:
3237 @smallexample
3238 $ cat ./my_script
3239 #!/bin/sh
3240 unset BINUTILS_ROOT
3241 unset GCC_ROOT
3242 c++ $*
3243 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3244 @end smallexample
3246 @item
3247 Using a non-GNU C++ compiler: The commands previously described can be
3248 used to insure that the C++ linker is used. Nonetheless, you need to add
3249 a few more parameters to the link command line, depending on the exception
3250 mechanism used.
3252 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
3253 to the libgcc libraries are required:
3255 @smallexample
3256 $ cat ./my_script
3257 #!/bin/sh
3258 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3259 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3260 @end smallexample
3262 Where CC is the name of the non-GNU C++ compiler.
3264 If the @code{zero cost} exception mechanism is used, and the platform
3265 supports automatic registration of exception tables (e.g. Solaris or IRIX),
3266 paths to more objects are required:
3268 @smallexample
3269 $ cat ./my_script
3270 #!/bin/sh
3271 CC `gcc -print-file-name=crtbegin.o` $* \
3272 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
3273 `gcc -print-file-name=crtend.o`
3274 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3275 @end smallexample
3277 If the @code{zero cost} exception mechanism is used, and the platform
3278 doesn't support automatic registration of exception tables (e.g. HP-UX,
3279 Tru64 or AIX), the simple approach described above will not work and
3280 a pre-linking phase using GNAT will be necessary.
3282 @end enumerate
3284 @node A Simple Example
3285 @subsection  A Simple Example
3286 @noindent
3287 The following example, provided as part of the GNAT examples, shows how
3288 to achieve procedural interfacing between Ada and C++ in both
3289 directions. The C++ class A has two methods. The first method is exported
3290 to Ada by the means of an extern C wrapper function. The second method
3291 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3292 a limited record with a layout comparable to the C++ class. The Ada
3293 subprogram, in turn, calls the C++ method. So, starting from the C++
3294 main program, the process passes back and forth between the two
3295 languages.
3297 @noindent
3298 Here are the compilation commands:
3299 @smallexample
3300 $ gnatmake -c simple_cpp_interface
3301 $ c++ -c cpp_main.C
3302 $ c++ -c ex7.C
3303 $ gnatbind -n simple_cpp_interface
3304 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3305       -lstdc++ ex7.o cpp_main.o
3306 @end smallexample
3308 @noindent
3309 Here are the corresponding sources:
3310 @smallexample
3312 //cpp_main.C
3314 #include "ex7.h"
3316 extern "C" @{
3317   void adainit (void);
3318   void adafinal (void);
3319   void method1 (A *t);
3322 void method1 (A *t)
3324   t->method1 ();
3327 int main ()
3329   A obj;
3330   adainit ();
3331   obj.method2 (3030);
3332   adafinal ();
3335 //ex7.h
3337 class Origin @{
3338  public:
3339   int o_value;
3341 class A : public Origin @{
3342  public:
3343   void method1 (void);
3344   void method2 (int v);
3345   A();
3346   int   a_value;
3349 //ex7.C
3351 #include "ex7.h"
3352 #include <stdio.h>
3354 extern "C" @{ void ada_method2 (A *t, int v);@}
3356 void A::method1 (void)
3358   a_value = 2020;
3359   printf ("in A::method1, a_value = %d \n",a_value);
3363 void A::method2 (int v)
3365    ada_method2 (this, v);
3366    printf ("in A::method2, a_value = %d \n",a_value);
3370 A::A(void)
3372    a_value = 1010;
3373   printf ("in A::A, a_value = %d \n",a_value);
3376 -- Ada sources
3377 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3379    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3380    @b{begin}
3381       Method1 (This);
3382       This.A_Value := V;
3383    @b{end} Ada_Method2;
3385 @b{end} Simple_Cpp_Interface;
3387 @b{package} Simple_Cpp_Interface @b{is}
3388    @b{type} A @b{is} @b{limited}
3389       @b{record}
3390          O_Value : Integer;
3391          A_Value : Integer;
3392       @b{end} @b{record};
3393    @b{pragma} Convention (C, A);
3395    @b{procedure} Method1 (This : @b{in} @b{out} A);
3396    @b{pragma} Import (C, Method1);
3398    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3399    @b{pragma} Export (C, Ada_Method2);
3401 @b{end} Simple_Cpp_Interface;
3402 @end smallexample
3404 @node Adapting the Run Time to a New C++ Compiler
3405 @subsection Adapting the Run Time to a New C++ Compiler
3406 @noindent
3407 GNAT offers the capability to derive Ada 95 tagged types directly from
3408 preexisting C++ classes and . See ``Interfacing with C++'' in the
3409 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3410 such a goal
3411 has been made user configurable through a GNAT library unit
3412 @code{Interfaces.CPP}. The default version of this file is adapted to
3413 the GNU C++ compiler. Internal knowledge of the virtual
3414 table layout used by the new C++ compiler is needed to configure
3415 properly this unit. The Interface of this unit is known by the compiler
3416 and cannot be changed except for the value of the constants defining the
3417 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3418 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3419 of this unit for more details.
3421 @node Comparison between GNAT and C/C++ Compilation Models
3422 @section Comparison between GNAT and C/C++ Compilation Models
3424 @noindent
3425 The GNAT model of compilation is close to the C and C++ models. You can
3426 think of Ada specs as corresponding to header files in C. As in C, you
3427 don't need to compile specs; they are compiled when they are used. The
3428 Ada @code{with} is similar in effect to the @code{#include} of a C
3429 header.
3431 One notable difference is that, in Ada, you may compile specs separately
3432 to check them for semantic and syntactic accuracy. This is not always
3433 possible with C headers because they are fragments of programs that have
3434 less specific syntactic or semantic rules.
3436 The other major difference is the requirement for running the binder,
3437 which performs two important functions. First, it checks for
3438 consistency. In C or C++, the only defense against assembling
3439 inconsistent programs lies outside the compiler, in a makefile, for
3440 example. The binder satisfies the Ada requirement that it be impossible
3441 to construct an inconsistent program when the compiler is used in normal
3442 mode.
3444 @cindex Elaboration order control
3445 The other important function of the binder is to deal with elaboration
3446 issues. There are also elaboration issues in C++ that are handled
3447 automatically. This automatic handling has the advantage of being
3448 simpler to use, but the C++ programmer has no control over elaboration.
3449 Where @code{gnatbind} might complain there was no valid order of
3450 elaboration, a C++ compiler would simply construct a program that
3451 malfunctioned at run time.
3452 @end ifclear
3454 @node Comparison between GNAT and Conventional Ada Library Models
3455 @section Comparison between GNAT and Conventional Ada Library Models
3457 @noindent
3458 This section is intended for Ada programmers who have
3459 used an Ada compiler implementing the traditional Ada library
3460 model, as described in the Ada 95 Language Reference Manual.
3462 @cindex GNAT library
3463 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3464 source files themselves acts as the library. Compiling Ada programs does
3465 not generate any centralized information, but rather an object file and
3466 a ALI file, which are of interest only to the binder and linker.
3467 In a traditional system, the compiler reads information not only from
3468 the source file being compiled, but also from the centralized library.
3469 This means that the effect of a compilation depends on what has been
3470 previously compiled. In particular:
3472 @itemize @bullet
3473 @item
3474 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3475 to the version of the unit most recently compiled into the library.
3477 @item
3478 Inlining is effective only if the necessary body has already been
3479 compiled into the library.
3481 @item
3482 Compiling a unit may obsolete other units in the library.
3483 @end itemize
3485 @noindent
3486 In GNAT, compiling one unit never affects the compilation of any other
3487 units because the compiler reads only source files. Only changes to source
3488 files can affect the results of a compilation. In particular:
3490 @itemize @bullet
3491 @item
3492 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3493 to the source version of the unit that is currently accessible to the
3494 compiler.
3496 @item
3497 @cindex Inlining
3498 Inlining requires the appropriate source files for the package or
3499 subprogram bodies to be available to the compiler. Inlining is always
3500 effective, independent of the order in which units are complied.
3502 @item
3503 Compiling a unit never affects any other compilations. The editing of
3504 sources may cause previous compilations to be out of date if they
3505 depended on the source file being modified.
3506 @end itemize
3508 @noindent
3509 The most important result of these differences is that order of compilation
3510 is never significant in GNAT. There is no situation in which one is
3511 required to do one compilation before another. What shows up as order of
3512 compilation requirements in the traditional Ada library becomes, in
3513 GNAT, simple source dependencies; in other words, there is only a set
3514 of rules saying what source files must be present when a file is
3515 compiled.
3517 @ifset vms
3518 @node Placement of temporary files
3519 @section Placement of temporary files
3520 @cindex Temporary files (user control over placement)
3522 @noindent
3523 GNAT creates temporary files in the directory designated by the environment
3524 variable @env{TMPDIR}.
3525 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3526 for detailed information on how environment variables are resolved.
3527 For most users the easiest way to make use of this feature is to simply
3528 define @env{TMPDIR} as a job level logical name).
3529 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3530 for compiler temporary files, then you can include something like the
3531 following command in your @file{LOGIN.COM} file:
3533 @smallexample
3534 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3535 @end smallexample
3537 @noindent
3538 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3539 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3540 designated by @env{TEMP}.
3541 If none of these environment variables are defined then GNAT uses the
3542 directory designated by the logical name @code{SYS$SCRATCH:}
3543 (by default the user's home directory). If all else fails
3544 GNAT uses the current directory for temporary files.
3545 @end ifset
3547 @c *************************
3548 @node Compiling Using gcc
3549 @chapter Compiling Using @command{gcc}
3551 @noindent
3552 This chapter discusses how to compile Ada programs using the @command{gcc}
3553 command. It also describes the set of switches
3554 that can be used to control the behavior of the compiler.
3555 @menu
3556 * Compiling Programs::
3557 * Switches for gcc::
3558 * Search Paths and the Run-Time Library (RTL)::
3559 * Order of Compilation Issues::
3560 * Examples::
3561 @end menu
3563 @node Compiling Programs
3564 @section Compiling Programs
3566 @noindent
3567 The first step in creating an executable program is to compile the units
3568 of the program using the @command{gcc} command. You must compile the
3569 following files:
3571 @itemize @bullet
3572 @item
3573 the body file (@file{.adb}) for a library level subprogram or generic
3574 subprogram
3576 @item
3577 the spec file (@file{.ads}) for a library level package or generic
3578 package that has no body
3580 @item
3581 the body file (@file{.adb}) for a library level package
3582 or generic package that has a body
3584 @end itemize
3586 @noindent
3587 You need @emph{not} compile the following files
3589 @itemize @bullet
3591 @item
3592 the spec of a library unit which has a body
3594 @item
3595 subunits
3596 @end itemize
3598 @noindent
3599 because they are compiled as part of compiling related units. GNAT
3600 package specs
3601 when the corresponding body is compiled, and subunits when the parent is
3602 compiled.
3604 @cindex cannot generate code
3605 If you attempt to compile any of these files, you will get one of the
3606 following error messages (where fff is the name of the file you compiled):
3608 @smallexample
3609 cannot generate code for file @var{fff} (package spec)
3610 to check package spec, use -gnatc
3612 cannot generate code for file @var{fff} (missing subunits)
3613 to check parent unit, use -gnatc
3615 cannot generate code for file @var{fff} (subprogram spec)
3616 to check subprogram spec, use -gnatc
3618 cannot generate code for file @var{fff} (subunit)
3619 to check subunit, use -gnatc
3620 @end smallexample
3622 @noindent
3623 As indicated by the above error messages, if you want to submit
3624 one of these files to the compiler to check for correct semantics
3625 without generating code, then use the @option{-gnatc} switch.
3627 The basic command for compiling a file containing an Ada unit is
3629 @smallexample
3630 $ gcc -c [@var{switches}] @file{file name}
3631 @end smallexample
3633 @noindent
3634 where @var{file name} is the name of the Ada file (usually
3635 having an extension
3636 @file{.ads} for a spec or @file{.adb} for a body).
3637 @ifclear vms
3638 You specify the
3639 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3640 @end ifclear
3641 The result of a successful compilation is an object file, which has the
3642 same name as the source file but an extension of @file{.o} and an Ada
3643 Library Information (ALI) file, which also has the same name as the
3644 source file, but with @file{.ali} as the extension. GNAT creates these
3645 two output files in the current directory, but you may specify a source
3646 file in any directory using an absolute or relative path specification
3647 containing the directory information.
3649 @findex gnat1
3650 @command{gcc} is actually a driver program that looks at the extensions of
3651 the file arguments and loads the appropriate compiler. For example, the
3652 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3653 These programs are in directories known to the driver program (in some
3654 configurations via environment variables you set), but need not be in
3655 your path. The @command{gcc} driver also calls the assembler and any other
3656 utilities needed to complete the generation of the required object
3657 files.
3659 It is possible to supply several file names on the same @command{gcc}
3660 command. This causes @command{gcc} to call the appropriate compiler for
3661 each file. For example, the following command lists three separate
3662 files to be compiled:
3664 @smallexample
3665 $ gcc -c x.adb y.adb z.c
3666 @end smallexample
3668 @noindent
3669 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3670 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3671 The compiler generates three object files @file{x.o}, @file{y.o} and
3672 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3673 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3674 @ifclear vms
3675 except for
3676 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3677 @end ifclear
3679 @node Switches for gcc
3680 @section Switches for @command{gcc}
3682 @noindent
3683 The @command{gcc} command accepts switches that control the
3684 compilation process. These switches are fully described in this section.
3685 First we briefly list all the switches, in alphabetical order, then we
3686 describe the switches in more detail in functionally grouped sections.
3688 More switches exist for GCC than those documented here, especially
3689 for specific targets. However, their use is not recommended as
3690 they may change code generation in ways that are incompatible with
3691 the Ada run-time library, or can cause inconsistencies between
3692 compilation units.
3694 @menu
3695 * Output and Error Message Control::
3696 * Warning Message Control::
3697 * Debugging and Assertion Control::
3698 * Validity Checking::
3699 * Style Checking::
3700 * Run-Time Checks::
3701 * Using gcc for Syntax Checking::
3702 * Using gcc for Semantic Checking::
3703 * Compiling Different Versions of Ada::
3704 * Character Set Control::
3705 * File Naming Control::
3706 * Subprogram Inlining Control::
3707 * Auxiliary Output Control::
3708 * Debugging Control::
3709 * Exception Handling Control::
3710 * Units to Sources Mapping Files::
3711 * Integrated Preprocessing::
3712 * Code Generation Control::
3713 @ifset vms
3714 * Return Codes::
3715 @end ifset
3716 @end menu
3718 @table @option
3719 @c !sort!
3720 @ifclear vms
3721 @cindex @option{-b} (@command{gcc})
3722 @item -b @var{target}
3723 Compile your program to run on @var{target}, which is the name of a
3724 system configuration. You must have a GNAT cross-compiler built if
3725 @var{target} is not the same as your host system.
3727 @item -B@var{dir}
3728 @cindex @option{-B} (@command{gcc})
3729 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3730 from @var{dir} instead of the default location. Only use this switch
3731 when multiple versions of the GNAT compiler are available. See the
3732 @command{gcc} manual page for further details. You would normally use the
3733 @option{-b} or @option{-V} switch instead.
3735 @item -c
3736 @cindex @option{-c} (@command{gcc})
3737 Compile. Always use this switch when compiling Ada programs.
3739 Note: for some other languages when using @command{gcc}, notably in
3740 the case of C and C++, it is possible to use
3741 use @command{gcc} without a @option{-c} switch to
3742 compile and link in one step. In the case of GNAT, you
3743 cannot use this approach, because the binder must be run
3744 and @command{gcc} cannot be used to run the GNAT binder.
3745 @end ifclear
3747 @item -fno-inline
3748 @cindex @option{-fno-inline} (@command{gcc})
3749 Suppresses all back-end inlining, even if other optimization or inlining
3750 switches are set.
3751 This includes suppression of inlining that results
3752 from the use of the pragma @code{Inline_Always}.
3753 See also @option{-gnatn} and @option{-gnatN}.
3755 @item -fno-strict-aliasing
3756 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3757 Causes the compiler to avoid assumptions regarding non-aliasing
3758 of objects of different types. See
3759 @ref{Optimization and Strict Aliasing} for details.
3761 @item -fstack-check
3762 @cindex @option{-fstack-check} (@command{gcc})
3763 Activates stack checking.
3764 See @ref{Stack Overflow Checking} for details.
3766 @item -fstack-usage
3767 @cindex @option{-fstack-usage} (@command{gcc})
3768 Makes the compiler output stack usage information for the program, on a
3769 per-function basis. See @ref{Static Stack Usage Analysis} for details.
3771 @item -fcallgraph-info[=su]
3772 @cindex @option{-fcallgraph-info} (@command{gcc})
3773 Makes the compiler output callgraph information for the program, on a
3774 per-file basis.  The information is generated in the VCG format.  It can
3775 be decorated with stack-usage per-node information.
3777 @item ^-g^/DEBUG^
3778 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3779 Generate debugging information. This information is stored in the object
3780 file and copied from there to the final executable file by the linker,
3781 where it can be read by the debugger. You must use the
3782 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3784 @item -gnat83
3785 @cindex @option{-gnat83} (@command{gcc})
3786 Enforce Ada 83 restrictions.
3788 @item -gnat95
3789 @cindex @option{-gnat95} (@command{gcc})
3790 Enforce Ada 95 restrictions.
3792 @item -gnat05
3793 @cindex @option{-gnat05} (@command{gcc})
3794 Allow full Ada 2005 features.
3796 @item -gnata
3797 @cindex @option{-gnata} (@command{gcc})
3798 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3799 activated. Note that these pragmas can also be controlled using the
3800 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3802 @item -gnatA
3803 @cindex @option{-gnatA} (@command{gcc})
3804 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3805 it will be ignored.
3807 @item -gnatb
3808 @cindex @option{-gnatb} (@command{gcc})
3809 Generate brief messages to @file{stderr} even if verbose mode set.
3811 @item -gnatc
3812 @cindex @option{-gnatc} (@command{gcc})
3813 Check syntax and semantics only (no code generation attempted).
3815 @item -gnatd
3816 @cindex @option{-gnatd} (@command{gcc})
3817 Specify debug options for the compiler. The string of characters after
3818 the @option{-gnatd} specify the specific debug options. The possible
3819 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3820 compiler source file @file{debug.adb} for details of the implemented
3821 debug options. Certain debug options are relevant to applications
3822 programmers, and these are documented at appropriate points in this
3823 users guide.
3825 @item -gnatD
3826 @cindex @option{-gnatD} (@command{gcc})
3827 Create expanded source files for source level debugging. This switch
3828 also suppress generation of cross-reference information
3829 (see @option{-gnatx}).
3831 @item -gnatec=@var{path}
3832 @cindex @option{-gnatec} (@command{gcc})
3833 Specify a configuration pragma file
3834 @ifclear vms
3835 (the equal sign is optional)
3836 @end ifclear
3837 (@pxref{The Configuration Pragmas Files}).
3839 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3840 @cindex @option{-gnateD} (@command{gcc})
3841 Defines a symbol, associated with value, for preprocessing.
3842 (@pxref{Integrated Preprocessing}).
3844 @item -gnatef
3845 @cindex @option{-gnatef} (@command{gcc})
3846 Display full source path name in brief error messages.
3848 @item -gnatem=@var{path}
3849 @cindex @option{-gnatem} (@command{gcc})
3850 Specify a mapping file
3851 @ifclear vms
3852 (the equal sign is optional)
3853 @end ifclear
3854 (@pxref{Units to Sources Mapping Files}).
3856 @item -gnatep=@var{file}
3857 @cindex @option{-gnatep} (@command{gcc})
3858 Specify a preprocessing data file
3859 @ifclear vms
3860 (the equal sign is optional)
3861 @end ifclear
3862 (@pxref{Integrated Preprocessing}).
3864 @item -gnatE
3865 @cindex @option{-gnatE} (@command{gcc})
3866 Full dynamic elaboration checks.
3868 @item -gnatf
3869 @cindex @option{-gnatf} (@command{gcc})
3870 Full errors. Multiple errors per line, all undefined references, do not
3871 attempt to suppress cascaded errors.
3873 @item -gnatF
3874 @cindex @option{-gnatF} (@command{gcc})
3875 Externals names are folded to all uppercase.
3877 @item -gnatg
3878 @cindex @option{-gnatg} (@command{gcc})
3879 Internal GNAT implementation mode. This should not be used for
3880 applications programs, it is intended only for use by the compiler
3881 and its run-time library. For documentation, see the GNAT sources.
3882 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3883 are generated on unreferenced entities, and all warnings are treated
3884 as errors.
3886 @item -gnatG
3887 @cindex @option{-gnatG} (@command{gcc})
3888 List generated expanded code in source form.
3890 @item ^-gnath^/HELP^
3891 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3892 Output usage information. The output is written to @file{stdout}.
3894 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3895 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3896 Identifier character set
3897 @ifclear vms
3898 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3899 @end ifclear
3900 @ifset vms
3901 For details of the possible selections for @var{c},
3902 see @ref{Character Set Control}.
3903 @end ifset
3905 @item -gnatk=@var{n}
3906 @cindex @option{-gnatk} (@command{gcc})
3907 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3909 @item -gnatl
3910 @cindex @option{-gnatl} (@command{gcc})
3911 Output full source listing with embedded error messages.
3913 @item -gnatm=@var{n}
3914 @cindex @option{-gnatm} (@command{gcc})
3915 Limit number of detected error or warning messages to @var{n}
3916 where @var{n} is in the range 1..999_999. The default setting if
3917 no switch is given is 9999. Compilation is terminated if this
3918 limit is exceeded. The equal sign here is optional.
3920 @item -gnatn
3921 @cindex @option{-gnatn} (@command{gcc})
3922 Activate inlining for subprograms for which
3923 pragma @code{inline} is specified. This inlining is performed
3924 by the GCC back-end.
3926 @item -gnatN
3927 @cindex @option{-gnatN} (@command{gcc})
3928 Activate front end inlining for subprograms for which
3929 pragma @code{Inline} is specified. This inlining is performed
3930 by the front end and will be visible in the
3931 @option{-gnatG} output.
3932 In some cases, this has proved more effective than the back end
3933 inlining resulting from the use of
3934 @option{-gnatn}.
3935 Note that
3936 @option{-gnatN} automatically implies
3937 @option{-gnatn} so it is not necessary
3938 to specify both options. There are a few cases that the back-end inlining
3939 catches that cannot be dealt with in the front-end.
3941 @item -gnato
3942 @cindex @option{-gnato} (@command{gcc})
3943 Enable numeric overflow checking (which is not normally enabled by
3944 default). Not that division by zero is a separate check that is not
3945 controlled by this switch (division by zero checking is on by default).
3947 @item -gnatp
3948 @cindex @option{-gnatp} (@command{gcc})
3949 Suppress all checks.
3951 @item -gnatP
3952 @cindex @option{-gnatP} (@command{gcc})
3953 Enable polling. This is required on some systems (notably Windows NT) to
3954 obtain asynchronous abort and asynchronous transfer of control capability.
3955 See the description of pragma Polling in the GNAT Reference Manual for
3956 full details.
3958 @item -gnatq
3959 @cindex @option{-gnatq} (@command{gcc})
3960 Don't quit; try semantics, even if parse errors.
3962 @item -gnatQ
3963 @cindex @option{-gnatQ} (@command{gcc})
3964 Don't quit; generate @file{ALI} and tree files even if illegalities.
3966 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3967 @cindex @option{-gnatR} (@command{gcc})
3968 Output representation information for declared types and objects.
3970 @item -gnats
3971 @cindex @option{-gnats} (@command{gcc})
3972 Syntax check only.
3974 @item -gnatS
3975 @cindex @option{-gnatS} (@command{gcc})
3976 Print package Standard.
3978 @item -gnatt
3979 @cindex @option{-gnatt} (@command{gcc})
3980 Generate tree output file.
3982 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3983 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
3984 All compiler tables start at @var{nnn} times usual starting size.
3986 @item -gnatu
3987 @cindex @option{-gnatu} (@command{gcc})
3988 List units for this compilation.
3990 @item -gnatU
3991 @cindex @option{-gnatU} (@command{gcc})
3992 Tag all error messages with the unique string ``error:''
3994 @item -gnatv
3995 @cindex @option{-gnatv} (@command{gcc})
3996 Verbose mode. Full error output with source lines to @file{stdout}.
3998 @item -gnatV
3999 @cindex @option{-gnatV} (@command{gcc})
4000 Control level of validity checking. See separate section describing
4001 this feature.
4003 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
4004 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4005 Warning mode where
4006 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4007 the exact warnings that
4008 are enabled or disabled (@pxref{Warning Message Control}).
4010 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4011 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4012 Wide character encoding method
4013 @ifclear vms
4014 (@var{e}=n/h/u/s/e/8).
4015 @end ifclear
4016 @ifset vms
4017 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4018 @end ifset
4020 @item -gnatx
4021 @cindex @option{-gnatx} (@command{gcc})
4022 Suppress generation of cross-reference information.
4024 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
4025 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4026 Enable built-in style checks (@pxref{Style Checking}).
4028 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4029 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4030 Distribution stub generation and compilation
4031 @ifclear vms
4032 (@var{m}=r/c for receiver/caller stubs).
4033 @end ifclear
4034 @ifset vms
4035 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4036 to be generated and compiled).
4037 @end ifset
4039 @item ^-I^/SEARCH=^@var{dir}
4040 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4041 @cindex RTL
4042 Direct GNAT to search the @var{dir} directory for source files needed by
4043 the current compilation
4044 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4046 @item ^-I-^/NOCURRENT_DIRECTORY^
4047 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4048 @cindex RTL
4049 Except for the source file named in the command line, do not look for source
4050 files in the directory containing the source file named in the command line
4051 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4053 @ifclear vms
4054 @item -mbig-switch
4055 @cindex @option{-mbig-switch} (@command{gcc})
4056 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4057 This standard gcc switch causes the compiler to use larger offsets in its
4058 jump table representation for @code{case} statements.
4059 This may result in less efficient code, but is sometimes necessary
4060 (for example on HP-UX targets)
4061 @cindex HP-UX and @option{-mbig-switch} option
4062 in order to compile large and/or nested @code{case} statements.
4064 @item -o @var{file}
4065 @cindex @option{-o} (@command{gcc})
4066 This switch is used in @command{gcc} to redirect the generated object file
4067 and its associated ALI file. Beware of this switch with GNAT, because it may
4068 cause the object file and ALI file to have different names which in turn
4069 may confuse the binder and the linker.
4070 @end ifclear
4072 @item -nostdinc
4073 @cindex @option{-nostdinc} (@command{gcc})
4074 Inhibit the search of the default location for the GNAT Run Time
4075 Library (RTL) source files.
4077 @item -nostdlib
4078 @cindex @option{-nostdlib} (@command{gcc})
4079 Inhibit the search of the default location for the GNAT Run Time
4080 Library (RTL) ALI files.
4082 @ifclear vms
4083 @item -O[@var{n}]
4084 @cindex @option{-O} (@command{gcc})
4085 @var{n} controls the optimization level.
4087 @table @asis
4088 @item n = 0
4089 No optimization, the default setting if no @option{-O} appears
4091 @item n = 1
4092 Normal optimization, the default if you specify @option{-O} without
4093 an operand. A good compromise between code quality and compilation
4094 time.
4096 @item n = 2
4097 Extensive optimization, may improve execution time, possibly at the cost of
4098 substantially increased compilation time.
4100 @end table
4101 @end ifclear
4103 @ifset vms
4104 @item  /NOOPTIMIZE
4105 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4106 Equivalent to @option{/OPTIMIZE=NONE}.
4107 This is the default behavior in the absence of an @option{/OPTMIZE}
4108 qualifier.
4110 @item /OPTIMIZE[=(keyword[,...])]
4111 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4112 Selects the level of optimization for your program. The supported
4113 keywords are as follows:
4114 @table @code
4115 @item   ALL
4116 Perform most optimizations, including those that
4117 are expensive.
4118 This is the default if the @option{/OPTMIZE} qualifier is supplied
4119 without keyword options.
4121 @item   NONE
4122 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4124 @item SOME
4125 Perform some optimizations, but omit ones that are costly.
4127 @item   DEVELOPMENT
4128 Same as @code{SOME}.
4130 @item   UNROLL_LOOPS
4131 Try to unroll loops. This keyword may be specified together with
4132 any keyword above other than @code{NONE}. Loop unrolling
4133 usually, but not always, improves the performance of programs.
4134 @end table
4135 @end ifset
4137 @ifclear vms
4138 @item -pass-exit-codes
4139 @cindex @option{-pass-exit-codes} (@command{gcc})
4140 Catch exit codes from the compiler and use the most meaningful as
4141 exit status.
4142 @end ifclear
4144 @item --RTS=@var{rts-path}
4145 @cindex @option{--RTS} (@command{gcc})
4146 Specifies the default location of the runtime library. Same meaning as the
4147 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4149 @item ^-S^/ASM^
4150 @cindex @option{^-S^/ASM^} (@command{gcc})
4151 ^Used in place of @option{-c} to^Used to^
4152 cause the assembler source file to be
4153 generated, using @file{^.s^.S^} as the extension,
4154 instead of the object file.
4155 This may be useful if you need to examine the generated assembly code.
4157 @item ^-fverbose-asm^/VERBOSE_ASM^
4158 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4159 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4160 to cause the generated assembly code file to be annotated with variable
4161 names, making it significantly easier to follow.
4163 @item ^-v^/VERBOSE^
4164 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4165 Show commands generated by the @command{gcc} driver. Normally used only for
4166 debugging purposes or if you need to be sure what version of the
4167 compiler you are executing.
4169 @ifclear vms
4170 @item -V @var{ver}
4171 @cindex @option{-V} (@command{gcc})
4172 Execute @var{ver} version of the compiler. This is the @command{gcc}
4173 version, not the GNAT version.
4174 @end ifclear
4176 @item ^-w^NO_BACK_END_WARNINGS^
4177 @cindex @option{-w} (@command{gcc})
4178 Turn off warnings generated by the back end of the compiler. Use of
4179 this switch also causes the default for front end warnings to be set
4180 to suppress (as though @option{-gnatws} had appeared at the start of
4181 the options.
4183 @end table
4185 @ifclear vms
4186 @c Combining qualifiers does not work on VMS
4187 You may combine a sequence of GNAT switches into a single switch. For
4188 example, the combined switch
4190 @cindex Combining GNAT switches
4191 @smallexample
4192 -gnatofi3
4193 @end smallexample
4195 @noindent
4196 is equivalent to specifying the following sequence of switches:
4198 @smallexample
4199 -gnato -gnatf -gnati3
4200 @end smallexample
4201 @end ifclear
4203 @noindent
4204 The following restrictions apply to the combination of switches
4205 in this manner:
4207 @itemize @bullet
4208 @item
4209 The switch @option{-gnatc} if combined with other switches must come
4210 first in the string.
4212 @item
4213 The switch @option{-gnats} if combined with other switches must come
4214 first in the string.
4216 @item
4217 The switches
4218 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4219 may not be combined with any other switches.
4221 @ifclear vms
4222 @item
4223 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4224 switch), then all further characters in the switch are interpreted
4225 as style modifiers (see description of @option{-gnaty}).
4227 @item
4228 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4229 switch), then all further characters in the switch are interpreted
4230 as debug flags (see description of @option{-gnatd}).
4232 @item
4233 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4234 switch), then all further characters in the switch are interpreted
4235 as warning mode modifiers (see description of @option{-gnatw}).
4237 @item
4238 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4239 switch), then all further characters in the switch are interpreted
4240 as validity checking options (see description of @option{-gnatV}).
4241 @end ifclear
4242 @end itemize
4244 @node Output and Error Message Control
4245 @subsection Output and Error Message Control
4246 @findex stderr
4248 @noindent
4249 The standard default format for error messages is called ``brief format''.
4250 Brief format messages are written to @file{stderr} (the standard error
4251 file) and have the following form:
4253 @smallexample
4254 e.adb:3:04: Incorrect spelling of keyword "function"
4255 e.adb:4:20: ";" should be "is"
4256 @end smallexample
4258 @noindent
4259 The first integer after the file name is the line number in the file,
4260 and the second integer is the column number within the line.
4261 @code{glide} can parse the error messages
4262 and point to the referenced character.
4263 The following switches provide control over the error message
4264 format:
4266 @table @option
4267 @c !sort!
4268 @item -gnatv
4269 @cindex @option{-gnatv} (@command{gcc})
4270 @findex stdout
4271 @ifclear vms
4272 The v stands for verbose.
4273 @end ifclear
4274 The effect of this setting is to write long-format error
4275 messages to @file{stdout} (the standard output file.
4276 The same program compiled with the
4277 @option{-gnatv} switch would generate:
4279 @smallexample
4280 @cartouche
4281 3. funcion X (Q : Integer)
4282    |
4283 >>> Incorrect spelling of keyword "function"
4284 4. return Integer;
4285                  |
4286 >>> ";" should be "is"
4287 @end cartouche
4288 @end smallexample
4290 @noindent
4291 The vertical bar indicates the location of the error, and the @samp{>>>}
4292 prefix can be used to search for error messages. When this switch is
4293 used the only source lines output are those with errors.
4295 @item -gnatl
4296 @cindex @option{-gnatl} (@command{gcc})
4297 @ifclear vms
4298 The @code{l} stands for list.
4299 @end ifclear
4300 This switch causes a full listing of
4301 the file to be generated. The output might look as follows:
4303 @smallexample
4304 @cartouche
4305  1. procedure E is
4306  2.    V : Integer;
4307  3.    funcion X (Q : Integer)
4308        |
4309     >>> Incorrect spelling of keyword "function"
4310  4.     return Integer;
4311                       |
4312     >>> ";" should be "is"
4313  5.    begin
4314  6.       return Q + Q;
4315  7.    end;
4316  8. begin
4317  9.    V := X + X;
4318 10.end E;
4319 @end cartouche
4320 @end smallexample
4322 @noindent
4323 @findex stderr
4324 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4325 standard output is redirected, a brief summary is written to
4326 @file{stderr} (standard error) giving the number of error messages and
4327 warning messages generated.
4329 @item -gnatU
4330 @cindex @option{-gnatU} (@command{gcc})
4331 This switch forces all error messages to be preceded by the unique
4332 string ``error:''. This means that error messages take a few more
4333 characters in space, but allows easy searching for and identification
4334 of error messages.
4336 @item -gnatb
4337 @cindex @option{-gnatb} (@command{gcc})
4338 @ifclear vms
4339 The @code{b} stands for brief.
4340 @end ifclear
4341 This switch causes GNAT to generate the
4342 brief format error messages to @file{stderr} (the standard error
4343 file) as well as the verbose
4344 format message or full listing (which as usual is written to
4345 @file{stdout} (the standard output file).
4347 @item -gnatm=@var{n}
4348 @cindex @option{-gnatm} (@command{gcc})
4349 @ifclear vms
4350 The @code{m} stands for maximum.
4351 @end ifclear
4352 @var{n} is a decimal integer in the
4353 range of 1 to 999 and limits the number of error messages to be
4354 generated. For example, using @option{-gnatm2} might yield
4356 @smallexample
4357 e.adb:3:04: Incorrect spelling of keyword "function"
4358 e.adb:5:35: missing ".."
4359 fatal error: maximum errors reached
4360 compilation abandoned
4361 @end smallexample
4363 @noindent
4364 Note that the equal sign is optional, so the switches
4365 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4367 @item -gnatf
4368 @cindex @option{-gnatf} (@command{gcc})
4369 @cindex Error messages, suppressing
4370 @ifclear vms
4371 The @code{f} stands for full.
4372 @end ifclear
4373 Normally, the compiler suppresses error messages that are likely to be
4374 redundant. This switch causes all error
4375 messages to be generated. In particular, in the case of
4376 references to undefined variables. If a given variable is referenced
4377 several times, the normal format of messages is
4378 @smallexample
4379 e.adb:7:07: "V" is undefined (more references follow)
4380 @end smallexample
4382 @noindent
4383 where the parenthetical comment warns that there are additional
4384 references to the variable @code{V}. Compiling the same program with the
4385 @option{-gnatf} switch yields
4387 @smallexample
4388 e.adb:7:07: "V" is undefined
4389 e.adb:8:07: "V" is undefined
4390 e.adb:8:12: "V" is undefined
4391 e.adb:8:16: "V" is undefined
4392 e.adb:9:07: "V" is undefined
4393 e.adb:9:12: "V" is undefined
4394 @end smallexample
4396 @noindent
4397 The @option{-gnatf} switch also generates additional information for
4398 some error messages.  Some examples are:
4400 @itemize @bullet
4401 @item
4402 Full details on entities not available in high integrity mode
4403 @item
4404 Details on possibly non-portable unchecked conversion
4405 @item
4406 List possible interpretations for ambiguous calls
4407 @item
4408 Additional details on incorrect parameters
4409 @end itemize
4411 @item -gnatq
4412 @cindex @option{-gnatq} (@command{gcc})
4413 @ifclear vms
4414 The @code{q} stands for quit (really ``don't quit'').
4415 @end ifclear
4416 In normal operation mode, the compiler first parses the program and
4417 determines if there are any syntax errors. If there are, appropriate
4418 error messages are generated and compilation is immediately terminated.
4419 This switch tells
4420 GNAT to continue with semantic analysis even if syntax errors have been
4421 found. This may enable the detection of more errors in a single run. On
4422 the other hand, the semantic analyzer is more likely to encounter some
4423 internal fatal error when given a syntactically invalid tree.
4425 @item -gnatQ
4426 @cindex @option{-gnatQ} (@command{gcc})
4427 In normal operation mode, the @file{ALI} file is not generated if any
4428 illegalities are detected in the program. The use of @option{-gnatQ} forces
4429 generation of the @file{ALI} file. This file is marked as being in
4430 error, so it cannot be used for binding purposes, but it does contain
4431 reasonably complete cross-reference information, and thus may be useful
4432 for use by tools (e.g. semantic browsing tools or integrated development
4433 environments) that are driven from the @file{ALI} file. This switch
4434 implies @option{-gnatq}, since the semantic phase must be run to get a
4435 meaningful ALI file.
4437 In addition, if @option{-gnatt} is also specified, then the tree file is
4438 generated even if there are illegalities. It may be useful in this case
4439 to also specify @option{-gnatq} to ensure that full semantic processing
4440 occurs. The resulting tree file can be processed by ASIS, for the purpose
4441 of providing partial information about illegal units, but if the error
4442 causes the tree to be badly malformed, then ASIS may crash during the
4443 analysis.
4445 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4446 being in error, @command{gnatmake} will attempt to recompile the source when it
4447 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4449 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4450 since ALI files are never generated if @option{-gnats} is set.
4452 @end table
4454 @node Warning Message Control
4455 @subsection Warning Message Control
4456 @cindex Warning messages
4457 @noindent
4458 In addition to error messages, which correspond to illegalities as defined
4459 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4460 situations.
4462 First, the compiler considers some constructs suspicious and generates a
4463 warning message to alert you to a possible error. Second, if the
4464 compiler detects a situation that is sure to raise an exception at
4465 run time, it generates a warning message. The following shows an example
4466 of warning messages:
4467 @smallexample
4468 e.adb:4:24: warning: creation of object may raise Storage_Error
4469 e.adb:10:17: warning: static value out of range
4470 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4471 @end smallexample
4473 @noindent
4474 GNAT considers a large number of situations as appropriate
4475 for the generation of warning messages. As always, warnings are not
4476 definite indications of errors. For example, if you do an out-of-range
4477 assignment with the deliberate intention of raising a
4478 @code{Constraint_Error} exception, then the warning that may be
4479 issued does not indicate an error. Some of the situations for which GNAT
4480 issues warnings (at least some of the time) are given in the following
4481 list. This list is not complete, and new warnings are often added to
4482 subsequent versions of GNAT. The list is intended to give a general idea
4483 of the kinds of warnings that are generated.
4485 @itemize @bullet
4486 @item
4487 Possible infinitely recursive calls
4489 @item
4490 Out-of-range values being assigned
4492 @item
4493 Possible order of elaboration problems
4495 @item
4496 Unreachable code
4498 @item
4499 Fixed-point type declarations with a null range
4501 @item
4502 Direct_IO or Sequential_IO instantiated with a type that has access values
4504 @item
4505 Variables that are never assigned a value
4507 @item
4508 Variables that are referenced before being initialized
4510 @item
4511 Task entries with no corresponding @code{accept} statement
4513 @item
4514 Duplicate accepts for the same task entry in a @code{select}
4516 @item
4517 Objects that take too much storage
4519 @item
4520 Unchecked conversion between types of differing sizes
4522 @item
4523 Missing @code{return} statement along some execution path in a function
4525 @item
4526 Incorrect (unrecognized) pragmas
4528 @item
4529 Incorrect external names
4531 @item
4532 Allocation from empty storage pool
4534 @item
4535 Potentially blocking operation in protected type
4537 @item
4538 Suspicious parenthesization of expressions
4540 @item
4541 Mismatching bounds in an aggregate
4543 @item
4544 Attempt to return local value by reference
4546 @item
4547 Premature instantiation of a generic body
4549 @item
4550 Attempt to pack aliased components
4552 @item
4553 Out of bounds array subscripts
4555 @item
4556 Wrong length on string assignment
4558 @item
4559 Violations of style rules if style checking is enabled
4561 @item
4562 Unused @code{with} clauses
4564 @item
4565 @code{Bit_Order} usage that does not have any effect
4567 @item
4568 @code{Standard.Duration} used to resolve universal fixed expression
4570 @item
4571 Dereference of possibly null value
4573 @item
4574 Declaration that is likely to cause storage error
4576 @item
4577 Internal GNAT unit @code{with}'ed by application unit
4579 @item
4580 Values known to be out of range at compile time
4582 @item
4583 Unreferenced labels and variables
4585 @item
4586 Address overlays that could clobber memory
4588 @item
4589 Unexpected initialization when address clause present
4591 @item
4592 Bad alignment for address clause
4594 @item
4595 Useless type conversions
4597 @item
4598 Redundant assignment statements and other redundant constructs
4600 @item
4601 Useless exception handlers
4603 @item
4604 Accidental hiding of name by child unit
4606 @item
4607 Access before elaboration detected at compile time
4609 @item
4610 A range in a @code{for} loop that is known to be null or might be null
4612 @end itemize
4614 @noindent
4615 The following switches are available to control the handling of
4616 warning messages:
4618 @table @option
4619 @c !sort!
4620 @item -gnatwa
4621 @emph{Activate all optional errors.}
4622 @cindex @option{-gnatwa} (@command{gcc})
4623 This switch activates most optional warning messages, see remaining list
4624 in this section for details on optional warning messages that can be
4625 individually controlled.  The warnings that are not turned on by this
4626 switch are
4627 @option{-gnatwd} (implicit dereferencing),
4628 @option{-gnatwh} (hiding),
4629 and @option{-gnatwl} (elaboration warnings).
4630 All other optional warnings are turned on.
4632 @item -gnatwA
4633 @emph{Suppress all optional errors.}
4634 @cindex @option{-gnatwA} (@command{gcc})
4635 This switch suppresses all optional warning messages, see remaining list
4636 in this section for details on optional warning messages that can be
4637 individually controlled.
4639 @item -gnatwb
4640 @emph{Activate warnings on bad fixed values.}
4641 @cindex @option{-gnatwb} (@command{gcc})
4642 @cindex Bad fixed values
4643 @cindex Fixed-point Small value
4644 @cindex Small value
4645 This switch activates warnings for static fixed-point expressions whose
4646 value is not an exact multiple of Small. Such values are implementation
4647 dependent, since an implementation is free to choose either of the multiples
4648 that surround the value. GNAT always chooses the closer one, but this is not
4649 required behavior, and it is better to specify a value that is an exact
4650 multiple, ensuring predictable execution. The default is that such warnings
4651 are not generated.
4653 @item -gnatwB
4654 @emph{Suppress warnings on bad fixed values.}
4655 @cindex @option{-gnatwB} (@command{gcc})
4656 This switch suppresses warnings for static fixed-point expressions whose
4657 value is not an exact multiple of Small.
4659 @item -gnatwc
4660 @emph{Activate warnings on conditionals.}
4661 @cindex @option{-gnatwc} (@command{gcc})
4662 @cindex Conditionals, constant
4663 This switch activates warnings for conditional expressions used in
4664 tests that are known to be True or False at compile time. The default
4665 is that such warnings are not generated.
4666 Note that this warning does
4667 not get issued for the use of boolean variables or constants whose
4668 values are known at compile time, since this is a standard technique
4669 for conditional compilation in Ada, and this would generate too many
4670 ``false positive'' warnings.
4672 This warning option also activates a special test for comparisons using
4673 the operators ``>='' and`` <=''.
4674 If the compiler can tell that only the equality condition is possible,
4675 then it will warn that the ``>'' or ``<'' part of the test
4676 is useless and that the operator could be replaced by ``=''.
4677 An example would be comparing a @code{Natural} variable <= 0.
4679 This warning can also be turned on using @option{-gnatwa}.
4681 @item -gnatwC
4682 @emph{Suppress warnings on conditionals.}
4683 @cindex @option{-gnatwC} (@command{gcc})
4684 This switch suppresses warnings for conditional expressions used in
4685 tests that are known to be True or False at compile time.
4687 @item -gnatwd
4688 @emph{Activate warnings on implicit dereferencing.}
4689 @cindex @option{-gnatwd} (@command{gcc})
4690 If this switch is set, then the use of a prefix of an access type
4691 in an indexed component, slice, or selected component without an
4692 explicit @code{.all} will generate a warning. With this warning
4693 enabled, access checks occur only at points where an explicit
4694 @code{.all} appears in the source code (assuming no warnings are
4695 generated as a result of this switch). The default is that such
4696 warnings are not generated.
4697 Note that @option{-gnatwa} does not affect the setting of
4698 this warning option.
4700 @item -gnatwD
4701 @emph{Suppress warnings on implicit dereferencing.}
4702 @cindex @option{-gnatwD} (@command{gcc})
4703 @cindex Implicit dereferencing
4704 @cindex Dereferencing, implicit
4705 This switch suppresses warnings for implicit dereferences in
4706 indexed components, slices, and selected components.
4708 @item -gnatwe
4709 @emph{Treat warnings as errors.}
4710 @cindex @option{-gnatwe} (@command{gcc})
4711 @cindex Warnings, treat as error
4712 This switch causes warning messages to be treated as errors.
4713 The warning string still appears, but the warning messages are counted
4714 as errors, and prevent the generation of an object file.
4716 @item -gnatwf
4717 @emph{Activate warnings on unreferenced formals.}
4718 @cindex @option{-gnatwf} (@command{gcc})
4719 @cindex Formals, unreferenced
4720 This switch causes a warning to be generated if a formal parameter
4721 is not referenced in the body of the subprogram. This warning can
4722 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4724 @item -gnatwF
4725 @emph{Suppress warnings on unreferenced formals.}
4726 @cindex @option{-gnatwF} (@command{gcc})
4727 This switch suppresses warnings for unreferenced formal
4728 parameters. Note that the
4729 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4730 effect of warning on unreferenced entities other than subprogram
4731 formals.
4733 @item -gnatwg
4734 @emph{Activate warnings on unrecognized pragmas.}
4735 @cindex @option{-gnatwg} (@command{gcc})
4736 @cindex Pragmas, unrecognized
4737 This switch causes a warning to be generated if an unrecognized
4738 pragma is encountered. Apart from issuing this warning, the
4739 pragma is ignored and has no effect. This warning can
4740 also be turned on using @option{-gnatwa}. The default
4741 is that such warnings are issued (satisfying the Ada Reference
4742 Manual requirement that such warnings appear).
4744 @item -gnatwG
4745 @emph{Suppress warnings on unrecognized pragmas.}
4746 @cindex @option{-gnatwG} (@command{gcc})
4747 This switch suppresses warnings for unrecognized pragmas.
4749 @item -gnatwh
4750 @emph{Activate warnings on hiding.}
4751 @cindex @option{-gnatwh} (@command{gcc})
4752 @cindex Hiding of Declarations
4753 This switch activates warnings on hiding declarations.
4754 A declaration is considered hiding
4755 if it is for a non-overloadable entity, and it declares an entity with the
4756 same name as some other entity that is directly or use-visible. The default
4757 is that such warnings are not generated.
4758 Note that @option{-gnatwa} does not affect the setting of this warning option.
4760 @item -gnatwH
4761 @emph{Suppress warnings on hiding.}
4762 @cindex @option{-gnatwH} (@command{gcc})
4763 This switch suppresses warnings on hiding declarations.
4765 @item -gnatwi
4766 @emph{Activate warnings on implementation units.}
4767 @cindex @option{-gnatwi} (@command{gcc})
4768 This switch activates warnings for a @code{with} of an internal GNAT
4769 implementation unit, defined as any unit from the @code{Ada},
4770 @code{Interfaces}, @code{GNAT},
4771 ^^@code{DEC},^ or @code{System}
4772 hierarchies that is not
4773 documented in either the Ada Reference Manual or the GNAT
4774 Programmer's Reference Manual. Such units are intended only
4775 for internal implementation purposes and should not be @code{with}'ed
4776 by user programs. The default is that such warnings are generated
4777 This warning can also be turned on using @option{-gnatwa}.
4779 @item -gnatwI
4780 @emph{Disable warnings on implementation units.}
4781 @cindex @option{-gnatwI} (@command{gcc})
4782 This switch disables warnings for a @code{with} of an internal GNAT
4783 implementation unit.
4785 @item -gnatwj
4786 @emph{Activate warnings on obsolescent features (Annex J).}
4787 @cindex @option{-gnatwj} (@command{gcc})
4788 @cindex Features, obsolescent
4789 @cindex Obsolescent features
4790 If this warning option is activated, then warnings are generated for
4791 calls to subprograms marked with @code{pragma Obsolescent} and
4792 for use of features in Annex J of the Ada Reference Manual. In the
4793 case of Annex J, not all features are flagged. In particular use
4794 of the renamed packages (like @code{Text_IO}) and use of package
4795 @code{ASCII} are not flagged, since these are very common and
4796 would generate many annoying positive warnings. The default is that
4797 such warnings are not generated.
4799 In addition to the above cases, warnings are also generated for
4800 GNAT features that have been provided in past versions but which
4801 have been superseded (typically by features in the new Ada standard).
4802 For example, @code{pragma Ravenscar} will be flagged since its
4803 function is replaced by @code{pragma Profile(Ravenscar)}.
4805 Note that this warning option functions differently from the
4806 restriction @code{No_Obsolescent_Features} in two respects.
4807 First, the restriction applies only to annex J features.
4808 Second, the restriction does flag uses of package @code{ASCII}.
4810 @item -gnatwJ
4811 @emph{Suppress warnings on obsolescent features (Annex J).}
4812 @cindex @option{-gnatwJ} (@command{gcc})
4813 This switch disables warnings on use of obsolescent features.
4815 @item -gnatwk
4816 @emph{Activate warnings on variables that could be constants.}
4817 @cindex @option{-gnatwk} (@command{gcc})
4818 This switch activates warnings for variables that are initialized but
4819 never modified, and then could be declared constants.
4821 @item -gnatwK
4822 @emph{Suppress warnings on variables that could be constants.}
4823 @cindex @option{-gnatwK} (@command{gcc})
4824 This switch disables warnings on variables that could be declared constants.
4826 @item -gnatwl
4827 @emph{Activate warnings for missing elaboration pragmas.}
4828 @cindex @option{-gnatwl} (@command{gcc})
4829 @cindex Elaboration, warnings
4830 This switch activates warnings on missing
4831 @code{Elaborate_All} and @code{Elaborate} pragmas.
4832 See the section in this guide on elaboration checking for details on
4833 when such pragmas should be used. Warnings are also generated if you
4834 are using the static mode of elaboration, and a @code{pragma Elaborate}
4835 is encountered. The default is that such warnings
4836 are not generated.
4837 This warning is not automatically turned on by the use of @option{-gnatwa}.
4839 @item -gnatwL
4840 @emph{Suppress warnings for missing elaboration pragmas.}
4841 @cindex @option{-gnatwL} (@command{gcc})
4842 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
4843 See the section in this guide on elaboration checking for details on
4844 when such pragmas should be used.
4846 @item -gnatwm
4847 @emph{Activate warnings on modified but unreferenced variables.}
4848 @cindex @option{-gnatwm} (@command{gcc})
4849 This switch activates warnings for variables that are assigned (using
4850 an initialization value or with one or more assignment statements) but
4851 whose value is never read. The warning is suppressed for volatile
4852 variables and also for variables that are renamings of other variables
4853 or for which an address clause is given.
4854 This warning can also be turned on using @option{-gnatwa}.
4856 @item -gnatwM
4857 @emph{Disable warnings on modified but unreferenced variables.}
4858 @cindex @option{-gnatwM} (@command{gcc})
4859 This switch disables warnings for variables that are assigned or
4860 initialized, but never read.
4862 @item -gnatwn
4863 @emph{Set normal warnings mode.}
4864 @cindex @option{-gnatwn} (@command{gcc})
4865 This switch sets normal warning mode, in which enabled warnings are
4866 issued and treated as warnings rather than errors. This is the default
4867 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4868 an explicit @option{-gnatws} or
4869 @option{-gnatwe}. It also cancels the effect of the
4870 implicit @option{-gnatwe} that is activated by the
4871 use of @option{-gnatg}.
4873 @item -gnatwo
4874 @emph{Activate warnings on address clause overlays.}
4875 @cindex @option{-gnatwo} (@command{gcc})
4876 @cindex Address Clauses, warnings
4877 This switch activates warnings for possibly unintended initialization
4878 effects of defining address clauses that cause one variable to overlap
4879 another. The default is that such warnings are generated.
4880 This warning can also be turned on using @option{-gnatwa}.
4882 @item -gnatwO
4883 @emph{Suppress warnings on address clause overlays.}
4884 @cindex @option{-gnatwO} (@command{gcc})
4885 This switch suppresses warnings on possibly unintended initialization
4886 effects of defining address clauses that cause one variable to overlap
4887 another.
4889 @item -gnatwp
4890 @emph{Activate warnings on ineffective pragma Inlines.}
4891 @cindex @option{-gnatwp} (@command{gcc})
4892 @cindex Inlining, warnings
4893 This switch activates warnings for failure of front end inlining
4894 (activated by @option{-gnatN}) to inline a particular call. There are
4895 many reasons for not being able to inline a call, including most
4896 commonly that the call is too complex to inline.
4897 This warning can also be turned on using @option{-gnatwa}.
4899 @item -gnatwP
4900 @emph{Suppress warnings on ineffective pragma Inlines.}
4901 @cindex @option{-gnatwP} (@command{gcc})
4902 This switch suppresses warnings on ineffective pragma Inlines. If the
4903 inlining mechanism cannot inline a call, it will simply ignore the
4904 request silently.
4906 @item -gnatwr
4907 @emph{Activate warnings on redundant constructs.}
4908 @cindex @option{-gnatwr} (@command{gcc})
4909 This switch activates warnings for redundant constructs. The following
4910 is the current list of constructs regarded as redundant:
4911 This warning can also be turned on using @option{-gnatwa}.
4913 @itemize @bullet
4914 @item
4915 Assignment of an item to itself.
4916 @item
4917 Type conversion that converts an expression to its own type.
4918 @item
4919 Use of the attribute @code{Base} where @code{typ'Base} is the same
4920 as @code{typ}.
4921 @item
4922 Use of pragma @code{Pack} when all components are placed by a record
4923 representation clause.
4924 @item
4925 Exception handler containing only a reraise statement (raise with no
4926 operand) which has no effect.
4927 @item
4928 Use of the operator abs on an operand that is known at compile time
4929 to be non-negative
4930 @item
4931 Comparison of boolean expressions to an explicit True value.
4932 @end itemize
4934 @item -gnatwR
4935 @emph{Suppress warnings on redundant constructs.}
4936 @cindex @option{-gnatwR} (@command{gcc})
4937 This switch suppresses warnings for redundant constructs.
4939 @item -gnatws
4940 @emph{Suppress all warnings.}
4941 @cindex @option{-gnatws} (@command{gcc})
4942 This switch completely suppresses the
4943 output of all warning messages from the GNAT front end.
4944 Note that it does not suppress warnings from the @command{gcc} back end.
4945 To suppress these back end warnings as well, use the switch @option{-w}
4946 in addition to @option{-gnatws}.
4948 @item -gnatwu
4949 @emph{Activate warnings on unused entities.}
4950 @cindex @option{-gnatwu} (@command{gcc})
4951 This switch activates warnings to be generated for entities that
4952 are declared but not referenced, and for units that are @code{with}'ed
4953 and not
4954 referenced. In the case of packages, a warning is also generated if
4955 no entities in the package are referenced. This means that if the package
4956 is referenced but the only references are in @code{use}
4957 clauses or @code{renames}
4958 declarations, a warning is still generated. A warning is also generated
4959 for a generic package that is @code{with}'ed but never instantiated.
4960 In the case where a package or subprogram body is compiled, and there
4961 is a @code{with} on the corresponding spec
4962 that is only referenced in the body,
4963 a warning is also generated, noting that the
4964 @code{with} can be moved to the body. The default is that
4965 such warnings are not generated.
4966 This switch also activates warnings on unreferenced formals
4967 (it includes the effect of @option{-gnatwf}).
4968 This warning can also be turned on using @option{-gnatwa}.
4970 @item -gnatwU
4971 @emph{Suppress warnings on unused entities.}
4972 @cindex @option{-gnatwU} (@command{gcc})
4973 This switch suppresses warnings for unused entities and packages.
4974 It also turns off warnings on unreferenced formals (and thus includes
4975 the effect of @option{-gnatwF}).
4977 @item -gnatwv
4978 @emph{Activate warnings on unassigned variables.}
4979 @cindex @option{-gnatwv} (@command{gcc})
4980 @cindex Unassigned variable warnings
4981 This switch activates warnings for access to variables which
4982 may not be properly initialized. The default is that
4983 such warnings are generated.
4985 @item -gnatwV
4986 @emph{Suppress warnings on unassigned variables.}
4987 @cindex @option{-gnatwV} (@command{gcc})
4988 This switch suppresses warnings for access to variables which
4989 may not be properly initialized.
4991 @item -gnatwy
4992 @emph{Activate warnings for Ada 2005 compatibility issues.}
4993 @cindex @option{-gnatwy} (@command{gcc})
4994 @cindex Ada 2005 compatibility issues warnings
4995 For the most part Ada 2005 is upwards compatible with Ada 95,
4996 but there are some exceptions (for example the fact that
4997 @code{interface} is now a reserved word in Ada 2005). This
4998 switch activates several warnings to help in identifying
4999 and correcting such incompatibilities. The default is that
5000 these warnings are generated. Note that at one point Ada 2005
5001 was called Ada 0Y, hence the choice of character.
5003 @item -gnatwY
5004 @emph{Disable warnings for Ada 2005 compatibility issues.}
5005 @cindex @option{-gnatwY} (@command{gcc})
5006 @cindex Ada 2005 compatibility issues warnings
5007 This switch suppresses several warnings intended to help in identifying
5008 incompatibilities between Ada 95 and Ada 2005.
5010 @item -gnatwx
5011 @emph{Activate warnings on Export/Import pragmas.}
5012 @cindex @option{-gnatwx} (@command{gcc})
5013 @cindex Export/Import pragma warnings
5014 This switch activates warnings on Export/Import pragmas when
5015 the compiler detects a possible conflict between the Ada and
5016 foreign language calling sequences. For example, the use of
5017 default parameters in a convention C procedure is dubious
5018 because the C compiler cannot supply the proper default, so
5019 a warning is issued. The default is that such warnings are
5020 generated.
5022 @item -gnatwX
5023 @emph{Suppress warnings on Export/Import pragmas.}
5024 @cindex @option{-gnatwX} (@command{gcc})
5025 This switch suppresses warnings on Export/Import pragmas.
5026 The sense of this is that you are telling the compiler that
5027 you know what you are doing in writing the pragma, and it
5028 should not complain at you.
5030 @item -gnatwz
5031 @emph{Activate warnings on unchecked conversions.}
5032 @cindex @option{-gnatwz} (@command{gcc})
5033 @cindex Unchecked_Conversion warnings
5034 This switch activates warnings for unchecked conversions
5035 where the types are known at compile time to have different
5036 sizes. The default
5037 is that such warnings are generated.
5039 @item -gnatwZ
5040 @emph{Suppress warnings on unchecked conversions.}
5041 @cindex @option{-gnatwZ} (@command{gcc})
5042 This switch suppresses warnings for unchecked conversions
5043 where the types are known at compile time to have different
5044 sizes.
5046 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5047 @cindex @option{-Wuninitialized}
5048 The warnings controlled by the @option{-gnatw} switch are generated by the
5049 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
5050 can provide additional warnings. One such useful warning is provided by
5051 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
5052 conjunction with turning on optimization mode. This causes the flow
5053 analysis circuits of the back end optimizer to output additional
5054 warnings about uninitialized variables.
5056 @item ^-w^/NO_BACK_END_WARNINGS^
5057 @cindex @option{-w}
5058 This switch suppresses warnings from the @option{^gcc^GCC^} back end. The
5059 code generator detects a number of warning situations that are missed
5060 by the @option{GNAT} front end, and this switch can be used to suppress them.
5061 The use of this switch also sets the default front end warning mode to
5062 @option{-gnatws}, that is, front end warnings suppressed as well.
5064 @end table
5066 @noindent
5067 @ifclear vms
5068 A string of warning parameters can be used in the same parameter. For example:
5070 @smallexample
5071 -gnatwaLe
5072 @end smallexample
5074 @noindent
5075 will turn on all optional warnings except for elaboration pragma warnings,
5076 and also specify that warnings should be treated as errors.
5077 @end ifclear
5078 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5080 @table @option
5081 @c !sort!
5082 @item -gnatwC
5083 @item -gnatwD
5084 @item -gnatwF
5085 @item -gnatwg
5086 @item -gnatwH
5087 @item -gnatwi
5088 @item -gnatwJ
5089 @item -gnatwK
5090 @item -gnatwL
5091 @item -gnatwM
5092 @item -gnatwn
5093 @item -gnatwo
5094 @item -gnatwP
5095 @item -gnatwR
5096 @item -gnatwU
5097 @item -gnatwv
5098 @item -gnatwz
5099 @item -gnatwx
5101 @end table
5103 @node Debugging and Assertion Control
5104 @subsection Debugging and Assertion Control
5106 @table @option
5107 @item -gnata
5108 @cindex @option{-gnata} (@command{gcc})
5109 @findex Assert
5110 @findex Debug
5111 @cindex Assertions
5113 @noindent
5114 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5115 are ignored. This switch, where @samp{a} stands for assert, causes
5116 @code{Assert} and @code{Debug} pragmas to be activated.
5118 The pragmas have the form:
5120 @smallexample
5121 @cartouche
5122    @b{pragma} Assert (@var{Boolean-expression} [,
5123                       @var{static-string-expression}])
5124    @b{pragma} Debug (@var{procedure call})
5125 @end cartouche
5126 @end smallexample
5128 @noindent
5129 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5130 If the result is @code{True}, the pragma has no effect (other than
5131 possible side effects from evaluating the expression). If the result is
5132 @code{False}, the exception @code{Assert_Failure} declared in the package
5133 @code{System.Assertions} is
5134 raised (passing @var{static-string-expression}, if present, as the
5135 message associated with the exception). If no string expression is
5136 given the default is a string giving the file name and line number
5137 of the pragma.
5139 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5140 @code{pragma Debug} may appear within a declaration sequence, allowing
5141 debugging procedures to be called between declarations.
5143 @ifset vms
5144 @item /DEBUG[=debug-level]
5145 @itemx  /NODEBUG
5146 Specifies how much debugging information is to be included in
5147 the resulting object file where 'debug-level' is one of the following:
5148 @table @code
5149 @item   TRACEBACK
5150 Include both debugger symbol records and traceback
5151 the object file.
5152 This is the default setting.
5153 @item   ALL
5154 Include both debugger symbol records and traceback in
5155 object file.
5156 @item   NONE
5157 Excludes both debugger symbol records and traceback
5158 the object file. Same as /NODEBUG.
5159 @item   SYMBOLS
5160 Includes only debugger symbol records in the object
5161 file. Note that this doesn't include traceback information.
5162 @end table
5163 @end ifset
5164 @end table
5166 @node Validity Checking
5167 @subsection Validity Checking
5168 @findex Validity Checking
5170 @noindent
5171 The Ada 95 Reference Manual has specific requirements for checking
5172 for invalid values. In particular, RM 13.9.1 requires that the
5173 evaluation of invalid values (for example from unchecked conversions),
5174 not result in erroneous execution. In GNAT, the result of such an
5175 evaluation in normal default mode is to either use the value
5176 unmodified, or to raise Constraint_Error in those cases where use
5177 of the unmodified value would cause erroneous execution. The cases
5178 where unmodified values might lead to erroneous execution are case
5179 statements (where a wild jump might result from an invalid value),
5180 and subscripts on the left hand side (where memory corruption could
5181 occur as a result of an invalid value).
5183 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5184 checking mode.
5185 @ifclear vms
5186 The @code{x} argument is a string of letters that
5187 indicate validity checks that are performed or not performed in addition
5188 to the default checks described above.
5189 @end ifclear
5190 @ifset vms
5191 The options allowed for this qualifier
5192 indicate validity checks that are performed or not performed in addition
5193 to the default checks described above.
5194 @end ifset
5196 @table @option
5197 @c !sort!
5198 @item -gnatVa
5199 @emph{All validity checks.}
5200 @cindex @option{-gnatVa} (@command{gcc})
5201 All validity checks are turned on.
5202 @ifclear vms
5203 That is, @option{-gnatVa} is
5204 equivalent to @option{gnatVcdfimorst}.
5205 @end ifclear
5207 @item -gnatVc
5208 @emph{Validity checks for copies.}
5209 @cindex @option{-gnatVc} (@command{gcc})
5210 The right hand side of assignments, and the initializing values of
5211 object declarations are validity checked.
5213 @item -gnatVd
5214 @emph{Default (RM) validity checks.}
5215 @cindex @option{-gnatVd} (@command{gcc})
5216 Some validity checks are done by default following normal Ada semantics
5217 (RM 13.9.1 (9-11)).
5218 A check is done in case statements that the expression is within the range
5219 of the subtype. If it is not, Constraint_Error is raised.
5220 For assignments to array components, a check is done that the expression used
5221 as index is within the range. If it is not, Constraint_Error is raised.
5222 Both these validity checks may be turned off using switch @option{-gnatVD}.
5223 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5224 switch @option{-gnatVd} will leave the checks turned on.
5225 Switch @option{-gnatVD} should be used only if you are sure that all such
5226 expressions have valid values. If you use this switch and invalid values
5227 are present, then the program is erroneous, and wild jumps or memory
5228 overwriting may occur.
5230 @item -gnatVf
5231 @emph{Validity checks for floating-point values.}
5232 @cindex @option{-gnatVf} (@command{gcc})
5233 In the absence of this switch, validity checking occurs only for discrete
5234 values. If @option{-gnatVf} is specified, then validity checking also applies
5235 for floating-point values, and NaN's and infinities are considered invalid,
5236 as well as out of range values for constrained types. Note that this means
5237 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5238 in which floating-point values are checked depends on the setting of other
5239 options. For example,
5240 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5241 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5242 (the order does not matter) specifies that floating-point parameters of mode
5243 @code{in} should be validity checked.
5245 @item -gnatVi
5246 @emph{Validity checks for @code{in} mode parameters}
5247 @cindex @option{-gnatVi} (@command{gcc})
5248 Arguments for parameters of mode @code{in} are validity checked in function
5249 and procedure calls at the point of call.
5251 @item -gnatVm
5252 @emph{Validity checks for @code{in out} mode parameters.}
5253 @cindex @option{-gnatVm} (@command{gcc})
5254 Arguments for parameters of mode @code{in out} are validity checked in
5255 procedure calls at the point of call. The @code{'m'} here stands for
5256 modify, since this concerns parameters that can be modified by the call.
5257 Note that there is no specific option to test @code{out} parameters,
5258 but any reference within the subprogram will be tested in the usual
5259 manner, and if an invalid value is copied back, any reference to it
5260 will be subject to validity checking.
5262 @item -gnatVn
5263 @emph{No validity checks.}
5264 @cindex @option{-gnatVn} (@command{gcc})
5265 This switch turns off all validity checking, including the default checking
5266 for case statements and left hand side subscripts. Note that the use of
5267 the switch @option{-gnatp} suppresses all run-time checks, including
5268 validity checks, and thus implies @option{-gnatVn}. When this switch
5269 is used, it cancels any other @option{-gnatV} previously issued.
5271 @item -gnatVo
5272 @emph{Validity checks for operator and attribute operands.}
5273 @cindex @option{-gnatVo} (@command{gcc})
5274 Arguments for predefined operators and attributes are validity checked.
5275 This includes all operators in package @code{Standard},
5276 the shift operators defined as intrinsic in package @code{Interfaces}
5277 and operands for attributes such as @code{Pos}. Checks are also made
5278 on individual component values for composite comparisons.
5280 @item -gnatVp
5281 @emph{Validity checks for parameters.}
5282 @cindex @option{-gnatVp} (@command{gcc})
5283 This controls the treatment of parameters within a subprogram (as opposed
5284 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5285 of parameters on a call. If either of these call options is used, then
5286 normally an assumption is made within a subprogram that the input arguments
5287 have been validity checking at the point of call, and do not need checking
5288 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5289 is not made, and parameters are not assumed to be valid, so their validity
5290 will be checked (or rechecked) within the subprogram.
5292 @item -gnatVr
5293 @emph{Validity checks for function returns.}
5294 @cindex @option{-gnatVr} (@command{gcc})
5295 The expression in @code{return} statements in functions is validity
5296 checked.
5298 @item -gnatVs
5299 @emph{Validity checks for subscripts.}
5300 @cindex @option{-gnatVs} (@command{gcc})
5301 All subscripts expressions are checked for validity, whether they appear
5302 on the right side or left side (in default mode only left side subscripts
5303 are validity checked).
5305 @item -gnatVt
5306 @emph{Validity checks for tests.}
5307 @cindex @option{-gnatVt} (@command{gcc})
5308 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5309 statements are checked, as well as guard expressions in entry calls.
5311 @end table
5313 @noindent
5314 The @option{-gnatV} switch may be followed by
5315 ^a string of letters^a list of options^
5316 to turn on a series of validity checking options.
5317 For example,
5318 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5319 specifies that in addition to the default validity checking, copies and
5320 function return expressions are to be validity checked.
5321 In order to make it easier
5322 to specify the desired combination of effects,
5323 @ifclear vms
5324 the upper case letters @code{CDFIMORST} may
5325 be used to turn off the corresponding lower case option.
5326 @end ifclear
5327 @ifset vms
5328 the prefix @code{NO} on an option turns off the corresponding validity
5329 checking:
5330 @itemize @bullet
5331 @item @code{NOCOPIES}
5332 @item @code{NODEFAULT}
5333 @item @code{NOFLOATS}
5334 @item @code{NOIN_PARAMS}
5335 @item @code{NOMOD_PARAMS}
5336 @item @code{NOOPERANDS}
5337 @item @code{NORETURNS}
5338 @item @code{NOSUBSCRIPTS}
5339 @item @code{NOTESTS}
5340 @end itemize
5341 @end ifset
5342 Thus
5343 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5344 turns on all validity checking options except for
5345 checking of @code{@b{in out}} procedure arguments.
5347 The specification of additional validity checking generates extra code (and
5348 in the case of @option{-gnatVa} the code expansion can be substantial.
5349 However, these additional checks can be very useful in detecting
5350 uninitialized variables, incorrect use of unchecked conversion, and other
5351 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5352 is useful in conjunction with the extra validity checking, since this
5353 ensures that wherever possible uninitialized variables have invalid values.
5355 See also the pragma @code{Validity_Checks} which allows modification of
5356 the validity checking mode at the program source level, and also allows for
5357 temporary disabling of validity checks.
5359 @node Style Checking
5360 @subsection Style Checking
5361 @findex Style checking
5363 @noindent
5364 The @option{-gnaty^x^(option,option,...)^} switch
5365 @cindex @option{-gnaty} (@command{gcc})
5366 causes the compiler to
5367 enforce specified style rules. A limited set of style rules has been used
5368 in writing the GNAT sources themselves. This switch allows user programs
5369 to activate all or some of these checks. If the source program fails a
5370 specified style check, an appropriate warning message is given, preceded by
5371 the character sequence ``(style)''.
5372 @ifset vms
5373 @code{(option,option,...)} is a sequence of keywords
5374 @end ifset
5375 @ifclear vms
5376 The string @var{x} is a sequence of letters or digits
5377 @end ifclear
5378 indicating the particular style
5379 checks to be performed. The following checks are defined:
5381 @table @option
5382 @c !sort!
5383 @item 1-9
5384 @emph{Specify indentation level.}
5385 If a digit from 1-9 appears
5386 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5387 then proper indentation is checked, with the digit indicating the
5388 indentation level required.
5389 The general style of required indentation is as specified by
5390 the examples in the Ada Reference Manual. Full line comments must be
5391 aligned with the @code{--} starting on a column that is a multiple of
5392 the alignment level.
5394 @item ^a^ATTRIBUTE^
5395 @emph{Check attribute casing.}
5396 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5397 then attribute names, including the case of keywords such as @code{digits}
5398 used as attributes names, must be written in mixed case, that is, the
5399 initial letter and any letter following an underscore must be uppercase.
5400 All other letters must be lowercase.
5402 @item ^b^BLANKS^
5403 @emph{Blanks not allowed at statement end.}
5404 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5405 trailing blanks are not allowed at the end of statements. The purpose of this
5406 rule, together with h (no horizontal tabs), is to enforce a canonical format
5407 for the use of blanks to separate source tokens.
5409 @item ^c^COMMENTS^
5410 @emph{Check comments.}
5411 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5412 then comments must meet the following set of rules:
5414 @itemize @bullet
5416 @item
5417 The ``@code{--}'' that starts the column must either start in column one,
5418 or else at least one blank must precede this sequence.
5420 @item
5421 Comments that follow other tokens on a line must have at least one blank
5422 following the ``@code{--}'' at the start of the comment.
5424 @item
5425 Full line comments must have two blanks following the ``@code{--}'' that
5426 starts the comment, with the following exceptions.
5428 @item
5429 A line consisting only of the ``@code{--}'' characters, possibly preceded
5430 by blanks is permitted.
5432 @item
5433 A comment starting with ``@code{--x}'' where @code{x} is a special character
5434 is permitted.
5435 This allows proper processing of the output generated by specialized tools
5436 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5437 annotation
5438 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5439 special character is defined as being in one of the ASCII ranges
5440 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5441 Note that this usage is not permitted
5442 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5444 @item
5445 A line consisting entirely of minus signs, possibly preceded by blanks, is
5446 permitted. This allows the construction of box comments where lines of minus
5447 signs are used to form the top and bottom of the box.
5449 @item
5450 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5451 least one blank follows the initial ``@code{--}''. Together with the preceding
5452 rule, this allows the construction of box comments, as shown in the following
5453 example:
5454 @smallexample
5455 ---------------------------
5456 -- This is a box comment --
5457 -- with two text lines.  --
5458 ---------------------------
5459 @end smallexample
5460 @end itemize
5462 @item ^d^DOS_LINE_ENDINGS^
5463 @emph{Check no DOS line terminators present.}
5464 If the ^letter d^word DOS_LINE_ENDINGS^ appears in the string after
5465 @option{-gnaty} then all lines must be terminated by a single ASCII.LF
5466 character (in particular the DOS line terminator sequence CR/LF is not
5467 allowed).
5469 @item ^e^END^
5470 @emph{Check end/exit labels.}
5471 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5472 optional labels on @code{end} statements ending subprograms and on
5473 @code{exit} statements exiting named loops, are required to be present.
5475 @item ^f^VTABS^
5476 @emph{No form feeds or vertical tabs.}
5477 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5478 neither form feeds nor vertical tab characters are permitted
5479 in the source text.
5481 @item ^h^HTABS^
5482 @emph{No horizontal tabs.}
5483 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5484 horizontal tab characters are not permitted in the source text.
5485 Together with the b (no blanks at end of line) check, this
5486 enforces a canonical form for the use of blanks to separate
5487 source tokens.
5489 @item ^i^IF_THEN^
5490 @emph{Check if-then layout.}
5491 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5492 then the keyword @code{then} must appear either on the same
5493 line as corresponding @code{if}, or on a line on its own, lined
5494 up under the @code{if} with at least one non-blank line in between
5495 containing all or part of the condition to be tested.
5497 @item ^I^IN_MODE^
5498 @emph{check mode IN keywords}
5499 If the ^letter I (upper case)^word IN_MODE^ appears in the string
5500 after @option{-gnaty} then mode @code{in} (the default mode) is not
5501 allowed to be given explicitly. @code{in out} is fine,
5502 but not @code{in} on its own.
5504 @item ^k^KEYWORD^
5505 @emph{Check keyword casing.}
5506 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5507 all keywords must be in lower case (with the exception of keywords
5508 such as @code{digits} used as attribute names to which this check
5509 does not apply).
5511 @item ^l^LAYOUT^
5512 @emph{Check layout.}
5513 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5514 layout of statement and declaration constructs must follow the
5515 recommendations in the Ada Reference Manual, as indicated by the
5516 form of the syntax rules. For example an @code{else} keyword must
5517 be lined up with the corresponding @code{if} keyword.
5519 There are two respects in which the style rule enforced by this check
5520 option are more liberal than those in the Ada Reference Manual. First
5521 in the case of record declarations, it is permissible to put the
5522 @code{record} keyword on the same line as the @code{type} keyword, and
5523 then the @code{end} in @code{end record} must line up under @code{type}.
5524 For example, either of the following two layouts is acceptable:
5526 @smallexample @c ada
5527 @cartouche
5528 type q is record
5529    a : integer;
5530    b : integer;
5531 end record;
5533 type q is
5534    record
5535       a : integer;
5536       b : integer;
5537    end record;
5538 @end cartouche
5539 @end smallexample
5541 @noindent
5542 Second, in the case of a block statement, a permitted alternative
5543 is to put the block label on the same line as the @code{declare} or
5544 @code{begin} keyword, and then line the @code{end} keyword up under
5545 the block label. For example both the following are permitted:
5547 @smallexample @c ada
5548 @cartouche
5549 Block : declare
5550    A : Integer := 3;
5551 begin
5552    Proc (A, A);
5553 end Block;
5555 Block :
5556    declare
5557       A : Integer := 3;
5558    begin
5559       Proc (A, A);
5560    end Block;
5561 @end cartouche
5562 @end smallexample
5564 @noindent
5565 The same alternative format is allowed for loops. For example, both of
5566 the following are permitted:
5568 @smallexample @c ada
5569 @cartouche
5570 Clear : while J < 10 loop
5571    A (J) := 0;
5572 end loop Clear;
5574 Clear :
5575    while J < 10 loop
5576       A (J) := 0;
5577    end loop Clear;
5578 @end cartouche
5579 @end smallexample
5581 @item ^Lnnn^MAX_NESTING=nnn^
5582 @emph{Set maximum nesting level}
5583 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5584 the range 0-999, appears in the string after @option{-gnaty} then the
5585 maximum level of nesting of constructs (including subprograms, loops,
5586 blocks, packages, and conditionals) may not exceed the given value. A
5587 value of zero disconnects this style check.
5589 @item ^m^LINE_LENGTH^
5590 @emph{Check maximum line length.}
5591 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5592 then the length of source lines must not exceed 79 characters, including
5593 any trailing blanks. The value of 79 allows convenient display on an
5594 80 character wide device or window, allowing for possible special
5595 treatment of 80 character lines. Note that this count is of
5596 characters in the source text. This means that a tab character counts
5597 as one character in this count but a wide character sequence counts as
5598 a single character (however many bytes are needed in the encoding).
5600 @item ^Mnnn^MAX_LENGTH=nnn^
5601 @emph{Set maximum line length.}
5602 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5603 the string after @option{-gnaty} then the length of lines must not exceed the
5604 given value. The maximum value that can be specified is 32767.
5606 @item ^n^STANDARD_CASING^
5607 @emph{Check casing of entities in Standard.}
5608 If the ^letter n^word STANDARD_CASING^ appears in the string
5609 after @option{-gnaty} then any identifier from Standard must be cased
5610 to match the presentation in the Ada Reference Manual (for example,
5611 @code{Integer} and @code{ASCII.NUL}).
5613 @item ^o^ORDERED_SUBPROGRAMS^
5614 @emph{Check order of subprogram bodies.}
5615 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5616 after @option{-gnaty} then all subprogram bodies in a given scope
5617 (e.g. a package body) must be in alphabetical order. The ordering
5618 rule uses normal Ada rules for comparing strings, ignoring casing
5619 of letters, except that if there is a trailing numeric suffix, then
5620 the value of this suffix is used in the ordering (e.g. Junk2 comes
5621 before Junk10).
5623 @item ^p^PRAGMA^
5624 @emph{Check pragma casing.}
5625 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5626 pragma names must be written in mixed case, that is, the
5627 initial letter and any letter following an underscore must be uppercase.
5628 All other letters must be lowercase.
5630 @item ^r^REFERENCES^
5631 @emph{Check references.}
5632 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5633 then all identifier references must be cased in the same way as the
5634 corresponding declaration. No specific casing style is imposed on
5635 identifiers. The only requirement is for consistency of references
5636 with declarations.
5638 @item ^s^SPECS^
5639 @emph{Check separate specs.}
5640 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5641 separate declarations (``specs'') are required for subprograms (a
5642 body is not allowed to serve as its own declaration). The only
5643 exception is that parameterless library level procedures are
5644 not required to have a separate declaration. This exception covers
5645 the most frequent form of main program procedures.
5647 @item ^t^TOKEN^
5648 @emph{Check token spacing.}
5649 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5650 the following token spacing rules are enforced:
5652 @itemize @bullet
5654 @item
5655 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5657 @item
5658 The token @code{=>} must be surrounded by spaces.
5660 @item
5661 The token @code{<>} must be preceded by a space or a left parenthesis.
5663 @item
5664 Binary operators other than @code{**} must be surrounded by spaces.
5665 There is no restriction on the layout of the @code{**} binary operator.
5667 @item
5668 Colon must be surrounded by spaces.
5670 @item
5671 Colon-equal (assignment, initialization) must be surrounded by spaces.
5673 @item
5674 Comma must be the first non-blank character on the line, or be
5675 immediately preceded by a non-blank character, and must be followed
5676 by a space.
5678 @item
5679 If the token preceding a left parenthesis ends with a letter or digit, then
5680 a space must separate the two tokens.
5682 @item
5683 A right parenthesis must either be the first non-blank character on
5684 a line, or it must be preceded by a non-blank character.
5686 @item
5687 A semicolon must not be preceded by a space, and must not be followed by
5688 a non-blank character.
5690 @item
5691 A unary plus or minus may not be followed by a space.
5693 @item
5694 A vertical bar must be surrounded by spaces.
5695 @end itemize
5697 @item ^u^UNNECESSARY_BLANK_LINES^
5698 @emph{Check unnecessary blank lines.}
5699 Check for unnecessary blank lines. A blank line is considered
5700 unnecessary if it appears at the end of the file, or if more than
5701 one blank line occurs in sequence.
5703 @item ^x^XTRA_PARENS^
5704 @emph{Check extra parentheses.}
5705 Check for the use of an unnecessary extra level of parentheses (C-style)
5706 around conditions in @code{if} statements, @code{while} statements and
5707 @code{exit} statements.
5709 @end table
5711 @noindent
5712 In the above rules, appearing in column one is always permitted, that is,
5713 counts as meeting either a requirement for a required preceding space,
5714 or as meeting a requirement for no preceding space.
5716 Appearing at the end of a line is also always permitted, that is, counts
5717 as meeting either a requirement for a following space, or as meeting
5718 a requirement for no following space.
5720 @noindent
5721 If any of these style rules is violated, a message is generated giving
5722 details on the violation. The initial characters of such messages are
5723 always ``@code{(style)}''. Note that these messages are treated as warning
5724 messages, so they normally do not prevent the generation of an object
5725 file. The @option{-gnatwe} switch can be used to treat warning messages,
5726 including style messages, as fatal errors.
5728 The switch
5729 @ifclear vms
5730 @option{-gnaty} on its own (that is not
5731 followed by any letters or digits),
5732 is equivalent to @code{gnaty3abcefhiklmnprst}, that is all checking
5733 options enabled with the exception of @option{-gnatyo},
5734 @option{-gnatyd}, @option{-gnatyu}, and @option{-gnatyx}.
5735 @end ifclear
5736 @ifset vms
5737 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5738 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
5739 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
5740 @end ifset
5741 an indentation level of 3 is set. This is similar to the standard
5742 checking option that is used for the GNAT sources.
5744 The switch
5745 @ifclear vms
5746 @option{-gnatyN}
5747 @end ifclear
5748 @ifset vms
5749 /STYLE_CHECKS=NONE
5750 @end ifset
5751 clears any previously set style checks.
5753 @node Run-Time Checks
5754 @subsection Run-Time Checks
5755 @cindex Division by zero
5756 @cindex Access before elaboration
5757 @cindex Checks, division by zero
5758 @cindex Checks, access before elaboration
5759 @cindex Checks, stack overflow checking
5761 @noindent
5762 If you compile with the default options, GNAT will insert many run-time
5763 checks into the compiled code, including code that performs range
5764 checking against constraints, but not arithmetic overflow checking for
5765 integer operations (including division by zero), checks for access
5766 before elaboration on subprogram calls, or stack overflow checking. All
5767 other run-time checks, as required by the Ada 95 Reference Manual, are
5768 generated by default. The following @command{gcc} switches refine this
5769 default behavior:
5771 @table @option
5772 @c !sort!
5773 @item -gnatp
5774 @cindex @option{-gnatp} (@command{gcc})
5775 @cindex Suppressing checks
5776 @cindex Checks, suppressing
5777 @findex Suppress
5778 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5779 had been present in the source. Validity checks are also suppressed (in
5780 other words @option{-gnatp} also implies @option{-gnatVn}.
5781 Use this switch to improve the performance
5782 of the code at the expense of safety in the presence of invalid data or
5783 program bugs.
5785 @item -gnato
5786 @cindex @option{-gnato} (@command{gcc})
5787 @cindex Overflow checks
5788 @cindex Check, overflow
5789 Enables overflow checking for integer operations.
5790 This causes GNAT to generate slower and larger executable
5791 programs by adding code to check for overflow (resulting in raising
5792 @code{Constraint_Error} as required by standard Ada
5793 semantics). These overflow checks correspond to situations in which
5794 the true value of the result of an operation may be outside the base
5795 range of the result type. The following example shows the distinction:
5797 @smallexample @c ada
5798 X1 : Integer := Integer'Last;
5799 X2 : Integer range 1 .. 5 := 5;
5800 X3 : Integer := Integer'Last;
5801 X4 : Integer range 1 .. 5 := 5;
5802 F  : Float := 2.0E+20;
5804 X1 := X1 + 1;
5805 X2 := X2 + 1;
5806 X3 := Integer (F);
5807 X4 := Integer (F);
5808 @end smallexample
5810 @noindent
5811 Here the first addition results in a value that is outside the base range
5812 of Integer, and hence requires an overflow check for detection of the
5813 constraint error. Thus the first assignment to @code{X1} raises a
5814 @code{Constraint_Error} exception only if @option{-gnato} is set.
5816 The second increment operation results in a violation
5817 of the explicit range constraint, and such range checks are always
5818 performed (unless specifically suppressed with a pragma @code{suppress}
5819 or the use of @option{-gnatp}).
5821 The two conversions of @code{F} both result in values that are outside
5822 the base range of type @code{Integer} and thus will raise
5823 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5824 The fact that the result of the second conversion is assigned to
5825 variable @code{X4} with a restricted range is irrelevant, since the problem
5826 is in the conversion, not the assignment.
5828 Basically the rule is that in the default mode (@option{-gnato} not
5829 used), the generated code assures that all integer variables stay
5830 within their declared ranges, or within the base range if there is
5831 no declared range. This prevents any serious problems like indexes
5832 out of range for array operations.
5834 What is not checked in default mode is an overflow that results in
5835 an in-range, but incorrect value. In the above example, the assignments
5836 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5837 range of the target variable, but the result is wrong in the sense that
5838 it is too large to be represented correctly. Typically the assignment
5839 to @code{X1} will result in wrap around to the largest negative number.
5840 The conversions of @code{F} will result in some @code{Integer} value
5841 and if that integer value is out of the @code{X4} range then the
5842 subsequent assignment would generate an exception.
5844 @findex Machine_Overflows
5845 Note that the @option{-gnato} switch does not affect the code generated
5846 for any floating-point operations; it applies only to integer
5847 semantics).
5848 For floating-point, GNAT has the @code{Machine_Overflows}
5849 attribute set to @code{False} and the normal mode of operation is to
5850 generate IEEE NaN and infinite values on overflow or invalid operations
5851 (such as dividing 0.0 by 0.0).
5853 The reason that we distinguish overflow checking from other kinds of
5854 range constraint checking is that a failure of an overflow check can
5855 generate an incorrect value, but cannot cause erroneous behavior. This
5856 is unlike the situation with a constraint check on an array subscript,
5857 where failure to perform the check can result in random memory description,
5858 or the range check on a case statement, where failure to perform the check
5859 can cause a wild jump.
5861 Note again that @option{-gnato} is off by default, so overflow checking is
5862 not performed in default mode. This means that out of the box, with the
5863 default settings, GNAT does not do all the checks expected from the
5864 language description in the Ada Reference Manual. If you want all constraint
5865 checks to be performed, as described in this Manual, then you must
5866 explicitly use the -gnato switch either on the @command{gnatmake} or
5867 @command{gcc} command.
5869 @item -gnatE
5870 @cindex @option{-gnatE} (@command{gcc})
5871 @cindex Elaboration checks
5872 @cindex Check, elaboration
5873 Enables dynamic checks for access-before-elaboration
5874 on subprogram calls and generic instantiations.
5875 For full details of the effect and use of this switch,
5876 @xref{Compiling Using gcc}.
5878 @item -fstack-check
5879 @cindex @option{-fstack-check} (@command{gcc})
5880 @cindex Stack Overflow Checking
5881 @cindex Checks, stack overflow checking
5882 Activates stack overflow checking. For full details of the effect and use of
5883 this switch see @ref{Stack Overflow Checking}.
5884 @end table
5886 @findex Unsuppress
5887 @noindent
5888 The setting of these switches only controls the default setting of the
5889 checks. You may modify them using either @code{Suppress} (to remove
5890 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5891 the program source.
5893 @node Using gcc for Syntax Checking
5894 @subsection Using @command{gcc} for Syntax Checking
5895 @table @option
5896 @item -gnats
5897 @cindex @option{-gnats} (@command{gcc})
5898 @ifclear vms
5900 @noindent
5901 The @code{s} stands for ``syntax''.
5902 @end ifclear
5904 Run GNAT in syntax checking only mode. For
5905 example, the command
5907 @smallexample
5908 $ gcc -c -gnats x.adb
5909 @end smallexample
5911 @noindent
5912 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5913 series of files in a single command
5914 @ifclear vms
5915 , and can use wild cards to specify such a group of files.
5916 Note that you must specify the @option{-c} (compile
5917 only) flag in addition to the @option{-gnats} flag.
5918 @end ifclear
5920 You may use other switches in conjunction with @option{-gnats}. In
5921 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5922 format of any generated error messages.
5924 When the source file is empty or contains only empty lines and/or comments,
5925 the output is a warning:
5927 @smallexample
5928 $ gcc -c -gnats -x ada toto.txt
5929 toto.txt:1:01: warning: empty file, contains no compilation units
5931 @end smallexample
5933 Otherwise, the output is simply the error messages, if any. No object file or
5934 ALI file is generated by a syntax-only compilation. Also, no units other
5935 than the one specified are accessed. For example, if a unit @code{X}
5936 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5937 check only mode does not access the source file containing unit
5938 @code{Y}.
5940 @cindex Multiple units, syntax checking
5941 Normally, GNAT allows only a single unit in a source file. However, this
5942 restriction does not apply in syntax-check-only mode, and it is possible
5943 to check a file containing multiple compilation units concatenated
5944 together. This is primarily used by the @code{gnatchop} utility
5945 (@pxref{Renaming Files Using gnatchop}).
5946 @end table
5948 @node Using gcc for Semantic Checking
5949 @subsection Using @command{gcc} for Semantic Checking
5950 @table @option
5951 @item -gnatc
5952 @cindex @option{-gnatc} (@command{gcc})
5954 @ifclear vms
5955 @noindent
5956 The @code{c} stands for ``check''.
5957 @end ifclear
5958 Causes the compiler to operate in semantic check mode,
5959 with full checking for all illegalities specified in the
5960 Ada 95 Reference Manual, but without generation of any object code
5961 (no object file is generated).
5963 Because dependent files must be accessed, you must follow the GNAT
5964 semantic restrictions on file structuring to operate in this mode:
5966 @itemize @bullet
5967 @item
5968 The needed source files must be accessible
5969 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5971 @item
5972 Each file must contain only one compilation unit.
5974 @item
5975 The file name and unit name must match (@pxref{File Naming Rules}).
5976 @end itemize
5978 The output consists of error messages as appropriate. No object file is
5979 generated. An @file{ALI} file is generated for use in the context of
5980 cross-reference tools, but this file is marked as not being suitable
5981 for binding (since no object file is generated).
5982 The checking corresponds exactly to the notion of
5983 legality in the Ada 95 Reference Manual.
5985 Any unit can be compiled in semantics-checking-only mode, including
5986 units that would not normally be compiled (subunits,
5987 and specifications where a separate body is present).
5988 @end table
5990 @node Compiling Different Versions of Ada
5991 @subsection Compiling Different Versions of Ada
5992 @table @option
5993 @cindex Compatibility with Ada 83
5994 @cindex Ada 83 mode
5995 @cindex Ada 95 mode
5996 @cindex Ada 2005 mode
5998 GNAT is primarily an Ada 95 compiler, but the switches described in
5999 this section allow operation in Ada 83 compatibility mode, and also
6000 allow the use of a preliminary implementation of many of the expected
6001 new features in Ada 2005, the forthcoming new version of the standard.
6003 @item -gnat83 (Ada 83 Compatibility Mode)
6004 @cindex @option{-gnat83} (@command{gcc})
6005 @cindex ACVC, Ada 83 tests
6007 @noindent
6008 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
6009 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
6010 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
6011 where this can be done easily.
6012 It is not possible to guarantee this switch does a perfect
6013 job; for example, some subtle tests, such as are
6014 found in earlier ACVC tests (and that have been removed from the ACATS suite
6015 for Ada 95), might not compile correctly.
6016 Nevertheless, this switch may be useful in some circumstances, for example
6017 where, due to contractual reasons, legacy code needs to be maintained
6018 using only Ada 83 features.
6020 With few exceptions (most notably the need to use @code{<>} on
6021 @cindex Generic formal parameters
6022 unconstrained generic formal parameters, the use of the new Ada 95
6023 reserved words, and the use of packages
6024 with optional bodies), it is not necessary to use the
6025 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6026 exceptions, Ada 95 is upwardly compatible with Ada 83. This
6027 means that a correct Ada 83 program is usually also a correct Ada 95
6028 program.
6029 For further information, please refer to @ref{Compatibility and Porting Guide}.
6031 @item -gnat95 (Ada 95 mode)
6032 @cindex @option{-gnat95} (@command{gcc})
6034 @noindent
6035 GNAT is primarily an Ada 95 compiler, and all current releases of GNAT Pro
6036 compile in Ada 95 mode by default. Typically, Ada 95 is sufficiently upwards
6037 compatible with Ada 83, that legacy Ada 83 programs may be compiled using
6038 this default Ada95 mode without problems (see section above describing the
6039 use of @option{-gnat83} to run in Ada 83 mode).
6041 In Ada 95 mode, the use of Ada 2005 features will in general cause error
6042 messages or warnings. Some specialized releases of GNAT (notably the GAP
6043 academic version) operate in Ada 2005 mode by default (see section below
6044 describing the use of @option{-gnat05} to run in Ada 2005 mode). For such
6045 versions the @option{-gnat95} switch may be used to enforce Ada 95 mode.
6046 This option also can be used to cancel the effect of a previous
6047 @option{-gnat83} or @option{-gnat05} switch earlier in the command line.
6050 @item -gnat05 (Ada 2005 mode)
6051 @cindex @option{-gnat05} (@command{gcc})
6053 @noindent
6054 Although GNAT is primarily an Ada 95 compiler, it can be set to operate
6055 in Ada 2005 mode using this option. Although the new standard has not
6056 yet been issued (as of early 2005), many features have been discussed and
6057 approved in ``Ada Issues'' (AI's). For the text of these AI's, see
6058 @url{www.ada-auth.org/cgi-bin/cvsweb.cgi/AIs}. Included with GNAT
6059 releases is a file @file{features-ada0y} that describes the current set
6060 of implemented Ada 2005 features.
6062 If these features are used in Ada 95 mode (which is the normal default),
6063 then error messages or warnings may be
6064 generated, reflecting the fact that these new features are otherwise
6065 unauthorized extensions to Ada 95. The use of the @option{-gnat05}
6066 switch (or an equivalent pragma) causes these messages to be suppressed.
6068 Note that some specialized releases of GNAT (notably the GAP academic
6069 version) have Ada 2005 mode on by default, and in such environments,
6070 the Ada 2005 features can be used freely without the use of switches.
6072 @end table
6074 @node Character Set Control
6075 @subsection Character Set Control
6076 @table @option
6077 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6078 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6080 @noindent
6081 Normally GNAT recognizes the Latin-1 character set in source program
6082 identifiers, as described in the Ada 95 Reference Manual.
6083 This switch causes
6084 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6085 single character ^^or word^ indicating the character set, as follows:
6087 @table @code
6088 @item 1
6089 ISO 8859-1 (Latin-1) identifiers
6091 @item 2
6092 ISO 8859-2 (Latin-2) letters allowed in identifiers
6094 @item 3
6095 ISO 8859-3 (Latin-3) letters allowed in identifiers
6097 @item 4
6098 ISO 8859-4 (Latin-4) letters allowed in identifiers
6100 @item 5
6101 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6103 @item 9
6104 ISO 8859-15 (Latin-9) letters allowed in identifiers
6106 @item ^p^PC^
6107 IBM PC letters (code page 437) allowed in identifiers
6109 @item ^8^PC850^
6110 IBM PC letters (code page 850) allowed in identifiers
6112 @item ^f^FULL_UPPER^
6113 Full upper-half codes allowed in identifiers
6115 @item ^n^NO_UPPER^
6116 No upper-half codes allowed in identifiers
6118 @item ^w^WIDE^
6119 Wide-character codes (that is, codes greater than 255)
6120 allowed in identifiers
6121 @end table
6123 @xref{Foreign Language Representation}, for full details on the
6124 implementation of these character sets.
6126 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6127 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6128 Specify the method of encoding for wide characters.
6129 @var{e} is one of the following:
6131 @table @code
6133 @item ^h^HEX^
6134 Hex encoding (brackets coding also recognized)
6136 @item ^u^UPPER^
6137 Upper half encoding (brackets encoding also recognized)
6139 @item ^s^SHIFT_JIS^
6140 Shift/JIS encoding (brackets encoding also recognized)
6142 @item ^e^EUC^
6143 EUC encoding (brackets encoding also recognized)
6145 @item ^8^UTF8^
6146 UTF-8 encoding (brackets encoding also recognized)
6148 @item ^b^BRACKETS^
6149 Brackets encoding only (default value)
6150 @end table
6151 For full details on these encoding
6152 methods see @ref{Wide Character Encodings}.
6153 Note that brackets coding is always accepted, even if one of the other
6154 options is specified, so for example @option{-gnatW8} specifies that both
6155 brackets and @code{UTF-8} encodings will be recognized. The units that are
6156 with'ed directly or indirectly will be scanned using the specified
6157 representation scheme, and so if one of the non-brackets scheme is
6158 used, it must be used consistently throughout the program. However,
6159 since brackets encoding is always recognized, it may be conveniently
6160 used in standard libraries, allowing these libraries to be used with
6161 any of the available coding schemes.
6162 scheme. If no @option{-gnatW?} parameter is present, then the default
6163 representation is Brackets encoding only.
6165 Note that the wide character representation that is specified (explicitly
6166 or by default) for the main program also acts as the default encoding used
6167 for Wide_Text_IO files if not specifically overridden by a WCEM form
6168 parameter.
6170 @end table
6171 @node File Naming Control
6172 @subsection File Naming Control
6174 @table @option
6175 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6176 @cindex @option{-gnatk} (@command{gcc})
6177 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6178 1-999, indicates the maximum allowable length of a file name (not
6179 including the @file{.ads} or @file{.adb} extension). The default is not
6180 to enable file name krunching.
6182 For the source file naming rules, @xref{File Naming Rules}.
6183 @end table
6185 @node Subprogram Inlining Control
6186 @subsection Subprogram Inlining Control
6188 @table @option
6189 @c !sort!
6190 @item -gnatn
6191 @cindex @option{-gnatn} (@command{gcc})
6192 @ifclear vms
6193 The @code{n} here is intended to suggest the first syllable of the
6194 word ``inline''.
6195 @end ifclear
6196 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6197 inlining to actually occur, optimization must be enabled. To enable
6198 inlining of subprograms specified by pragma @code{Inline},
6199 you must also specify this switch.
6200 In the absence of this switch, GNAT does not attempt
6201 inlining and does not need to access the bodies of
6202 subprograms for which @code{pragma Inline} is specified if they are not
6203 in the current unit.
6205 If you specify this switch the compiler will access these bodies,
6206 creating an extra source dependency for the resulting object file, and
6207 where possible, the call will be inlined.
6208 For further details on when inlining is possible
6209 see @ref{Inlining of Subprograms}.
6211 @item -gnatN
6212 @cindex @option{-gnatN} (@command{gcc})
6213 The front end inlining activated by this switch is generally more extensive,
6214 and quite often more effective than the standard @option{-gnatn} inlining mode.
6215 It will also generate additional dependencies.
6216 Note that
6217 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6218 to specify both options.
6219 @end table
6221 @node Auxiliary Output Control
6222 @subsection Auxiliary Output Control
6224 @table @option
6225 @item -gnatt
6226 @cindex @option{-gnatt} (@command{gcc})
6227 @cindex Writing internal trees
6228 @cindex Internal trees, writing to file
6229 Causes GNAT to write the internal tree for a unit to a file (with the
6230 extension @file{.adt}.
6231 This not normally required, but is used by separate analysis tools.
6232 Typically
6233 these tools do the necessary compilations automatically, so you should
6234 not have to specify this switch in normal operation.
6236 @item -gnatu
6237 @cindex @option{-gnatu} (@command{gcc})
6238 Print a list of units required by this compilation on @file{stdout}.
6239 The listing includes all units on which the unit being compiled depends
6240 either directly or indirectly.
6242 @ifclear vms
6243 @item -pass-exit-codes
6244 @cindex @option{-pass-exit-codes} (@command{gcc})
6245 If this switch is not used, the exit code returned by @command{gcc} when
6246 compiling multiple files indicates whether all source files have
6247 been successfully used to generate object files or not.
6249 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6250 exit status and allows an integrated development environment to better
6251 react to a compilation failure. Those exit status are:
6253 @table @asis
6254 @item 5
6255 There was an error in at least one source file.
6256 @item 3
6257 At least one source file did not generate an object file.
6258 @item 2
6259 The compiler died unexpectedly (internal error for example).
6260 @item 0
6261 An object file has been generated for every source file.
6262 @end table
6263 @end ifclear
6264 @end table
6266 @node Debugging Control
6267 @subsection Debugging Control
6269 @table @option
6270 @c !sort!
6271 @cindex Debugging options
6272 @ifclear vms
6273 @item -gnatd@var{x}
6274 @cindex @option{-gnatd} (@command{gcc})
6275 Activate internal debugging switches. @var{x} is a letter or digit, or
6276 string of letters or digits, which specifies the type of debugging
6277 outputs desired. Normally these are used only for internal development
6278 or system debugging purposes. You can find full documentation for these
6279 switches in the body of the @code{Debug} unit in the compiler source
6280 file @file{debug.adb}.
6281 @end ifclear
6283 @item -gnatG
6284 @cindex @option{-gnatG} (@command{gcc})
6285 This switch causes the compiler to generate auxiliary output containing
6286 a pseudo-source listing of the generated expanded code. Like most Ada
6287 compilers, GNAT works by first transforming the high level Ada code into
6288 lower level constructs. For example, tasking operations are transformed
6289 into calls to the tasking run-time routines. A unique capability of GNAT
6290 is to list this expanded code in a form very close to normal Ada source.
6291 This is very useful in understanding the implications of various Ada
6292 usage on the efficiency of the generated code. There are many cases in
6293 Ada (e.g. the use of controlled types), where simple Ada statements can
6294 generate a lot of run-time code. By using @option{-gnatG} you can identify
6295 these cases, and consider whether it may be desirable to modify the coding
6296 approach to improve efficiency.
6298 The format of the output is very similar to standard Ada source, and is
6299 easily understood by an Ada programmer. The following special syntactic
6300 additions correspond to low level features used in the generated code that
6301 do not have any exact analogies in pure Ada source form. The following
6302 is a partial list of these special constructions. See the specification
6303 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6305 @table @code
6306 @item new @var{xxx} [storage_pool = @var{yyy}]
6307 Shows the storage pool being used for an allocator.
6309 @item at end @var{procedure-name};
6310 Shows the finalization (cleanup) procedure for a scope.
6312 @item (if @var{expr} then @var{expr} else @var{expr})
6313 Conditional expression equivalent to the @code{x?y:z} construction in C.
6315 @item @var{target}^^^(@var{source})
6316 A conversion with floating-point truncation instead of rounding.
6318 @item @var{target}?(@var{source})
6319 A conversion that bypasses normal Ada semantic checking. In particular
6320 enumeration types and fixed-point types are treated simply as integers.
6322 @item @var{target}?^^^(@var{source})
6323 Combines the above two cases.
6325 @item @var{x} #/ @var{y}
6326 @itemx @var{x} #mod @var{y}
6327 @itemx @var{x} #* @var{y}
6328 @itemx @var{x} #rem @var{y}
6329 A division or multiplication of fixed-point values which are treated as
6330 integers without any kind of scaling.
6332 @item free @var{expr} [storage_pool = @var{xxx}]
6333 Shows the storage pool associated with a @code{free} statement.
6335 @item [subtype or type declaration]
6336 Used to list an equivalent declaration for an internally generated
6337 type that is referenced elsewhere in the listing.
6339 @item freeze @var{type-name} [@var{actions}]
6340 Shows the point at which @var{type-name} is frozen, with possible
6341 associated actions to be performed at the freeze point.
6343 @item reference @var{itype}
6344 Reference (and hence definition) to internal type @var{itype}.
6346 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6347 Intrinsic function call.
6349 @item @var{label-name} : label
6350 Declaration of label @var{labelname}.
6352 @item #$ @var{subprogram-name}
6353 An implicit call to a run-time support routine
6354 (to meet the requirement of H.3.1(9) in a
6355 convenient manner).
6357 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6358 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6359 @var{expr}, but handled more efficiently).
6361 @item [constraint_error]
6362 Raise the @code{Constraint_Error} exception.
6364 @item @var{expression}'reference
6365 A pointer to the result of evaluating @var{expression}.
6367 @item @var{target-type}!(@var{source-expression})
6368 An unchecked conversion of @var{source-expression} to @var{target-type}.
6370 @item [@var{numerator}/@var{denominator}]
6371 Used to represent internal real literals (that) have no exact
6372 representation in base 2-16 (for example, the result of compile time
6373 evaluation of the expression 1.0/27.0).
6374 @end table
6376 @item -gnatD
6377 @cindex @option{-gnatD} (@command{gcc})
6378 When used in conjunction with @option{-gnatG}, this switch causes
6379 the expanded source, as described above for
6380 @option{-gnatG} to be written to files with names
6381 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6382 instead of to the standard output file. For
6383 example, if the source file name is @file{hello.adb}, then a file
6384 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6385 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6386 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6387 you to do source level debugging using the generated code which is
6388 sometimes useful for complex code, for example to find out exactly
6389 which part of a complex construction raised an exception. This switch
6390 also suppress generation of cross-reference information (see
6391 @option{-gnatx}) since otherwise the cross-reference information
6392 would refer to the @file{^.dg^.DG^} file, which would cause
6393 confusion since this is not the original source file.
6395 Note that @option{-gnatD} actually implies @option{-gnatG}
6396 automatically, so it is not necessary to give both options.
6397 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6399 @ifclear vms
6400 @item -gnatR[0|1|2|3[s]]
6401 @cindex @option{-gnatR} (@command{gcc})
6402 This switch controls output from the compiler of a listing showing
6403 representation information for declared types and objects. For
6404 @option{-gnatR0}, no information is output (equivalent to omitting
6405 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6406 so @option{-gnatR} with no parameter has the same effect), size and alignment
6407 information is listed for declared array and record types. For
6408 @option{-gnatR2}, size and alignment information is listed for all
6409 expression information for values that are computed at run time for
6410 variant records. These symbolic expressions have a mostly obvious
6411 format with #n being used to represent the value of the n'th
6412 discriminant. See source files @file{repinfo.ads/adb} in the
6413 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6414 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6415 the output is to a file with the name @file{^file.rep^file_REP^} where
6416 file is the name of the corresponding source file.
6417 @end ifclear
6418 @ifset vms
6419 @item /REPRESENTATION_INFO
6420 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6421 This qualifier controls output from the compiler of a listing showing
6422 representation information for declared types and objects. For
6423 @option{/REPRESENTATION_INFO=NONE}, no information is output
6424 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6425 @option{/REPRESENTATION_INFO} without option is equivalent to
6426 @option{/REPRESENTATION_INFO=ARRAYS}.
6427 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6428 information is listed for declared array and record types. For
6429 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6430 is listed for all expression information for values that are computed
6431 at run time for variant records. These symbolic expressions have a mostly
6432 obvious format with #n being used to represent the value of the n'th
6433 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6434 @code{GNAT} sources for full details on the format of
6435 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6436 If _FILE is added at the end of an option
6437 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6438 then the output is to a file with the name @file{file_REP} where
6439 file is the name of the corresponding source file.
6440 @end ifset
6441 Note that it is possible for record components to have zero size. In
6442 this case, the component clause uses an obvious extension of permitted
6443 Ada syntax, for example @code{at 0 range 0 .. -1}.
6445 @item -gnatS
6446 @cindex @option{-gnatS} (@command{gcc})
6447 The use of the switch @option{-gnatS} for an
6448 Ada compilation will cause the compiler to output a
6449 representation of package Standard in a form very
6450 close to standard Ada. It is not quite possible to
6451 do this entirely in standard Ada (since new
6452 numeric base types cannot be created in standard
6453 Ada), but the output is easily
6454 readable to any Ada programmer, and is useful to
6455 determine the characteristics of target dependent
6456 types in package Standard.
6458 @item -gnatx
6459 @cindex @option{-gnatx} (@command{gcc})
6460 Normally the compiler generates full cross-referencing information in
6461 the @file{ALI} file. This information is used by a number of tools,
6462 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6463 suppresses this information. This saves some space and may slightly
6464 speed up compilation, but means that these tools cannot be used.
6465 @end table
6467 @node Exception Handling Control
6468 @subsection Exception Handling Control
6470 @noindent
6471 GNAT uses two methods for handling exceptions at run-time. The
6472 @code{setjmp/longjmp} method saves the context when entering
6473 a frame with an exception handler. Then when an exception is
6474 raised, the context can be restored immediately, without the
6475 need for tracing stack frames. This method provides very fast
6476 exception propagation, but introduces significant overhead for
6477 the use of exception handlers, even if no exception is raised.
6479 The other approach is called ``zero cost'' exception handling.
6480 With this method, the compiler builds static tables to describe
6481 the exception ranges. No dynamic code is required when entering
6482 a frame containing an exception handler. When an exception is
6483 raised, the tables are used to control a back trace of the
6484 subprogram invocation stack to locate the required exception
6485 handler. This method has considerably poorer performance for
6486 the propagation of exceptions, but there is no overhead for
6487 exception handlers if no exception is raised. Note that in this
6488 mode and in the context of mixed Ada and C/C++ programming,
6489 to propagate an exception through a C/C++ code, the C/C++ code
6490 must be compiled with the @option{-funwind-tables} GCC's
6491 option.
6493 The following switches can be used to control which of the
6494 two exception handling methods is used.
6496 @table @option
6497 @c !sort!
6499 @item --RTS=sjlj
6500 @cindex @option{--RTS=sjlj} (@command{gnatmake})
6501 This switch causes the setjmp/longjmp run-time to be used
6502 for exception handling. If this is the default mechanism for the
6503 target (see below), then this has no effect. If the default
6504 mechanism for the target is zero cost exceptions, then
6505 this switch can be used to modify this default, and must be
6506 used for all units in the partition.
6507 This option is rarely used. One case in which it may be
6508 advantageous is if you have an application where exception
6509 raising is common and the overall performance of the
6510 application is improved by favoring exception propagation.
6512 @item --RTS=zcx
6513 @cindex @option{--RTS=zcx} (@command{gnatmake})
6514 @cindex Zero Cost Exceptions
6515 This switch causes the zero cost approach to be used
6516 for exception handling. If this is the default mechanism for the
6517 target (see below), then this has no effect. If the default
6518 mechanism for the target is setjmp/longjmp exceptions, then
6519 this switch can be used to modify this default, and must be
6520 used for all units in the partition.
6521 This option can only be used if the zero cost approach
6522 is available for the target in use (see below).
6523 @end table
6525 @noindent
6526 The @code{setjmp/longjmp} approach is available on all targets, while
6527 the @code{zero cost} approach is available on selected targets.
6528 To determine whether zero cost exceptions can be used for a
6529 particular target, look at the private part of the file system.ads.
6530 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6531 be True to use the zero cost approach. If both of these switches
6532 are set to False, this means that zero cost exception handling
6533 is not yet available for that target. The switch
6534 @code{ZCX_By_Default} indicates the default approach. If this
6535 switch is set to True, then the @code{zero cost} approach is
6536 used by default.
6538 @node Units to Sources Mapping Files
6539 @subsection Units to Sources Mapping Files
6541 @table @option
6543 @item -gnatem^^=^@var{path}
6544 @cindex @option{-gnatem} (@command{gcc})
6545 A mapping file is a way to communicate to the compiler two mappings:
6546 from unit names to file names (without any directory information) and from
6547 file names to path names (with full directory information). These mappings
6548 are used by the compiler to short-circuit the path search.
6550 The use of mapping files is not required for correct operation of the
6551 compiler, but mapping files can improve efficiency, particularly when
6552 sources are read over a slow network connection. In normal operation,
6553 you need not be concerned with the format or use of mapping files,
6554 and the @option{-gnatem} switch is not a switch that you would use
6555 explicitly. it is intended only for use by automatic tools such as
6556 @command{gnatmake} running under the project file facility. The
6557 description here of the format of mapping files is provided
6558 for completeness and for possible use by other tools.
6560 A mapping file is a sequence of sets of three lines. In each set,
6561 the first line is the unit name, in lower case, with ``@code{%s}''
6562 appended for
6563 specifications and ``@code{%b}'' appended for bodies; the second line is the
6564 file name; and the third line is the path name.
6566 Example:
6567 @smallexample
6568    main%b
6569    main.2.ada
6570    /gnat/project1/sources/main.2.ada
6571 @end smallexample
6573 When the switch @option{-gnatem} is specified, the compiler will create
6574 in memory the two mappings from the specified file. If there is any problem
6575 (non existent file, truncated file or duplicate entries), no mapping
6576 will be created.
6578 Several @option{-gnatem} switches may be specified; however, only the last
6579 one on the command line will be taken into account.
6581 When using a project file, @command{gnatmake} create a temporary mapping file
6582 and communicates it to the compiler using this switch.
6584 @end table
6586 @node Integrated Preprocessing
6587 @subsection Integrated Preprocessing
6589 @noindent
6590 GNAT sources may be preprocessed immediately before compilation; the actual
6591 text of the source is not the text of the source file, but is derived from it
6592 through a process called preprocessing. Integrated preprocessing is specified
6593 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6594 indicates, through a text file, the preprocessing data to be used.
6595 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6597 @noindent
6598 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6599 used when Integrated Preprocessing is used. The reason is that preprocessing
6600 with another Preprocessing Data file without changing the sources will
6601 not trigger recompilation without this switch.
6603 @noindent
6604 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6605 always trigger recompilation for sources that are preprocessed,
6606 because @command{gnatmake} cannot compute the checksum of the source after
6607 preprocessing.
6609 @noindent
6610 The actual preprocessing function is described in details in section
6611 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6612 preprocessing is triggered and parameterized.
6614 @table @code
6616 @item -gnatep=@var{file}
6617 @cindex @option{-gnatep} (@command{gcc})
6618 This switch indicates to the compiler the file name (without directory
6619 information) of the preprocessor data file to use. The preprocessor data file
6620 should be found in the source directories.
6622 @noindent
6623 A preprocessing data file is a text file with significant lines indicating
6624 how should be preprocessed either a specific source or all sources not
6625 mentioned in other lines. A significant line is a non empty, non comment line.
6626 Comments are similar to Ada comments.
6628 @noindent
6629 Each significant line starts with either a literal string or the character '*'.
6630 A literal string is the file name (without directory information) of the source
6631 to preprocess. A character '*' indicates the preprocessing for all the sources
6632 that are not specified explicitly on other lines (order of the lines is not
6633 significant). It is an error to have two lines with the same file name or two
6634 lines starting with the character '*'.
6636 @noindent
6637 After the file name or the character '*', another optional literal string
6638 indicating the file name of the definition file to be used for preprocessing
6639 (@pxref{Form of Definitions File}). The definition files are found by the
6640 compiler in one of the source directories. In some cases, when compiling
6641 a source in a directory other than the current directory, if the definition
6642 file is in the current directory, it may be necessary to add the current
6643 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6644 the compiler would not find the definition file.
6646 @noindent
6647 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6648 be found. Those ^switches^switches^ are:
6650 @table @code
6652 @item -b
6653 Causes both preprocessor lines and the lines deleted by
6654 preprocessing to be replaced by blank lines, preserving the line number.
6655 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6656 it cancels the effect of @option{-c}.
6658 @item -c
6659 Causes both preprocessor lines and the lines deleted
6660 by preprocessing to be retained as comments marked
6661 with the special string ``@code{--! }''.
6663 @item -Dsymbol=value
6664 Define or redefine a symbol, associated with value. A symbol is an Ada
6665 identifier, or an Ada reserved word, with the exception of @code{if},
6666 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6667 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6668 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6669 same name defined in a definition file.
6671 @item -s
6672 Causes a sorted list of symbol names and values to be
6673 listed on the standard output file.
6675 @item -u
6676 Causes undefined symbols to be treated as having the value @code{FALSE}
6677 in the context
6678 of a preprocessor test. In the absence of this option, an undefined symbol in
6679 a @code{#if} or @code{#elsif} test will be treated as an error.
6681 @end table
6683 @noindent
6684 Examples of valid lines in a preprocessor data file:
6686 @smallexample
6687   "toto.adb"  "prep.def" -u
6688   --  preprocess "toto.adb", using definition file "prep.def",
6689   --  undefined symbol are False.
6691   * -c -DVERSION=V101
6692   --  preprocess all other sources without a definition file;
6693   --  suppressed lined are commented; symbol VERSION has the value V101.
6695   "titi.adb" "prep2.def" -s
6696   --  preprocess "titi.adb", using definition file "prep2.def";
6697   --  list all symbols with their values.
6698 @end smallexample
6700 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6701 @cindex @option{-gnateD} (@command{gcc})
6702 Define or redefine a preprocessing symbol, associated with value. If no value
6703 is given on the command line, then the value of the symbol is @code{True}.
6704 A symbol is an identifier, following normal Ada (case-insensitive)
6705 rules for its syntax, and value is any sequence (including an empty sequence)
6706 of characters from the set (letters, digits, period, underline).
6707 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6708 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6710 @noindent
6711 A symbol declared with this ^switch^switch^ on the command line replaces a
6712 symbol with the same name either in a definition file or specified with a
6713 ^switch^switch^ -D in the preprocessor data file.
6715 @noindent
6716 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6718 @end table
6720 @node Code Generation Control
6721 @subsection Code Generation Control
6723 @noindent
6725 The GCC technology provides a wide range of target dependent
6726 @option{-m} switches for controlling
6727 details of code generation with respect to different versions of
6728 architectures. This includes variations in instruction sets (e.g.
6729 different members of the power pc family), and different requirements
6730 for optimal arrangement of instructions (e.g. different members of
6731 the x86 family). The list of available @option{-m} switches may be
6732 found in the GCC documentation.
6734 Use of these @option{-m} switches may in some cases result in improved
6735 code performance.
6737 The GNAT Pro technology is tested and qualified without any
6738 @option{-m} switches,
6739 so generally the most reliable approach is to avoid the use of these
6740 switches. However, we generally expect most of these switches to work
6741 successfully with GNAT Pro, and many customers have reported successful
6742 use of these options.
6744 Our general advice is to avoid the use of @option{-m} switches unless
6745 special needs lead to requirements in this area. In particular,
6746 there is no point in using @option{-m} switches to improve performance
6747 unless you actually see a performance improvement.
6749 @ifset vms
6750 @node Return Codes
6751 @subsection Return Codes
6752 @cindex Return Codes
6753 @cindex @option{/RETURN_CODES=VMS}
6755 @noindent
6756 On VMS, GNAT compiled programs return POSIX-style codes by default,
6757 e.g. @option{/RETURN_CODES=POSIX}.
6759 To enable VMS style return codes, use GNAT BIND and LINK with the option
6760 @option{/RETURN_CODES=VMS}. For example:
6762 @smallexample
6763 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
6764 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6765 @end smallexample
6767 @noindent
6768 Programs built with /RETURN_CODES=VMS are suitable to be called in
6769 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6770 are suitable for spawning with appropriate GNAT RTL routines.
6772 @end ifset
6774 @node Search Paths and the Run-Time Library (RTL)
6775 @section Search Paths and the Run-Time Library (RTL)
6777 @noindent
6778 With the GNAT source-based library system, the compiler must be able to
6779 find source files for units that are needed by the unit being compiled.
6780 Search paths are used to guide this process.
6782 The compiler compiles one source file whose name must be given
6783 explicitly on the command line. In other words, no searching is done
6784 for this file. To find all other source files that are needed (the most
6785 common being the specs of units), the compiler examines the following
6786 directories, in the following order:
6788 @enumerate
6789 @item
6790 The directory containing the source file of the main unit being compiled
6791 (the file name on the command line).
6793 @item
6794 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6795 @command{gcc} command line, in the order given.
6797 @item
6798 @findex ADA_PRJ_INCLUDE_FILE
6799 Each of the directories listed in the text file whose name is given
6800 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6802 @noindent
6803 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6804 driver when project files are used. It should not normally be set
6805 by other means.
6807 @item
6808 @findex ADA_INCLUDE_PATH
6809 Each of the directories listed in the value of the
6810 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6811 @ifclear vms
6812 Construct this value
6813 exactly as the @code{PATH} environment variable: a list of directory
6814 names separated by colons (semicolons when working with the NT version).
6815 @end ifclear
6816 @ifset vms
6817 Normally, define this value as a logical name containing a comma separated
6818 list of directory names.
6820 This variable can also be defined by means of an environment string
6821 (an argument to the HP C exec* set of functions).
6823 Logical Name:
6824 @smallexample
6825 DEFINE ANOTHER_PATH FOO:[BAG]
6826 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6827 @end smallexample
6829 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6830 first, followed by the standard Ada 95
6831 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6832 If this is not redefined, the user will obtain the HP Ada 83 IO packages
6833 (Text_IO, Sequential_IO, etc)
6834 instead of the Ada95 packages. Thus, in order to get the Ada 95
6835 packages by default, ADA_INCLUDE_PATH must be redefined.
6836 @end ifset
6838 @item
6839 The content of the @file{ada_source_path} file which is part of the GNAT
6840 installation tree and is used to store standard libraries such as the
6841 GNAT Run Time Library (RTL) source files.
6842 @ifclear vms
6843 @ref{Installing a library}
6844 @end ifclear
6845 @end enumerate
6847 @noindent
6848 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6849 inhibits the use of the directory
6850 containing the source file named in the command line. You can still
6851 have this directory on your search path, but in this case it must be
6852 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6854 Specifying the switch @option{-nostdinc}
6855 inhibits the search of the default location for the GNAT Run Time
6856 Library (RTL) source files.
6858 The compiler outputs its object files and ALI files in the current
6859 working directory.
6860 @ifclear vms
6861 Caution: The object file can be redirected with the @option{-o} switch;
6862 however, @command{gcc} and @code{gnat1} have not been coordinated on this
6863 so the @file{ALI} file will not go to the right place. Therefore, you should
6864 avoid using the @option{-o} switch.
6865 @end ifclear
6867 @findex System.IO
6868 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6869 children make up the GNAT RTL, together with the simple @code{System.IO}
6870 package used in the @code{"Hello World"} example. The sources for these units
6871 are needed by the compiler and are kept together in one directory. Not
6872 all of the bodies are needed, but all of the sources are kept together
6873 anyway. In a normal installation, you need not specify these directory
6874 names when compiling or binding. Either the environment variables or
6875 the built-in defaults cause these files to be found.
6877 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6878 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6879 consisting of child units of @code{GNAT}. This is a collection of generally
6880 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6881 further details.
6883 Besides simplifying access to the RTL, a major use of search paths is
6884 in compiling sources from multiple directories. This can make
6885 development environments much more flexible.
6887 @node Order of Compilation Issues
6888 @section Order of Compilation Issues
6890 @noindent
6891 If, in our earlier example, there was a spec for the @code{hello}
6892 procedure, it would be contained in the file @file{hello.ads}; yet this
6893 file would not have to be explicitly compiled. This is the result of the
6894 model we chose to implement library management. Some of the consequences
6895 of this model are as follows:
6897 @itemize @bullet
6898 @item
6899 There is no point in compiling specs (except for package
6900 specs with no bodies) because these are compiled as needed by clients. If
6901 you attempt a useless compilation, you will receive an error message.
6902 It is also useless to compile subunits because they are compiled as needed
6903 by the parent.
6905 @item
6906 There are no order of compilation requirements: performing a
6907 compilation never obsoletes anything. The only way you can obsolete
6908 something and require recompilations is to modify one of the
6909 source files on which it depends.
6911 @item
6912 There is no library as such, apart from the ALI files
6913 (@pxref{The Ada Library Information Files}, for information on the format
6914 of these files). For now we find it convenient to create separate ALI files,
6915 but eventually the information therein may be incorporated into the object
6916 file directly.
6918 @item
6919 When you compile a unit, the source files for the specs of all units
6920 that it @code{with}'s, all its subunits, and the bodies of any generics it
6921 instantiates must be available (reachable by the search-paths mechanism
6922 described above), or you will receive a fatal error message.
6923 @end itemize
6925 @node Examples
6926 @section Examples
6928 @noindent
6929 The following are some typical Ada compilation command line examples:
6931 @table @code
6932 @item $ gcc -c xyz.adb
6933 Compile body in file @file{xyz.adb} with all default options.
6935 @ifclear vms
6936 @item $ gcc -c -O2 -gnata xyz-def.adb
6937 @end ifclear
6938 @ifset vms
6939 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6940 @end ifset
6942 Compile the child unit package in file @file{xyz-def.adb} with extensive
6943 optimizations, and pragma @code{Assert}/@code{Debug} statements
6944 enabled.
6946 @item $ gcc -c -gnatc abc-def.adb
6947 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6948 mode.
6949 @end table
6951 @node Binding Using gnatbind
6952 @chapter Binding Using @code{gnatbind}
6953 @findex gnatbind
6955 @menu
6956 * Running gnatbind::
6957 * Switches for gnatbind::
6958 * Command-Line Access::
6959 * Search Paths for gnatbind::
6960 * Examples of gnatbind Usage::
6961 @end menu
6963 @noindent
6964 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6965 to bind compiled GNAT objects. The @code{gnatbind} program performs
6966 four separate functions:
6968 @enumerate
6969 @item
6970 Checks that a program is consistent, in accordance with the rules in
6971 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6972 messages are generated if a program uses inconsistent versions of a
6973 given unit.
6975 @item
6976 Checks that an acceptable order of elaboration exists for the program
6977 and issues an error message if it cannot find an order of elaboration
6978 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6980 @item
6981 Generates a main program incorporating the given elaboration order.
6982 This program is a small Ada package (body and spec) that
6983 must be subsequently compiled
6984 using the GNAT compiler. The necessary compilation step is usually
6985 performed automatically by @command{gnatlink}. The two most important
6986 functions of this program
6987 are to call the elaboration routines of units in an appropriate order
6988 and to call the main program.
6990 @item
6991 Determines the set of object files required by the given main program.
6992 This information is output in the forms of comments in the generated program,
6993 to be read by the @command{gnatlink} utility used to link the Ada application.
6994 @end enumerate
6996 @node Running gnatbind
6997 @section Running @code{gnatbind}
6999 @noindent
7000 The form of the @code{gnatbind} command is
7002 @smallexample
7003 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
7004 @end smallexample
7006 @noindent
7007 where @file{@i{mainprog}.adb} is the Ada file containing the main program
7008 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
7009 package in two files whose names are
7010 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
7011 For example, if given the
7012 parameter @file{hello.ali}, for a main program contained in file
7013 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7014 and @file{b~hello.adb}.
7016 When doing consistency checking, the binder takes into consideration
7017 any source files it can locate. For example, if the binder determines
7018 that the given main program requires the package @code{Pack}, whose
7019 @file{.ALI}
7020 file is @file{pack.ali} and whose corresponding source spec file is
7021 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7022 (using the same search path conventions as previously described for the
7023 @command{gcc} command). If it can locate this source file, it checks that
7024 the time stamps
7025 or source checksums of the source and its references to in @file{ALI} files
7026 match. In other words, any @file{ALI} files that mentions this spec must have
7027 resulted from compiling this version of the source file (or in the case
7028 where the source checksums match, a version close enough that the
7029 difference does not matter).
7031 @cindex Source files, use by binder
7032 The effect of this consistency checking, which includes source files, is
7033 that the binder ensures that the program is consistent with the latest
7034 version of the source files that can be located at bind time. Editing a
7035 source file without compiling files that depend on the source file cause
7036 error messages to be generated by the binder.
7038 For example, suppose you have a main program @file{hello.adb} and a
7039 package @code{P}, from file @file{p.ads} and you perform the following
7040 steps:
7042 @enumerate
7043 @item
7044 Enter @code{gcc -c hello.adb} to compile the main program.
7046 @item
7047 Enter @code{gcc -c p.ads} to compile package @code{P}.
7049 @item
7050 Edit file @file{p.ads}.
7052 @item
7053 Enter @code{gnatbind hello}.
7054 @end enumerate
7056 @noindent
7057 At this point, the file @file{p.ali} contains an out-of-date time stamp
7058 because the file @file{p.ads} has been edited. The attempt at binding
7059 fails, and the binder generates the following error messages:
7061 @smallexample
7062 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7063 error: "p.ads" has been modified and must be recompiled
7064 @end smallexample
7066 @noindent
7067 Now both files must be recompiled as indicated, and then the bind can
7068 succeed, generating a main program. You need not normally be concerned
7069 with the contents of this file, but for reference purposes a sample
7070 binder output file is given in @ref{Example of Binder Output File}.
7072 In most normal usage, the default mode of @command{gnatbind} which is to
7073 generate the main package in Ada, as described in the previous section.
7074 In particular, this means that any Ada programmer can read and understand
7075 the generated main program. It can also be debugged just like any other
7076 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7077 @command{gnatbind} and @command{gnatlink}.
7079 However for some purposes it may be convenient to generate the main
7080 program in C rather than Ada. This may for example be helpful when you
7081 are generating a mixed language program with the main program in C. The
7082 GNAT compiler itself is an example.
7083 The use of the @option{^-C^/BIND_FILE=C^} switch
7084 for both @code{gnatbind} and @command{gnatlink} will cause the program to
7085 be generated in C (and compiled using the gnu C compiler).
7087 @node Switches for gnatbind
7088 @section Switches for @command{gnatbind}
7090 @noindent
7091 The following switches are available with @code{gnatbind}; details will
7092 be presented in subsequent sections.
7094 @menu
7095 * Consistency-Checking Modes::
7096 * Binder Error Message Control::
7097 * Elaboration Control::
7098 * Output Control::
7099 * Binding with Non-Ada Main Programs::
7100 * Binding Programs with No Main Subprogram::
7101 @end menu
7103 @table @option
7104 @c !sort!
7105 @item ^-aO^/OBJECT_SEARCH^
7106 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
7107 Specify directory to be searched for ALI files.
7109 @item ^-aI^/SOURCE_SEARCH^
7110 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7111 Specify directory to be searched for source file.
7113 @item ^-A^/BIND_FILE=ADA^
7114 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
7115 Generate binder program in Ada (default)
7117 @item ^-b^/REPORT_ERRORS=BRIEF^
7118 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
7119 Generate brief messages to @file{stderr} even if verbose mode set.
7121 @item ^-c^/NOOUTPUT^
7122 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
7123 Check only, no generation of binder output file.
7125 @item ^-C^/BIND_FILE=C^
7126 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
7127 Generate binder program in C
7129 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]
7130 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}[k|m]} (@command{gnatbind})
7131 This switch can be used to change the default task stack size value
7132 to a specified size @var{nn}, which is expressed in bytes by default, or
7133 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7134 with @var{m}.
7135 In the absence of a [k|m] suffix, this switch is equivalent, in effect,
7136 to completing all task specs with
7137 @smallexample @c ada
7138    pragma Storage_Size (nn);
7139 @end smallexample
7140 When they do not already have such a pragma.
7142 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}[k|m]
7143 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
7144 This switch can be used to change the default secondary stack size value
7145 to a specified size @var{nn}, which is expressed in bytes by default, or
7146 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
7147 with @var{m}.
7149 The secondary stack is used to deal with functions that return a variable
7150 sized result, for example a function returning an unconstrained
7151 String. There are two ways in which this secondary stack is allocated.
7153 For most targets, the secondary stack is growing on demand and is allocated
7154 as a chain of blocks in the heap. The -D option is not very
7155 relevant. It only give some control over the size of the allocated
7156 blocks (whose size is the minimum of the default secondary stack size value,
7157 and the actual size needed for the current allocation request).
7159 For certain targets, notably VxWorks 653,
7160 the secondary stack is allocated by carving off a fixed ratio chunk of the
7161 primary task stack. The -D option is used to defined the
7162 size of the environment task's secondary stack.
7164 @item ^-e^/ELABORATION_DEPENDENCIES^
7165 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
7166 Output complete list of elaboration-order dependencies.
7168 @item ^-E^/STORE_TRACEBACKS^
7169 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
7170 Store tracebacks in exception occurrences when the target supports it.
7171 This is the default with the zero cost exception mechanism.
7172 @ignore
7173 @c The following may get moved to an appendix
7174 This option is currently supported on the following targets:
7175 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7176 @end ignore
7177 See also the packages @code{GNAT.Traceback} and
7178 @code{GNAT.Traceback.Symbolic} for more information.
7179 @ifclear vms
7180 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
7181 @command{gcc} option.
7182 @end ifclear
7184 @item ^-F^/FORCE_ELABS_FLAGS^
7185 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
7186 Force the checks of elaboration flags. @command{gnatbind} does not normally
7187 generate checks of elaboration flags for the main executable, except when
7188 a Stand-Alone Library is used. However, there are cases when this cannot be
7189 detected by gnatbind. An example is importing an interface of a Stand-Alone
7190 Library through a pragma Import and only specifying through a linker switch
7191 this Stand-Alone Library. This switch is used to guarantee that elaboration
7192 flag checks are generated.
7194 @item ^-h^/HELP^
7195 @cindex @option{^-h^/HELP^} (@command{gnatbind})
7196 Output usage (help) information
7198 @item ^-I^/SEARCH^
7199 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7200 Specify directory to be searched for source and ALI files.
7202 @item ^-I-^/NOCURRENT_DIRECTORY^
7203 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7204 Do not look for sources in the current directory where @code{gnatbind} was
7205 invoked, and do not look for ALI files in the directory containing the
7206 ALI file named in the @code{gnatbind} command line.
7208 @item ^-l^/ORDER_OF_ELABORATION^
7209 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7210 Output chosen elaboration order.
7212 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7213 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7214 Bind the units for library building. In this case the adainit and
7215 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7216 are renamed to ^xxxinit^XXXINIT^ and
7217 ^xxxfinal^XXXFINAL^.
7218 Implies ^-n^/NOCOMPILE^.
7219 @ifclear vms
7220 (@xref{GNAT and Libraries}, for more details.)
7221 @end ifclear
7222 @ifset vms
7223 On OpenVMS, these init and final procedures are exported in uppercase
7224 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7225 the init procedure will be "TOTOINIT" and the exported name of the final
7226 procedure will be "TOTOFINAL".
7227 @end ifset
7229 @item ^-Mxyz^/RENAME_MAIN=xyz^
7230 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7231 Rename generated main program from main to xyz. This option is
7232 supported on cross environments only.
7234 @item ^-m^/ERROR_LIMIT=^@var{n}
7235 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7236 Limit number of detected errors to @var{n}, where @var{n} is
7237 in the range 1..999_999. The default value if no switch is
7238 given is 9999. Binding is terminated if the limit is exceeded.
7239 @ifset unw
7240 Furthermore, under Windows, the sources pointed to by the libraries path
7241 set in the registry are not searched for.
7242 @end ifset
7244 @item ^-n^/NOMAIN^
7245 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7246 No main program.
7248 @item -nostdinc
7249 @cindex @option{-nostdinc} (@command{gnatbind})
7250 Do not look for sources in the system default directory.
7252 @item -nostdlib
7253 @cindex @option{-nostdlib} (@command{gnatbind})
7254 Do not look for library files in the system default directory.
7256 @item --RTS=@var{rts-path}
7257 @cindex @option{--RTS} (@code{gnatbind})
7258 Specifies the default location of the runtime library. Same meaning as the
7259 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7261 @item ^-o ^/OUTPUT=^@var{file}
7262 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7263 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7264 Note that if this option is used, then linking must be done manually,
7265 gnatlink cannot be used.
7267 @item ^-O^/OBJECT_LIST^
7268 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7269 Output object list.
7271 @item ^-p^/PESSIMISTIC_ELABORATION^
7272 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7273 Pessimistic (worst-case) elaboration order
7275 @item ^-s^/READ_SOURCES=ALL^
7276 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7277 Require all source files to be present.
7279 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7280 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7281 Specifies the value to be used when detecting uninitialized scalar
7282 objects with pragma Initialize_Scalars.
7283 The @var{xxx} ^string specified with the switch^option^ may be either
7284 @itemize @bullet
7285 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7286 @item ``@option{^lo^LOW^}'' for the lowest possible value
7287 @item ``@option{^hi^HIGH^}'' for the highest possible value
7288 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7289 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7290 @end itemize
7292 In addition, you can specify @option{-Sev} to indicate that the value is
7293 to be set at run time. In this case, the program will look for an environment
7294 @cindex GNAT_INIT_SCALARS
7295 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7296 of @option{in/lo/hi/xx} with the same meanings as above.
7297 If no environment variable is found, or if it does not have a valid value,
7298 then the default is @option{in} (invalid values).
7300 @ifclear vms
7301 @item -static
7302 @cindex @option{-static} (@code{gnatbind})
7303 Link against a static GNAT run time.
7305 @item -shared
7306 @cindex @option{-shared} (@code{gnatbind})
7307 Link against a shared GNAT run time when available.
7308 @end ifclear
7310 @item ^-t^/NOTIME_STAMP_CHECK^
7311 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7312 Tolerate time stamp and other consistency errors
7314 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7315 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7316 Set the time slice value to @var{n} milliseconds. If the system supports
7317 the specification of a specific time slice value, then the indicated value
7318 is used. If the system does not support specific time slice values, but
7319 does support some general notion of round-robin scheduling, then any
7320 non-zero value will activate round-robin scheduling.
7322 A value of zero is treated specially. It turns off time
7323 slicing, and in addition, indicates to the tasking run time that the
7324 semantics should match as closely as possible the Annex D
7325 requirements of the Ada RM, and in particular sets the default
7326 scheduling policy to @code{FIFO_Within_Priorities}.
7329 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
7330 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
7331 Enable dynamic stack usage, with n result stored and displayed at program
7332 termination. Results that can't be stored are displayed on the fly, at task
7333 termination. This option is currently not supported on OpenVMS I64 platforms.
7335 @item ^-v^/REPORT_ERRORS=VERBOSE^
7336 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7337 Verbose mode. Write error messages, header, summary output to
7338 @file{stdout}.
7340 @ifclear vms
7341 @item -w@var{x}
7342 @cindex @option{-w} (@code{gnatbind})
7343 Warning mode (@var{x}=s/e for suppress/treat as error)
7344 @end ifclear
7346 @ifset vms
7347 @item /WARNINGS=NORMAL
7348 @cindex @option{/WARNINGS} (@code{gnatbind})
7349 Normal warnings mode. Warnings are issued but ignored
7351 @item /WARNINGS=SUPPRESS
7352 @cindex @option{/WARNINGS} (@code{gnatbind})
7353 All warning messages are suppressed
7355 @item /WARNINGS=ERROR
7356 @cindex @option{/WARNINGS} (@code{gnatbind})
7357 Warning messages are treated as fatal errors
7358 @end ifset
7360 @item ^-x^/READ_SOURCES=NONE^
7361 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7362 Exclude source files (check object consistency only).
7364 @ifset vms
7365 @item /READ_SOURCES=AVAILABLE
7366 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7367 Default mode, in which sources are checked for consistency only if
7368 they are available.
7369 @end ifset
7371 @item ^-z^/ZERO_MAIN^
7372 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7373 No main subprogram.
7374 @end table
7376 @ifclear vms
7377 @noindent
7378 You may obtain this listing of switches by running @code{gnatbind} with
7379 no arguments.
7380 @end ifclear
7382 @node Consistency-Checking Modes
7383 @subsection Consistency-Checking Modes
7385 @noindent
7386 As described earlier, by default @code{gnatbind} checks
7387 that object files are consistent with one another and are consistent
7388 with any source files it can locate. The following switches control binder
7389 access to sources.
7391 @table @option
7392 @c !sort!
7393 @item ^-s^/READ_SOURCES=ALL^
7394 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7395 Require source files to be present. In this mode, the binder must be
7396 able to locate all source files that are referenced, in order to check
7397 their consistency. In normal mode, if a source file cannot be located it
7398 is simply ignored. If you specify this switch, a missing source
7399 file is an error.
7401 @item ^-x^/READ_SOURCES=NONE^
7402 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7403 Exclude source files. In this mode, the binder only checks that ALI
7404 files are consistent with one another. Source files are not accessed.
7405 The binder runs faster in this mode, and there is still a guarantee that
7406 the resulting program is self-consistent.
7407 If a source file has been edited since it was last compiled, and you
7408 specify this switch, the binder will not detect that the object
7409 file is out of date with respect to the source file. Note that this is the
7410 mode that is automatically used by @command{gnatmake} because in this
7411 case the checking against sources has already been performed by
7412 @command{gnatmake} in the course of compilation (i.e. before binding).
7414 @ifset vms
7415 @item /READ_SOURCES=AVAILABLE
7416 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7417 This is the default mode in which source files are checked if they are
7418 available, and ignored if they are not available.
7419 @end ifset
7420 @end table
7422 @node Binder Error Message Control
7423 @subsection Binder Error Message Control
7425 @noindent
7426 The following switches provide control over the generation of error
7427 messages from the binder:
7429 @table @option
7430 @c !sort!
7431 @item ^-v^/REPORT_ERRORS=VERBOSE^
7432 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7433 Verbose mode. In the normal mode, brief error messages are generated to
7434 @file{stderr}. If this switch is present, a header is written
7435 to @file{stdout} and any error messages are directed to @file{stdout}.
7436 All that is written to @file{stderr} is a brief summary message.
7438 @item ^-b^/REPORT_ERRORS=BRIEF^
7439 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7440 Generate brief error messages to @file{stderr} even if verbose mode is
7441 specified. This is relevant only when used with the
7442 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7444 @ifclear vms
7445 @item -m@var{n}
7446 @cindex @option{-m} (@code{gnatbind})
7447 Limits the number of error messages to @var{n}, a decimal integer in the
7448 range 1-999. The binder terminates immediately if this limit is reached.
7450 @item -M@var{xxx}
7451 @cindex @option{-M} (@code{gnatbind})
7452 Renames the generated main program from @code{main} to @code{xxx}.
7453 This is useful in the case of some cross-building environments, where
7454 the actual main program is separate from the one generated
7455 by @code{gnatbind}.
7456 @end ifclear
7458 @item ^-ws^/WARNINGS=SUPPRESS^
7459 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7460 @cindex Warnings
7461 Suppress all warning messages.
7463 @item ^-we^/WARNINGS=ERROR^
7464 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7465 Treat any warning messages as fatal errors.
7467 @ifset vms
7468 @item /WARNINGS=NORMAL
7469 Standard mode with warnings generated, but warnings do not get treated
7470 as errors.
7471 @end ifset
7473 @item ^-t^/NOTIME_STAMP_CHECK^
7474 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7475 @cindex Time stamp checks, in binder
7476 @cindex Binder consistency checks
7477 @cindex Consistency checks, in binder
7478 The binder performs a number of consistency checks including:
7480 @itemize @bullet
7481 @item
7482 Check that time stamps of a given source unit are consistent
7483 @item
7484 Check that checksums of a given source unit are consistent
7485 @item
7486 Check that consistent versions of @code{GNAT} were used for compilation
7487 @item
7488 Check consistency of configuration pragmas as required
7489 @end itemize
7491 @noindent
7492 Normally failure of such checks, in accordance with the consistency
7493 requirements of the Ada Reference Manual, causes error messages to be
7494 generated which abort the binder and prevent the output of a binder
7495 file and subsequent link to obtain an executable.
7497 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7498 into warnings, so that
7499 binding and linking can continue to completion even in the presence of such
7500 errors. The result may be a failed link (due to missing symbols), or a
7501 non-functional executable which has undefined semantics.
7502 @emph{This means that
7503 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7504 with extreme care.}
7505 @end table
7507 @node Elaboration Control
7508 @subsection Elaboration Control
7510 @noindent
7511 The following switches provide additional control over the elaboration
7512 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7514 @table @option
7515 @item ^-p^/PESSIMISTIC_ELABORATION^
7516 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7517 Normally the binder attempts to choose an elaboration order that is
7518 likely to minimize the likelihood of an elaboration order error resulting
7519 in raising a @code{Program_Error} exception. This switch reverses the
7520 action of the binder, and requests that it deliberately choose an order
7521 that is likely to maximize the likelihood of an elaboration error.
7522 This is useful in ensuring portability and avoiding dependence on
7523 accidental fortuitous elaboration ordering.
7525 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7526 switch if dynamic
7527 elaboration checking is used (@option{-gnatE} switch used for compilation).
7528 This is because in the default static elaboration mode, all necessary
7529 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
7530 These implicit pragmas are still respected by the binder in
7531 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7532 safe elaboration order is assured.
7533 @end table
7535 @node Output Control
7536 @subsection Output Control
7538 @noindent
7539 The following switches allow additional control over the output
7540 generated by the binder.
7542 @table @option
7543 @c !sort!
7545 @item ^-A^/BIND_FILE=ADA^
7546 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7547 Generate binder program in Ada (default). The binder program is named
7548 @file{b~@var{mainprog}.adb} by default. This can be changed with
7549 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7551 @item ^-c^/NOOUTPUT^
7552 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7553 Check only. Do not generate the binder output file. In this mode the
7554 binder performs all error checks but does not generate an output file.
7556 @item ^-C^/BIND_FILE=C^
7557 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7558 Generate binder program in C. The binder program is named
7559 @file{b_@var{mainprog}.c}.
7560 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7561 option.
7563 @item ^-e^/ELABORATION_DEPENDENCIES^
7564 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7565 Output complete list of elaboration-order dependencies, showing the
7566 reason for each dependency. This output can be rather extensive but may
7567 be useful in diagnosing problems with elaboration order. The output is
7568 written to @file{stdout}.
7570 @item ^-h^/HELP^
7571 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7572 Output usage information. The output is written to @file{stdout}.
7574 @item ^-K^/LINKER_OPTION_LIST^
7575 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7576 Output linker options to @file{stdout}. Includes library search paths,
7577 contents of pragmas Ident and Linker_Options, and libraries added
7578 by @code{gnatbind}.
7580 @item ^-l^/ORDER_OF_ELABORATION^
7581 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7582 Output chosen elaboration order. The output is written to @file{stdout}.
7584 @item ^-O^/OBJECT_LIST^
7585 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7586 Output full names of all the object files that must be linked to provide
7587 the Ada component of the program. The output is written to @file{stdout}.
7588 This list includes the files explicitly supplied and referenced by the user
7589 as well as implicitly referenced run-time unit files. The latter are
7590 omitted if the corresponding units reside in shared libraries. The
7591 directory names for the run-time units depend on the system configuration.
7593 @item ^-o ^/OUTPUT=^@var{file}
7594 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7595 Set name of output file to @var{file} instead of the normal
7596 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7597 binder generated body filename. In C mode you would normally give
7598 @var{file} an extension of @file{.c} because it will be a C source program.
7599 Note that if this option is used, then linking must be done manually.
7600 It is not possible to use gnatlink in this case, since it cannot locate
7601 the binder file.
7603 @item ^-r^/RESTRICTION_LIST^
7604 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7605 Generate list of @code{pragma Restrictions} that could be applied to
7606 the current unit. This is useful for code audit purposes, and also may
7607 be used to improve code generation in some cases.
7609 @end table
7611 @node Binding with Non-Ada Main Programs
7612 @subsection Binding with Non-Ada Main Programs
7614 @noindent
7615 In our description so far we have assumed that the main
7616 program is in Ada, and that the task of the binder is to generate a
7617 corresponding function @code{main} that invokes this Ada main
7618 program. GNAT also supports the building of executable programs where
7619 the main program is not in Ada, but some of the called routines are
7620 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7621 The following switch is used in this situation:
7623 @table @option
7624 @item ^-n^/NOMAIN^
7625 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7626 No main program. The main program is not in Ada.
7627 @end table
7629 @noindent
7630 In this case, most of the functions of the binder are still required,
7631 but instead of generating a main program, the binder generates a file
7632 containing the following callable routines:
7634 @table @code
7635 @item adainit
7636 @findex adainit
7637 You must call this routine to initialize the Ada part of the program by
7638 calling the necessary elaboration routines. A call to @code{adainit} is
7639 required before the first call to an Ada subprogram.
7641 Note that it is assumed that the basic execution environment must be setup
7642 to be appropriate for Ada execution at the point where the first Ada
7643 subprogram is called. In particular, if the Ada code will do any
7644 floating-point operations, then the FPU must be setup in an appropriate
7645 manner. For the case of the x86, for example, full precision mode is
7646 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7647 that the FPU is in the right state.
7649 @item adafinal
7650 @findex adafinal
7651 You must call this routine to perform any library-level finalization
7652 required by the Ada subprograms. A call to @code{adafinal} is required
7653 after the last call to an Ada subprogram, and before the program
7654 terminates.
7655 @end table
7657 @noindent
7658 If the @option{^-n^/NOMAIN^} switch
7659 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7660 @cindex Binder, multiple input files
7661 is given, more than one ALI file may appear on
7662 the command line for @code{gnatbind}. The normal @dfn{closure}
7663 calculation is performed for each of the specified units. Calculating
7664 the closure means finding out the set of units involved by tracing
7665 @code{with} references. The reason it is necessary to be able to
7666 specify more than one ALI file is that a given program may invoke two or
7667 more quite separate groups of Ada units.
7669 The binder takes the name of its output file from the last specified ALI
7670 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7671 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7672 The output is an Ada unit in source form that can
7673 be compiled with GNAT unless the -C switch is used in which case the
7674 output is a C source file, which must be compiled using the C compiler.
7675 This compilation occurs automatically as part of the @command{gnatlink}
7676 processing.
7678 Currently the GNAT run time requires a FPU using 80 bits mode
7679 precision. Under targets where this is not the default it is required to
7680 call GNAT.Float_Control.Reset before using floating point numbers (this
7681 include float computation, float input and output) in the Ada code. A
7682 side effect is that this could be the wrong mode for the foreign code
7683 where floating point computation could be broken after this call.
7685 @node Binding Programs with No Main Subprogram
7686 @subsection Binding Programs with No Main Subprogram
7688 @noindent
7689 It is possible to have an Ada program which does not have a main
7690 subprogram. This program will call the elaboration routines of all the
7691 packages, then the finalization routines.
7693 The following switch is used to bind programs organized in this manner:
7695 @table @option
7696 @item ^-z^/ZERO_MAIN^
7697 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7698 Normally the binder checks that the unit name given on the command line
7699 corresponds to a suitable main subprogram. When this switch is used,
7700 a list of ALI files can be given, and the execution of the program
7701 consists of elaboration of these units in an appropriate order.
7702 @end table
7704 @node Command-Line Access
7705 @section Command-Line Access
7707 @noindent
7708 The package @code{Ada.Command_Line} provides access to the command-line
7709 arguments and program name. In order for this interface to operate
7710 correctly, the two variables
7712 @smallexample
7713 @group
7714 int gnat_argc;
7715 char **gnat_argv;
7716 @end group
7717 @end smallexample
7719 @noindent
7720 @findex gnat_argv
7721 @findex gnat_argc
7722 are declared in one of the GNAT library routines. These variables must
7723 be set from the actual @code{argc} and @code{argv} values passed to the
7724 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7725 generates the C main program to automatically set these variables.
7726 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7727 set these variables. If they are not set, the procedures in
7728 @code{Ada.Command_Line} will not be available, and any attempt to use
7729 them will raise @code{Constraint_Error}. If command line access is
7730 required, your main program must set @code{gnat_argc} and
7731 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7734 @node Search Paths for gnatbind
7735 @section Search Paths for @code{gnatbind}
7737 @noindent
7738 The binder takes the name of an ALI file as its argument and needs to
7739 locate source files as well as other ALI files to verify object consistency.
7741 For source files, it follows exactly the same search rules as @command{gcc}
7742 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7743 directories searched are:
7745 @enumerate
7746 @item
7747 The directory containing the ALI file named in the command line, unless
7748 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7750 @item
7751 All directories specified by @option{^-I^/SEARCH^}
7752 switches on the @code{gnatbind}
7753 command line, in the order given.
7755 @item
7756 @findex ADA_PRJ_OBJECTS_FILE
7757 Each of the directories listed in the text file whose name is given
7758 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7760 @noindent
7761 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7762 driver when project files are used. It should not normally be set
7763 by other means.
7765 @item
7766 @findex ADA_OBJECTS_PATH
7767 Each of the directories listed in the value of the
7768 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7769 @ifset unw
7770 Construct this value
7771 exactly as the @code{PATH} environment variable: a list of directory
7772 names separated by colons (semicolons when working with the NT version
7773 of GNAT).
7774 @end ifset
7775 @ifset vms
7776 Normally, define this value as a logical name containing a comma separated
7777 list of directory names.
7779 This variable can also be defined by means of an environment string
7780 (an argument to the HP C exec* set of functions).
7782 Logical Name:
7783 @smallexample
7784 DEFINE ANOTHER_PATH FOO:[BAG]
7785 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7786 @end smallexample
7788 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7789 first, followed by the standard Ada 95
7790 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7791 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7792 (Text_IO, Sequential_IO, etc)
7793 instead of the Ada95 packages. Thus, in order to get the Ada 95
7794 packages by default, ADA_OBJECTS_PATH must be redefined.
7795 @end ifset
7797 @item
7798 The content of the @file{ada_object_path} file which is part of the GNAT
7799 installation tree and is used to store standard libraries such as the
7800 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7801 specified.
7802 @ifclear vms
7803 @ref{Installing a library}
7804 @end ifclear
7805 @end enumerate
7807 @noindent
7808 In the binder the switch @option{^-I^/SEARCH^}
7809 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7810 is used to specify both source and
7811 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7812 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7813 instead if you want to specify
7814 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7815 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7816 if you want to specify library paths
7817 only. This means that for the binder
7818 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7819 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7820 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7821 The binder generates the bind file (a C language source file) in the
7822 current working directory.
7824 @findex Ada
7825 @findex System
7826 @findex Interfaces
7827 @findex GNAT
7828 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7829 children make up the GNAT Run-Time Library, together with the package
7830 GNAT and its children, which contain a set of useful additional
7831 library functions provided by GNAT. The sources for these units are
7832 needed by the compiler and are kept together in one directory. The ALI
7833 files and object files generated by compiling the RTL are needed by the
7834 binder and the linker and are kept together in one directory, typically
7835 different from the directory containing the sources. In a normal
7836 installation, you need not specify these directory names when compiling
7837 or binding. Either the environment variables or the built-in defaults
7838 cause these files to be found.
7840 Besides simplifying access to the RTL, a major use of search paths is
7841 in compiling sources from multiple directories. This can make
7842 development environments much more flexible.
7844 @node Examples of gnatbind Usage
7845 @section Examples of @code{gnatbind} Usage
7847 @noindent
7848 This section contains a number of examples of using the GNAT binding
7849 utility @code{gnatbind}.
7851 @table @code
7852 @item gnatbind hello
7853 The main program @code{Hello} (source program in @file{hello.adb}) is
7854 bound using the standard switch settings. The generated main program is
7855 @file{b~hello.adb}. This is the normal, default use of the binder.
7857 @ifclear vms
7858 @item gnatbind hello -o mainprog.adb
7859 @end ifclear
7860 @ifset vms
7861 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7862 @end ifset
7863 The main program @code{Hello} (source program in @file{hello.adb}) is
7864 bound using the standard switch settings. The generated main program is
7865 @file{mainprog.adb} with the associated spec in
7866 @file{mainprog.ads}. Note that you must specify the body here not the
7867 spec, in the case where the output is in Ada. Note that if this option
7868 is used, then linking must be done manually, since gnatlink will not
7869 be able to find the generated file.
7871 @ifclear vms
7872 @item gnatbind main -C -o mainprog.c -x
7873 @end ifclear
7874 @ifset vms
7875 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7876 @end ifset
7877 The main program @code{Main} (source program in
7878 @file{main.adb}) is bound, excluding source files from the
7879 consistency checking, generating
7880 the file @file{mainprog.c}.
7882 @ifclear vms
7883 @item gnatbind -x main_program -C -o mainprog.c
7884 This command is exactly the same as the previous example. Switches may
7885 appear anywhere in the command line, and single letter switches may be
7886 combined into a single switch.
7887 @end ifclear
7889 @ifclear vms
7890 @item gnatbind -n math dbase -C -o ada-control.c
7891 @end ifclear
7892 @ifset vms
7893 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7894 @end ifset
7895 The main program is in a language other than Ada, but calls to
7896 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7897 to @code{gnatbind} generates the file @file{ada-control.c} containing
7898 the @code{adainit} and @code{adafinal} routines to be called before and
7899 after accessing the Ada units.
7900 @end table
7902 @c ------------------------------------
7903 @node Linking Using gnatlink
7904 @chapter Linking Using @command{gnatlink}
7905 @c ------------------------------------
7906 @findex gnatlink
7908 @noindent
7909 This chapter discusses @command{gnatlink}, a tool that links
7910 an Ada program and builds an executable file. This utility
7911 invokes the system linker ^(via the @command{gcc} command)^^
7912 with a correct list of object files and library references.
7913 @command{gnatlink} automatically determines the list of files and
7914 references for the Ada part of a program. It uses the binder file
7915 generated by the @command{gnatbind} to determine this list.
7917 @menu
7918 * Running gnatlink::
7919 * Switches for gnatlink::
7920 @end menu
7922 @node Running gnatlink
7923 @section Running @command{gnatlink}
7925 @noindent
7926 The form of the @command{gnatlink} command is
7928 @smallexample
7929 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7930            [@var{non-Ada objects}] [@var{linker options}]
7931 @end smallexample
7933 @noindent
7934 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
7935 non-Ada objects
7936 or linker options) may be in any order, provided that no non-Ada object may
7937 be mistaken for a main @file{ALI} file.
7938 Any file name @file{F} without the @file{.ali}
7939 extension will be taken as the main @file{ALI} file if a file exists
7940 whose name is the concatenation of @file{F} and @file{.ali}.
7942 @noindent
7943 @file{@var{mainprog}.ali} references the ALI file of the main program.
7944 The @file{.ali} extension of this file can be omitted. From this
7945 reference, @command{gnatlink} locates the corresponding binder file
7946 @file{b~@var{mainprog}.adb} and, using the information in this file along
7947 with the list of non-Ada objects and linker options, constructs a
7948 linker command file to create the executable.
7950 The arguments other than the @command{gnatlink} switches and the main
7951 @file{ALI} file are passed to the linker uninterpreted.
7952 They typically include the names of
7953 object files for units written in other languages than Ada and any library
7954 references required to resolve references in any of these foreign language
7955 units, or in @code{Import} pragmas in any Ada units.
7957 @var{linker options} is an optional list of linker specific
7958 switches.
7959 The default linker called by gnatlink is @var{gcc} which in
7960 turn calls the appropriate system linker.
7961 Standard options for the linker such as @option{-lmy_lib} or
7962 @option{-Ldir} can be added as is.
7963 For options that are not recognized by
7964 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7965 @option{-Wl,}.
7966 Refer to the GCC documentation for
7967 details. Here is an example showing how to generate a linker map:
7969 @smallexample
7970 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
7971 @end smallexample
7973 Using @var{linker options} it is possible to set the program stack and
7974 heap size.
7975 @ifclear vms
7976 See @ref{Setting Stack Size from gnatlink} and
7977 @ref{Setting Heap Size from gnatlink}.
7978 @end ifclear
7980 @command{gnatlink} determines the list of objects required by the Ada
7981 program and prepends them to the list of objects passed to the linker.
7982 @command{gnatlink} also gathers any arguments set by the use of
7983 @code{pragma Linker_Options} and adds them to the list of arguments
7984 presented to the linker.
7986 @ifset vms
7987 @command{gnatlink} accepts the following types of extra files on the command
7988 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7989 options files (.OPT). These are recognized and handled according to their
7990 extension.
7991 @end ifset
7993 @node Switches for gnatlink
7994 @section Switches for @command{gnatlink}
7996 @noindent
7997 The following switches are available with the @command{gnatlink} utility:
7999 @table @option
8000 @c !sort!
8002 @item ^-A^/BIND_FILE=ADA^
8003 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
8004 The binder has generated code in Ada. This is the default.
8006 @item ^-C^/BIND_FILE=C^
8007 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
8008 If instead of generating a file in Ada, the binder has generated one in
8009 C, then the linker needs to know about it. Use this switch to signal
8010 to @command{gnatlink} that the binder has generated C code rather than
8011 Ada code.
8013 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8014 @cindex Command line length
8015 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8016 On some targets, the command line length is limited, and @command{gnatlink}
8017 will generate a separate file for the linker if the list of object files
8018 is too long.
8019 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8020 to be generated even if
8021 the limit is not exceeded. This is useful in some cases to deal with
8022 special situations where the command line length is exceeded.
8024 @item ^-g^/DEBUG^
8025 @cindex Debugging information, including
8026 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8027 The option to include debugging information causes the Ada bind file (in
8028 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8029 @option{^-g^/DEBUG^}.
8030 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8031 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8032 Without @option{^-g^/DEBUG^}, the binder removes these files by
8033 default. The same procedure apply if a C bind file was generated using
8034 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8035 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8037 @item ^-n^/NOCOMPILE^
8038 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8039 Do not compile the file generated by the binder. This may be used when
8040 a link is rerun with different options, but there is no need to recompile
8041 the binder file.
8043 @item ^-v^/VERBOSE^
8044 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8045 Causes additional information to be output, including a full list of the
8046 included object files. This switch option is most useful when you want
8047 to see what set of object files are being used in the link step.
8049 @item ^-v -v^/VERBOSE/VERBOSE^
8050 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
8051 Very verbose mode. Requests that the compiler operate in verbose mode when
8052 it compiles the binder file, and that the system linker run in verbose mode.
8054 @item ^-o ^/EXECUTABLE=^@var{exec-name}
8055 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
8056 @var{exec-name} specifies an alternate name for the generated
8057 executable program. If this switch is omitted, the executable has the same
8058 name as the main unit. For example, @code{gnatlink try.ali} creates
8059 an executable called @file{^try^TRY.EXE^}.
8061 @ifclear vms
8062 @item -b @var{target}
8063 @cindex @option{-b} (@command{gnatlink})
8064 Compile your program to run on @var{target}, which is the name of a
8065 system configuration. You must have a GNAT cross-compiler built if
8066 @var{target} is not the same as your host system.
8068 @item -B@var{dir}
8069 @cindex @option{-B} (@command{gnatlink})
8070 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8071 from @var{dir} instead of the default location. Only use this switch
8072 when multiple versions of the GNAT compiler are available. See the
8073 @command{gcc} manual page for further details. You would normally use the
8074 @option{-b} or @option{-V} switch instead.
8076 @item --GCC=@var{compiler_name}
8077 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
8078 Program used for compiling the binder file. The default is
8079 @command{gcc}. You need to use quotes around @var{compiler_name} if
8080 @code{compiler_name} contains spaces or other separator characters.
8081 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
8082 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
8083 inserted after your command name. Thus in the above example the compiler
8084 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
8085 A limitation of this syntax is that the name and path name of the executable
8086 itself must not include any embedded spaces. If several
8087 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
8088 is taken into account. However, all the additional switches are also taken
8089 into account. Thus,
8090 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8091 @option{--GCC="bar -x -y -z -t"}.
8093 @item --LINK=@var{name}
8094 @cindex @option{--LINK=} (@command{gnatlink})
8095 @var{name} is the name of the linker to be invoked. This is especially
8096 useful in mixed language programs since languages such as C++ require
8097 their own linker to be used. When this switch is omitted, the default
8098 name for the linker is @command{gcc}. When this switch is used, the
8099 specified linker is called instead of @command{gcc} with exactly the same
8100 parameters that would have been passed to @command{gcc} so if the desired
8101 linker requires different parameters it is necessary to use a wrapper
8102 script that massages the parameters before invoking the real linker. It
8103 may be useful to control the exact invocation by using the verbose
8104 switch.
8106 @end ifclear
8108 @ifset vms
8109 @item /DEBUG=TRACEBACK
8110 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
8111 This qualifier causes sufficient information to be included in the
8112 executable file to allow a traceback, but does not include the full
8113 symbol information needed by the debugger.
8115 @item /IDENTIFICATION="<string>"
8116 @code{"<string>"} specifies the string to be stored in the image file
8117 identification field in the image header.
8118 It overrides any pragma @code{Ident} specified string.
8120 @item /NOINHIBIT-EXEC
8121 Generate the executable file even if there are linker warnings.
8123 @item /NOSTART_FILES
8124 Don't link in the object file containing the ``main'' transfer address.
8125 Used when linking with a foreign language main program compiled with an
8126 HP compiler.
8128 @item /STATIC
8129 Prefer linking with object libraries over sharable images, even without
8130 /DEBUG.
8131 @end ifset
8133 @end table
8136 @node The GNAT Make Program gnatmake
8137 @chapter The GNAT Make Program @command{gnatmake}
8138 @findex gnatmake
8140 @menu
8141 * Running gnatmake::
8142 * Switches for gnatmake::
8143 * Mode Switches for gnatmake::
8144 * Notes on the Command Line::
8145 * How gnatmake Works::
8146 * Examples of gnatmake Usage::
8147 @end menu
8148 @noindent
8149 A typical development cycle when working on an Ada program consists of
8150 the following steps:
8152 @enumerate
8153 @item
8154 Edit some sources to fix bugs.
8156 @item
8157 Add enhancements.
8159 @item
8160 Compile all sources affected.
8162 @item
8163 Rebind and relink.
8165 @item
8166 Test.
8167 @end enumerate
8169 @noindent
8170 The third step can be tricky, because not only do the modified files
8171 @cindex Dependency rules
8172 have to be compiled, but any files depending on these files must also be
8173 recompiled. The dependency rules in Ada can be quite complex, especially
8174 in the presence of overloading, @code{use} clauses, generics and inlined
8175 subprograms.
8177 @command{gnatmake} automatically takes care of the third and fourth steps
8178 of this process. It determines which sources need to be compiled,
8179 compiles them, and binds and links the resulting object files.
8181 Unlike some other Ada make programs, the dependencies are always
8182 accurately recomputed from the new sources. The source based approach of
8183 the GNAT compilation model makes this possible. This means that if
8184 changes to the source program cause corresponding changes in
8185 dependencies, they will always be tracked exactly correctly by
8186 @command{gnatmake}.
8188 @node Running gnatmake
8189 @section Running @command{gnatmake}
8191 @noindent
8192 The usual form of the @command{gnatmake} command is
8194 @smallexample
8195 $ gnatmake [@var{switches}] @var{file_name}
8196       [@var{file_names}] [@var{mode_switches}]
8197 @end smallexample
8199 @noindent
8200 The only required argument is one @var{file_name}, which specifies
8201 a compilation unit that is a main program. Several @var{file_names} can be
8202 specified: this will result in several executables being built.
8203 If @code{switches} are present, they can be placed before the first
8204 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8205 If @var{mode_switches} are present, they must always be placed after
8206 the last @var{file_name} and all @code{switches}.
8208 If you are using standard file extensions (.adb and .ads), then the
8209 extension may be omitted from the @var{file_name} arguments. However, if
8210 you are using non-standard extensions, then it is required that the
8211 extension be given. A relative or absolute directory path can be
8212 specified in a @var{file_name}, in which case, the input source file will
8213 be searched for in the specified directory only. Otherwise, the input
8214 source file will first be searched in the directory where
8215 @command{gnatmake} was invoked and if it is not found, it will be search on
8216 the source path of the compiler as described in
8217 @ref{Search Paths and the Run-Time Library (RTL)}.
8219 All @command{gnatmake} output (except when you specify
8220 @option{^-M^/DEPENDENCIES_LIST^}) is to
8221 @file{stderr}. The output produced by the
8222 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8223 @file{stdout}.
8225 @node Switches for gnatmake
8226 @section Switches for @command{gnatmake}
8228 @noindent
8229 You may specify any of the following switches to @command{gnatmake}:
8231 @table @option
8232 @c !sort!
8233 @ifclear vms
8234 @item --GCC=@var{compiler_name}
8235 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8236 Program used for compiling. The default is `@command{gcc}'. You need to use
8237 quotes around @var{compiler_name} if @code{compiler_name} contains
8238 spaces or other separator characters. As an example @option{--GCC="foo -x
8239 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8240 compiler. A limitation of this syntax is that the name and path name of
8241 the executable itself must not include any embedded spaces. Note that
8242 switch @option{-c} is always inserted after your command name. Thus in the
8243 above example the compiler command that will be used by @command{gnatmake}
8244 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
8245 used, only the last @var{compiler_name} is taken into account. However,
8246 all the additional switches are also taken into account. Thus,
8247 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8248 @option{--GCC="bar -x -y -z -t"}.
8250 @item --GNATBIND=@var{binder_name}
8251 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8252 Program used for binding. The default is `@code{gnatbind}'. You need to
8253 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8254 or other separator characters. As an example @option{--GNATBIND="bar -x
8255 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8256 binder. Binder switches that are normally appended by @command{gnatmake}
8257 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8258 A limitation of this syntax is that the name and path name of the executable
8259 itself must not include any embedded spaces.
8261 @item --GNATLINK=@var{linker_name}
8262 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8263 Program used for linking. The default is `@command{gnatlink}'. You need to
8264 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8265 or other separator characters. As an example @option{--GNATLINK="lan -x
8266 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8267 linker. Linker switches that are normally appended by @command{gnatmake} to
8268 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8269 A limitation of this syntax is that the name and path name of the executable
8270 itself must not include any embedded spaces.
8272 @end ifclear
8274 @item ^-a^/ALL_FILES^
8275 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8276 Consider all files in the make process, even the GNAT internal system
8277 files (for example, the predefined Ada library files), as well as any
8278 locked files. Locked files are files whose ALI file is write-protected.
8279 By default,
8280 @command{gnatmake} does not check these files,
8281 because the assumption is that the GNAT internal files are properly up
8282 to date, and also that any write protected ALI files have been properly
8283 installed. Note that if there is an installation problem, such that one
8284 of these files is not up to date, it will be properly caught by the
8285 binder.
8286 You may have to specify this switch if you are working on GNAT
8287 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8288 in conjunction with @option{^-f^/FORCE_COMPILE^}
8289 if you need to recompile an entire application,
8290 including run-time files, using special configuration pragmas,
8291 such as a @code{Normalize_Scalars} pragma.
8293 By default
8294 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8295 internal files with
8296 @ifclear vms
8297 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8298 @end ifclear
8299 @ifset vms
8300 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8301 @end ifset
8303 @item ^-b^/ACTIONS=BIND^
8304 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8305 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8306 compilation and binding, but no link.
8307 Can be combined with @option{^-l^/ACTIONS=LINK^}
8308 to do binding and linking. When not combined with
8309 @option{^-c^/ACTIONS=COMPILE^}
8310 all the units in the closure of the main program must have been previously
8311 compiled and must be up to date. The root unit specified by @var{file_name}
8312 may be given without extension, with the source extension or, if no GNAT
8313 Project File is specified, with the ALI file extension.
8315 @item ^-c^/ACTIONS=COMPILE^
8316 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8317 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8318 is also specified. Do not perform linking, except if both
8319 @option{^-b^/ACTIONS=BIND^} and
8320  @option{^-l^/ACTIONS=LINK^} are also specified.
8321 If the root unit specified by @var{file_name} is not a main unit, this is the
8322 default. Otherwise @command{gnatmake} will attempt binding and linking
8323 unless all objects are up to date and the executable is more recent than
8324 the objects.
8326 @item ^-C^/MAPPING^
8327 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8328 Use a temporary mapping file. A mapping file is a way to communicate to the
8329 compiler two mappings: from unit names to file names (without any directory
8330 information) and from file names to path names (with full directory
8331 information). These mappings are used by the compiler to short-circuit the path
8332 search. When @command{gnatmake} is invoked with this switch, it will create
8333 a temporary mapping file, initially populated by the project manager,
8334 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8335 Each invocation of the compiler will add the newly accessed sources to the
8336 mapping file. This will improve the source search during the next invocation
8337 of the compiler.
8339 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8340 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8341 Use a specific mapping file. The file, specified as a path name (absolute or
8342 relative) by this switch, should already exist, otherwise the switch is
8343 ineffective. The specified mapping file will be communicated to the compiler.
8344 This switch is not compatible with a project file
8345 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8346 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8348 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8349 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8350 Put all object files and ALI file in directory @var{dir}.
8351 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8352 and ALI files go in the current working directory.
8354 This switch cannot be used when using a project file.
8356 @ifclear vms
8357 @item -eL
8358 @cindex @option{-eL} (@command{gnatmake})
8359 Follow all symbolic links when processing project files.
8360 @end ifclear
8362 @item ^-f^/FORCE_COMPILE^
8363 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8364 Force recompilations. Recompile all sources, even though some object
8365 files may be up to date, but don't recompile predefined or GNAT internal
8366 files or locked files (files with a write-protected ALI file),
8367 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8369 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8370 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8371 When using project files, if some errors or warnings are detected during
8372 parsing and verbose mode is not in effect (no use of switch
8373 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8374 file, rather than its simple file name.
8376 @item ^-i^/IN_PLACE^
8377 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8378 In normal mode, @command{gnatmake} compiles all object files and ALI files
8379 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8380 then instead object files and ALI files that already exist are overwritten
8381 in place. This means that once a large project is organized into separate
8382 directories in the desired manner, then @command{gnatmake} will automatically
8383 maintain and update this organization. If no ALI files are found on the
8384 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8385 the new object and ALI files are created in the
8386 directory containing the source being compiled. If another organization
8387 is desired, where objects and sources are kept in different directories,
8388 a useful technique is to create dummy ALI files in the desired directories.
8389 When detecting such a dummy file, @command{gnatmake} will be forced to
8390 recompile the corresponding source file, and it will be put the resulting
8391 object and ALI files in the directory where it found the dummy file.
8393 @item ^-j^/PROCESSES=^@var{n}
8394 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8395 @cindex Parallel make
8396 Use @var{n} processes to carry out the (re)compilations. On a
8397 multiprocessor machine compilations will occur in parallel. In the
8398 event of compilation errors, messages from various compilations might
8399 get interspersed (but @command{gnatmake} will give you the full ordered
8400 list of failing compiles at the end). If this is problematic, rerun
8401 the make process with n set to 1 to get a clean list of messages.
8403 @item ^-k^/CONTINUE_ON_ERROR^
8404 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8405 Keep going. Continue as much as possible after a compilation error. To
8406 ease the programmer's task in case of compilation errors, the list of
8407 sources for which the compile fails is given when @command{gnatmake}
8408 terminates.
8410 If @command{gnatmake} is invoked with several @file{file_names} and with this
8411 switch, if there are compilation errors when building an executable,
8412 @command{gnatmake} will not attempt to build the following executables.
8414 @item ^-l^/ACTIONS=LINK^
8415 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8416 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8417 and linking. Linking will not be performed if combined with
8418 @option{^-c^/ACTIONS=COMPILE^}
8419 but not with @option{^-b^/ACTIONS=BIND^}.
8420 When not combined with @option{^-b^/ACTIONS=BIND^}
8421 all the units in the closure of the main program must have been previously
8422 compiled and must be up to date, and the main program needs to have been bound.
8423 The root unit specified by @var{file_name}
8424 may be given without extension, with the source extension or, if no GNAT
8425 Project File is specified, with the ALI file extension.
8427 @item ^-m^/MINIMAL_RECOMPILATION^
8428 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8429 Specify that the minimum necessary amount of recompilations
8430 be performed. In this mode @command{gnatmake} ignores time
8431 stamp differences when the only
8432 modifications to a source file consist in adding/removing comments,
8433 empty lines, spaces or tabs. This means that if you have changed the
8434 comments in a source file or have simply reformatted it, using this
8435 switch will tell gnatmake not to recompile files that depend on it
8436 (provided other sources on which these files depend have undergone no
8437 semantic modifications). Note that the debugging information may be
8438 out of date with respect to the sources if the @option{-m} switch causes
8439 a compilation to be switched, so the use of this switch represents a
8440 trade-off between compilation time and accurate debugging information.
8442 @item ^-M^/DEPENDENCIES_LIST^
8443 @cindex Dependencies, producing list
8444 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8445 Check if all objects are up to date. If they are, output the object
8446 dependences to @file{stdout} in a form that can be directly exploited in
8447 a @file{Makefile}. By default, each source file is prefixed with its
8448 (relative or absolute) directory name. This name is whatever you
8449 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8450 and @option{^-I^/SEARCH^} switches. If you use
8451 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8452 @option{^-q^/QUIET^}
8453 (see below), only the source file names,
8454 without relative paths, are output. If you just specify the
8455 @option{^-M^/DEPENDENCIES_LIST^}
8456 switch, dependencies of the GNAT internal system files are omitted. This
8457 is typically what you want. If you also specify
8458 the @option{^-a^/ALL_FILES^} switch,
8459 dependencies of the GNAT internal files are also listed. Note that
8460 dependencies of the objects in external Ada libraries (see switch
8461 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8462 are never reported.
8464 @item ^-n^/DO_OBJECT_CHECK^
8465 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8466 Don't compile, bind, or link. Checks if all objects are up to date.
8467 If they are not, the full name of the first file that needs to be
8468 recompiled is printed.
8469 Repeated use of this option, followed by compiling the indicated source
8470 file, will eventually result in recompiling all required units.
8472 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8473 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8474 Output executable name. The name of the final executable program will be
8475 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8476 name for the executable will be the name of the input file in appropriate form
8477 for an executable file on the host system.
8479 This switch cannot be used when invoking @command{gnatmake} with several
8480 @file{file_names}.
8482 @item ^-P^/PROJECT_FILE=^@var{project}
8483 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8484 Use project file @var{project}. Only one such switch can be used.
8485 @xref{gnatmake and Project Files}.
8487 @item ^-q^/QUIET^
8488 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8489 Quiet. When this flag is not set, the commands carried out by
8490 @command{gnatmake} are displayed.
8492 @item ^-s^/SWITCH_CHECK/^
8493 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8494 Recompile if compiler switches have changed since last compilation.
8495 All compiler switches but -I and -o are taken into account in the
8496 following way:
8497 orders between different ``first letter'' switches are ignored, but
8498 orders between same switches are taken into account. For example,
8499 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8500 is equivalent to @option{-O -g}.
8502 This switch is recommended when Integrated Preprocessing is used.
8504 @item ^-u^/UNIQUE^
8505 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8506 Unique. Recompile at most the main files. It implies -c. Combined with
8507 -f, it is equivalent to calling the compiler directly. Note that using
8508 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8509 (@pxref{Project Files and Main Subprograms}).
8511 @item ^-U^/ALL_PROJECTS^
8512 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8513 When used without a project file or with one or several mains on the command
8514 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8515 on the command line, all sources of all project files are checked and compiled
8516 if not up to date, and libraries are rebuilt, if necessary.
8518 @item ^-v^/REASONS^
8519 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8520 Verbose. Display the reason for all recompilations @command{gnatmake}
8521 decides are necessary, with the highest verbosity level.
8523 @item ^-vl^/LOW_VERBOSITY^
8524 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
8525 Verbosity level Low. Display fewer lines than in verbosity Medium.
8527 @item ^-vm^/MEDIUM_VERBOSITY^
8528 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
8529 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
8531 @item ^-vh^/HIGH_VERBOSITY^
8532 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
8533 Verbosity level High. Equivalent to ^-v^/REASONS^.
8535 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8536 Indicate the verbosity of the parsing of GNAT project files.
8537 @xref{Switches Related to Project Files}.
8539 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8540 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8541 Indicate that sources that are not part of any Project File may be compiled.
8542 Normally, when using Project Files, only sources that are part of a Project
8543 File may be compile. When this switch is used, a source outside of all Project
8544 Files may be compiled. The ALI file and the object file will be put in the
8545 object directory of the main Project. The compilation switches used will only
8546 be those specified on the command line.
8548 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8549 Indicate that external variable @var{name} has the value @var{value}.
8550 The Project Manager will use this value for occurrences of
8551 @code{external(name)} when parsing the project file.
8552 @xref{Switches Related to Project Files}.
8554 @item ^-z^/NOMAIN^
8555 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8556 No main subprogram. Bind and link the program even if the unit name
8557 given on the command line is a package name. The resulting executable
8558 will execute the elaboration routines of the package and its closure,
8559 then the finalization routines.
8561 @item ^-g^/DEBUG^
8562 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8563 Enable debugging. This switch is simply passed to the compiler and to the
8564 linker.
8566 @end table
8568 @table @asis
8569 @item @command{gcc} @asis{switches}
8570 @ifclear vms
8571 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8572 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8573 @end ifclear
8574 @ifset vms
8575 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8576 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8577 automatically treated as a compiler switch, and passed on to all
8578 compilations that are carried out.
8579 @end ifset
8580 @end table
8582 @noindent
8583 Source and library search path switches:
8585 @table @option
8586 @c !sort!
8587 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8588 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8589 When looking for source files also look in directory @var{dir}.
8590 The order in which source files search is undertaken is
8591 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8593 @item ^-aL^/SKIP_MISSING=^@var{dir}
8594 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
8595 Consider @var{dir} as being an externally provided Ada library.
8596 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
8597 files have been located in directory @var{dir}. This allows you to have
8598 missing bodies for the units in @var{dir} and to ignore out of date bodies
8599 for the same units. You still need to specify
8600 the location of the specs for these units by using the switches
8601 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8602 or @option{^-I^/SEARCH=^@var{dir}}.
8603 Note: this switch is provided for compatibility with previous versions
8604 of @command{gnatmake}. The easier method of causing standard libraries
8605 to be excluded from consideration is to write-protect the corresponding
8606 ALI files.
8608 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8609 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
8610 When searching for library and object files, look in directory
8611 @var{dir}. The order in which library files are searched is described in
8612 @ref{Search Paths for gnatbind}.
8614 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8615 @cindex Search paths, for @command{gnatmake}
8616 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
8617 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8618 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8620 @item ^-I^/SEARCH=^@var{dir}
8621 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
8622 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8623 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8625 @item ^-I-^/NOCURRENT_DIRECTORY^
8626 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
8627 @cindex Source files, suppressing search
8628 Do not look for source files in the directory containing the source
8629 file named in the command line.
8630 Do not look for ALI or object files in the directory
8631 where @command{gnatmake} was invoked.
8633 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8634 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
8635 @cindex Linker libraries
8636 Add directory @var{dir} to the list of directories in which the linker
8637 will search for libraries. This is equivalent to
8638 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8639 @ifclear vms
8640 Furthermore, under Windows, the sources pointed to by the libraries path
8641 set in the registry are not searched for.
8642 @end ifclear
8644 @item -nostdinc
8645 @cindex @option{-nostdinc} (@command{gnatmake})
8646 Do not look for source files in the system default directory.
8648 @item -nostdlib
8649 @cindex @option{-nostdlib} (@command{gnatmake})
8650 Do not look for library files in the system default directory.
8652 @item --RTS=@var{rts-path}
8653 @cindex @option{--RTS} (@command{gnatmake})
8654 Specifies the default location of the runtime library. GNAT looks for the
8655 runtime
8656 in the following directories, and stops as soon as a valid runtime is found
8657 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8658 @file{ada_object_path} present):
8660 @itemize @bullet
8661 @item <current directory>/$rts_path
8663 @item <default-search-dir>/$rts_path
8665 @item <default-search-dir>/rts-$rts_path
8666 @end itemize
8668 @noindent
8669 The selected path is handled like a normal RTS path.
8671 @end table
8673 @node Mode Switches for gnatmake
8674 @section Mode Switches for @command{gnatmake}
8676 @noindent
8677 The mode switches (referred to as @code{mode_switches}) allow the
8678 inclusion of switches that are to be passed to the compiler itself, the
8679 binder or the linker. The effect of a mode switch is to cause all
8680 subsequent switches up to the end of the switch list, or up to the next
8681 mode switch, to be interpreted as switches to be passed on to the
8682 designated component of GNAT.
8684 @table @option
8685 @c !sort!
8686 @item -cargs @var{switches}
8687 @cindex @option{-cargs} (@command{gnatmake})
8688 Compiler switches. Here @var{switches} is a list of switches
8689 that are valid switches for @command{gcc}. They will be passed on to
8690 all compile steps performed by @command{gnatmake}.
8692 @item -bargs @var{switches}
8693 @cindex @option{-bargs} (@command{gnatmake})
8694 Binder switches. Here @var{switches} is a list of switches
8695 that are valid switches for @code{gnatbind}. They will be passed on to
8696 all bind steps performed by @command{gnatmake}.
8698 @item -largs @var{switches}
8699 @cindex @option{-largs} (@command{gnatmake})
8700 Linker switches. Here @var{switches} is a list of switches
8701 that are valid switches for @command{gnatlink}. They will be passed on to
8702 all link steps performed by @command{gnatmake}.
8704 @item -margs @var{switches}
8705 @cindex @option{-margs} (@command{gnatmake})
8706 Make switches. The switches are directly interpreted by @command{gnatmake},
8707 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8708 or @option{-largs}.
8709 @end table
8711 @node Notes on the Command Line
8712 @section Notes on the Command Line
8714 @noindent
8715 This section contains some additional useful notes on the operation
8716 of the @command{gnatmake} command.
8718 @itemize @bullet
8719 @item
8720 @cindex Recompilation, by @command{gnatmake}
8721 If @command{gnatmake} finds no ALI files, it recompiles the main program
8722 and all other units required by the main program.
8723 This means that @command{gnatmake}
8724 can be used for the initial compile, as well as during subsequent steps of
8725 the development cycle.
8727 @item
8728 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8729 is a subunit or body of a generic unit, @command{gnatmake} recompiles
8730 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8731 warning.
8733 @item
8734 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
8735 is used to specify both source and
8736 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8737 instead if you just want to specify
8738 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8739 if you want to specify library paths
8740 only.
8742 @item
8743 @command{gnatmake} will ignore any files whose ALI file is write-protected.
8744 This may conveniently be used to exclude standard libraries from
8745 consideration and in particular it means that the use of the
8746 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8747 unless @option{^-a^/ALL_FILES^} is also specified.
8749 @item
8750 @command{gnatmake} has been designed to make the use of Ada libraries
8751 particularly convenient. Assume you have an Ada library organized
8752 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8753 of your Ada compilation units,
8754 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8755 specs of these units, but no bodies. Then to compile a unit
8756 stored in @code{main.adb}, which uses this Ada library you would just type
8758 @smallexample
8759 @ifclear vms
8760 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8761 @end ifclear
8762 @ifset vms
8763 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8764            /SKIP_MISSING=@i{[OBJ_DIR]} main
8765 @end ifset
8766 @end smallexample
8768 @item
8769 Using @command{gnatmake} along with the
8770 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8771 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8772 this switch,
8773 you can update the comments/format of your
8774 source files without having to recompile everything. Note, however, that
8775 adding or deleting lines in a source files may render its debugging
8776 info obsolete. If the file in question is a spec, the impact is rather
8777 limited, as that debugging info will only be useful during the
8778 elaboration phase of your program. For bodies the impact can be more
8779 significant. In all events, your debugger will warn you if a source file
8780 is more recent than the corresponding object, and alert you to the fact
8781 that the debugging information may be out of date.
8782 @end itemize
8784 @node How gnatmake Works
8785 @section How @command{gnatmake} Works
8787 @noindent
8788 Generally @command{gnatmake} automatically performs all necessary
8789 recompilations and you don't need to worry about how it works. However,
8790 it may be useful to have some basic understanding of the @command{gnatmake}
8791 approach and in particular to understand how it uses the results of
8792 previous compilations without incorrectly depending on them.
8794 First a definition: an object file is considered @dfn{up to date} if the
8795 corresponding ALI file exists and if all the source files listed in the
8796 dependency section of this ALI file have time stamps matching those in
8797 the ALI file. This means that neither the source file itself nor any
8798 files that it depends on have been modified, and hence there is no need
8799 to recompile this file.
8801 @command{gnatmake} works by first checking if the specified main unit is up
8802 to date. If so, no compilations are required for the main unit. If not,
8803 @command{gnatmake} compiles the main program to build a new ALI file that
8804 reflects the latest sources. Then the ALI file of the main unit is
8805 examined to find all the source files on which the main program depends,
8806 and @command{gnatmake} recursively applies the above procedure on all these
8807 files.
8809 This process ensures that @command{gnatmake} only trusts the dependencies
8810 in an existing ALI file if they are known to be correct. Otherwise it
8811 always recompiles to determine a new, guaranteed accurate set of
8812 dependencies. As a result the program is compiled ``upside down'' from what may
8813 be more familiar as the required order of compilation in some other Ada
8814 systems. In particular, clients are compiled before the units on which
8815 they depend. The ability of GNAT to compile in any order is critical in
8816 allowing an order of compilation to be chosen that guarantees that
8817 @command{gnatmake} will recompute a correct set of new dependencies if
8818 necessary.
8820 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
8821 imported by several of the executables, it will be recompiled at most once.
8823 Note: when using non-standard naming conventions
8824 (@pxref{Using Other File Names}), changing through a configuration pragmas
8825 file the version of a source and invoking @command{gnatmake} to recompile may
8826 have no effect, if the previous version of the source is still accessible
8827 by @command{gnatmake}. It may be necessary to use the switch
8828 ^-f^/FORCE_COMPILE^.
8830 @node Examples of gnatmake Usage
8831 @section Examples of @command{gnatmake} Usage
8833 @table @code
8834 @item gnatmake hello.adb
8835 Compile all files necessary to bind and link the main program
8836 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8837 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8839 @item gnatmake main1 main2 main3
8840 Compile all files necessary to bind and link the main programs
8841 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8842 (containing unit @code{Main2}) and @file{main3.adb}
8843 (containing unit @code{Main3}) and bind and link the resulting object files
8844 to generate three executable files @file{^main1^MAIN1.EXE^},
8845 @file{^main2^MAIN2.EXE^}
8846 and @file{^main3^MAIN3.EXE^}.
8848 @ifclear vms
8849 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8850 @end ifclear
8852 @ifset vms
8853 @item gnatmake Main_Unit /QUIET
8854    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8855    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8856 @end ifset
8857 Compile all files necessary to bind and link the main program unit
8858 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8859 be done with optimization level 2 and the order of elaboration will be
8860 listed by the binder. @command{gnatmake} will operate in quiet mode, not
8861 displaying commands it is executing.
8862 @end table
8864 @c *************************
8865 @node Improving Performance
8866 @chapter Improving Performance
8867 @cindex Improving performance
8869 @noindent
8870 This chapter presents several topics related to program performance.
8871 It first describes some of the tradeoffs that need to be considered
8872 and some of the techniques for making your program run faster.
8873 It then documents the @command{gnatelim} tool and unused subprogram/data
8874 elimination feature, which can reduce the size of program executables.
8876 @ifnottex
8877 @menu
8878 * Performance Considerations::
8879 * Reducing the Size of Ada Executables with gnatelim::
8880 * Reducing the Size of Executables with unused subprogram/data elimination::
8881 @end menu
8882 @end ifnottex
8884 @c *****************************
8885 @node Performance Considerations
8886 @section Performance Considerations
8888 @noindent
8889 The GNAT system provides a number of options that allow a trade-off
8890 between
8892 @itemize @bullet
8893 @item
8894 performance of the generated code
8896 @item
8897 speed of compilation
8899 @item
8900 minimization of dependences and recompilation
8902 @item
8903 the degree of run-time checking.
8904 @end itemize
8906 @noindent
8907 The defaults (if no options are selected) aim at improving the speed
8908 of compilation and minimizing dependences, at the expense of performance
8909 of the generated code:
8911 @itemize @bullet
8912 @item
8913 no optimization
8915 @item
8916 no inlining of subprogram calls
8918 @item
8919 all run-time checks enabled except overflow and elaboration checks
8920 @end itemize
8922 @noindent
8923 These options are suitable for most program development purposes. This
8924 chapter describes how you can modify these choices, and also provides
8925 some guidelines on debugging optimized code.
8927 @menu
8928 * Controlling Run-Time Checks::
8929 * Use of Restrictions::
8930 * Optimization Levels::
8931 * Debugging Optimized Code::
8932 * Inlining of Subprograms::
8933 * Other Optimization Switches::
8934 * Optimization and Strict Aliasing::
8936 @ifset vms
8937 * Coverage Analysis::
8938 @end ifset
8939 @end menu
8941 @node Controlling Run-Time Checks
8942 @subsection Controlling Run-Time Checks
8944 @noindent
8945 By default, GNAT generates all run-time checks, except arithmetic overflow
8946 checking for integer operations and checks for access before elaboration on
8947 subprogram calls. The latter are not required in default mode, because all
8948 necessary checking is done at compile time.
8949 @cindex @option{-gnatp} (@command{gcc})
8950 @cindex @option{-gnato} (@command{gcc})
8951 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8952 be modified. @xref{Run-Time Checks}.
8954 Our experience is that the default is suitable for most development
8955 purposes.
8957 We treat integer overflow specially because these
8958 are quite expensive and in our experience are not as important as other
8959 run-time checks in the development process. Note that division by zero
8960 is not considered an overflow check, and divide by zero checks are
8961 generated where required by default.
8963 Elaboration checks are off by default, and also not needed by default, since
8964 GNAT uses a static elaboration analysis approach that avoids the need for
8965 run-time checking. This manual contains a full chapter discussing the issue
8966 of elaboration checks, and if the default is not satisfactory for your use,
8967 you should read this chapter.
8969 For validity checks, the minimal checks required by the Ada Reference
8970 Manual (for case statements and assignments to array elements) are on
8971 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8972 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8973 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8974 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8975 are also suppressed entirely if @option{-gnatp} is used.
8977 @cindex Overflow checks
8978 @cindex Checks, overflow
8979 @findex Suppress
8980 @findex Unsuppress
8981 @cindex pragma Suppress
8982 @cindex pragma Unsuppress
8983 Note that the setting of the switches controls the default setting of
8984 the checks. They may be modified using either @code{pragma Suppress} (to
8985 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8986 checks) in the program source.
8988 @node Use of Restrictions
8989 @subsection Use of Restrictions
8991 @noindent
8992 The use of pragma Restrictions allows you to control which features are
8993 permitted in your program. Apart from the obvious point that if you avoid
8994 relatively expensive features like finalization (enforceable by the use
8995 of pragma Restrictions (No_Finalization), the use of this pragma does not
8996 affect the generated code in most cases.
8998 One notable exception to this rule is that the possibility of task abort
8999 results in some distributed overhead, particularly if finalization or
9000 exception handlers are used. The reason is that certain sections of code
9001 have to be marked as non-abortable.
9003 If you use neither the @code{abort} statement, nor asynchronous transfer
9004 of control (@code{select .. then abort}), then this distributed overhead
9005 is removed, which may have a general positive effect in improving
9006 overall performance.  Especially code involving frequent use of tasking
9007 constructs and controlled types will show much improved performance.
9008 The relevant restrictions pragmas are
9010 @smallexample @c ada
9011    pragma Restrictions (No_Abort_Statements);
9012    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
9013 @end smallexample
9015 @noindent
9016 It is recommended that these restriction pragmas be used if possible. Note
9017 that this also means that you can write code without worrying about the
9018 possibility of an immediate abort at any point.
9020 @node Optimization Levels
9021 @subsection Optimization Levels
9022 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
9024 @noindent
9025 The default is optimization off. This results in the fastest compile
9026 times, but GNAT makes absolutely no attempt to optimize, and the
9027 generated programs are considerably larger and slower than when
9028 optimization is enabled. You can use the
9029 @ifclear vms
9030 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
9031 @end ifclear
9032 @ifset vms
9033 @code{OPTIMIZE} qualifier
9034 @end ifset
9035 to @command{gcc} to control the optimization level:
9037 @table @option
9038 @item ^-O0^/OPTIMIZE=NONE^
9039 No optimization (the default);
9040 generates unoptimized code but has
9041 the fastest compilation time.
9043 Note that many other compilers do fairly extensive optimization
9044 even if "no optimization" is specified. When using gcc, it is
9045 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
9046 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
9047 really does mean no optimization at all. This difference between
9048 gcc and other compilers should be kept in mind when doing
9049 performance comparisons.
9051 @item ^-O1^/OPTIMIZE=SOME^
9052 Moderate optimization;
9053 optimizes reasonably well but does not
9054 degrade compilation time significantly.
9056 @item ^-O2^/OPTIMIZE=ALL^
9057 @ifset vms
9058 @itemx /OPTIMIZE=DEVELOPMENT
9059 @end ifset
9060 Full optimization;
9061 generates highly optimized code and has
9062 the slowest compilation time.
9064 @item ^-O3^/OPTIMIZE=INLINING^
9065 Full optimization as in @option{-O2},
9066 and also attempts automatic inlining of small
9067 subprograms within a unit (@pxref{Inlining of Subprograms}).
9068 @end table
9070 @noindent
9071 Higher optimization levels perform more global transformations on the
9072 program and apply more expensive analysis algorithms in order to generate
9073 faster and more compact code. The price in compilation time, and the
9074 resulting improvement in execution time,
9075 both depend on the particular application and the hardware environment.
9076 You should experiment to find the best level for your application.
9078 Since the precise set of optimizations done at each level will vary from
9079 release to release (and sometime from target to target), it is best to think
9080 of the optimization settings in general terms.
9081 The @cite{Using GNU GCC} manual contains details about
9082 ^the @option{-O} settings and a number of @option{-f} options that^how to^
9083 individually enable or disable specific optimizations.
9085 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
9086 been tested extensively at all optimization levels. There are some bugs
9087 which appear only with optimization turned on, but there have also been
9088 bugs which show up only in @emph{unoptimized} code. Selecting a lower
9089 level of optimization does not improve the reliability of the code
9090 generator, which in practice is highly reliable at all optimization
9091 levels.
9093 Note regarding the use of @option{-O3}: The use of this optimization level
9094 is generally discouraged with GNAT, since it often results in larger
9095 executables which run more slowly. See further discussion of this point
9096 in @ref{Inlining of Subprograms}.
9098 @node Debugging Optimized Code
9099 @subsection Debugging Optimized Code
9100 @cindex Debugging optimized code
9101 @cindex Optimization and debugging
9103 @noindent
9104 Although it is possible to do a reasonable amount of debugging at
9105 @ifclear vms
9106 non-zero optimization levels,
9107 the higher the level the more likely that
9108 @end ifclear
9109 @ifset vms
9110 @option{/OPTIMIZE} settings other than @code{NONE},
9111 such settings will make it more likely that
9112 @end ifset
9113 source-level constructs will have been eliminated by optimization.
9114 For example, if a loop is strength-reduced, the loop
9115 control variable may be completely eliminated and thus cannot be
9116 displayed in the debugger.
9117 This can only happen at @option{-O2} or @option{-O3}.
9118 Explicit temporary variables that you code might be eliminated at
9119 ^level^setting^ @option{-O1} or higher.
9121 The use of the @option{^-g^/DEBUG^} switch,
9122 @cindex @option{^-g^/DEBUG^} (@command{gcc})
9123 which is needed for source-level debugging,
9124 affects the size of the program executable on disk,
9125 and indeed the debugging information can be quite large.
9126 However, it has no effect on the generated code (and thus does not
9127 degrade performance)
9129 Since the compiler generates debugging tables for a compilation unit before
9130 it performs optimizations, the optimizing transformations may invalidate some
9131 of the debugging data.  You therefore need to anticipate certain
9132 anomalous situations that may arise while debugging optimized code.
9133 These are the most common cases:
9135 @enumerate
9136 @item
9137 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
9138 commands show
9139 the PC bouncing back and forth in the code.  This may result from any of
9140 the following optimizations:
9142 @itemize @bullet
9143 @item
9144 @i{Common subexpression elimination:} using a single instance of code for a
9145 quantity that the source computes several times.  As a result you
9146 may not be able to stop on what looks like a statement.
9148 @item
9149 @i{Invariant code motion:} moving an expression that does not change within a
9150 loop, to the beginning of the loop.
9152 @item
9153 @i{Instruction scheduling:} moving instructions so as to
9154 overlap loads and stores (typically) with other code, or in
9155 general to move computations of values closer to their uses. Often
9156 this causes you to pass an assignment statement without the assignment
9157 happening and then later bounce back to the statement when the
9158 value is actually needed.  Placing a breakpoint on a line of code
9159 and then stepping over it may, therefore, not always cause all the
9160 expected side-effects.
9161 @end itemize
9163 @item
9164 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
9165 two identical pieces of code are merged and the program counter suddenly
9166 jumps to a statement that is not supposed to be executed, simply because
9167 it (and the code following) translates to the same thing as the code
9168 that @emph{was} supposed to be executed.  This effect is typically seen in
9169 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
9170 a @code{break} in a C @code{^switch^switch^} statement.
9172 @item
9173 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9174 There are various reasons for this effect:
9176 @itemize @bullet
9177 @item
9178 In a subprogram prologue, a parameter may not yet have been moved to its
9179 ``home''.
9181 @item
9182 A variable may be dead, and its register re-used.  This is
9183 probably the most common cause.
9185 @item
9186 As mentioned above, the assignment of a value to a variable may
9187 have been moved.
9189 @item
9190 A variable may be eliminated entirely by value propagation or
9191 other means.  In this case, GCC may incorrectly generate debugging
9192 information for the variable
9193 @end itemize
9195 @noindent
9196 In general, when an unexpected value appears for a local variable or parameter
9197 you should first ascertain if that value was actually computed by
9198 your program, as opposed to being incorrectly reported by the debugger.
9199 Record fields or
9200 array elements in an object designated by an access value
9201 are generally less of a problem, once you have ascertained that the access
9202 value is sensible.
9203 Typically, this means checking variables in the preceding code and in the
9204 calling subprogram to verify that the value observed is explainable from other
9205 values (one must apply the procedure recursively to those
9206 other values); or re-running the code and stopping a little earlier
9207 (perhaps before the call) and stepping to better see how the variable obtained
9208 the value in question; or continuing to step @emph{from} the point of the
9209 strange value to see if code motion had simply moved the variable's
9210 assignments later.
9211 @end enumerate
9213 @noindent
9214 In light of such anomalies, a recommended technique is to use @option{-O0}
9215 early in the software development cycle, when extensive debugging capabilities
9216 are most needed, and then move to @option{-O1} and later @option{-O2} as
9217 the debugger becomes less critical.
9218 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9219 a release management issue.
9220 @ifclear vms
9221 Note that if you use @option{-g} you can then use the @command{strip} program
9222 on the resulting executable,
9223 which removes both debugging information and global symbols.
9224 @end ifclear
9226 @node Inlining of Subprograms
9227 @subsection Inlining of Subprograms
9229 @noindent
9230 A call to a subprogram in the current unit is inlined if all the
9231 following conditions are met:
9233 @itemize @bullet
9234 @item
9235 The optimization level is at least @option{-O1}.
9237 @item
9238 The called subprogram is suitable for inlining: It must be small enough
9239 and not contain nested subprograms or anything else that @command{gcc}
9240 cannot support in inlined subprograms.
9242 @item
9243 The call occurs after the definition of the body of the subprogram.
9245 @item
9246 @cindex pragma Inline
9247 @findex Inline
9248 Either @code{pragma Inline} applies to the subprogram or it is
9249 small and automatic inlining (optimization level @option{-O3}) is
9250 specified.
9251 @end itemize
9253 @noindent
9254 Calls to subprograms in @code{with}'ed units are normally not inlined.
9255 To achieve this level of inlining, the following conditions must all be
9256 true:
9258 @itemize @bullet
9259 @item
9260 The optimization level is at least @option{-O1}.
9262 @item
9263 The called subprogram is suitable for inlining: It must be small enough
9264 and not contain nested subprograms or anything else @command{gcc} cannot
9265 support in inlined subprograms.
9267 @item
9268 The call appears in a body (not in a package spec).
9270 @item
9271 There is a @code{pragma Inline} for the subprogram.
9273 @item
9274 @cindex @option{-gnatn} (@command{gcc})
9275 The @option{^-gnatn^/INLINE^} switch
9276 is used in the @command{gcc} command line
9277 @end itemize
9279 Note that specifying the @option{-gnatn} switch causes additional
9280 compilation dependencies. Consider the following:
9282 @smallexample @c ada
9283 @cartouche
9284 package R is
9285    procedure Q;
9286    pragma Inline (Q);
9287 end R;
9288 package body R is
9289    ...
9290 end R;
9292 with R;
9293 procedure Main is
9294 begin
9295    ...
9296    R.Q;
9297 end Main;
9298 @end cartouche
9299 @end smallexample
9301 @noindent
9302 With the default behavior (no @option{-gnatn} switch specified), the
9303 compilation of the @code{Main} procedure depends only on its own source,
9304 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9305 means that editing the body of @code{R} does not require recompiling
9306 @code{Main}.
9308 On the other hand, the call @code{R.Q} is not inlined under these
9309 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9310 is compiled, the call will be inlined if the body of @code{Q} is small
9311 enough, but now @code{Main} depends on the body of @code{R} in
9312 @file{r.adb} as well as on the spec. This means that if this body is edited,
9313 the main program must be recompiled. Note that this extra dependency
9314 occurs whether or not the call is in fact inlined by @command{gcc}.
9316 The use of front end inlining with @option{-gnatN} generates similar
9317 additional dependencies.
9319 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9320 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9321 can be used to prevent
9322 all inlining. This switch overrides all other conditions and ensures
9323 that no inlining occurs. The extra dependences resulting from
9324 @option{-gnatn} will still be active, even if
9325 this switch is used to suppress the resulting inlining actions.
9327 Note regarding the use of @option{-O3}: There is no difference in inlining
9328 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9329 pragma @code{Inline} assuming the use of @option{-gnatn}
9330 or @option{-gnatN} (the switches that activate inlining). If you have used
9331 pragma @code{Inline} in appropriate cases, then it is usually much better
9332 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9333 in this case only has the effect of inlining subprograms you did not
9334 think should be inlined. We often find that the use of @option{-O3} slows
9335 down code by performing excessive inlining, leading to increased instruction
9336 cache pressure from the increased code size. So the bottom line here is
9337 that you should not automatically assume that @option{-O3} is better than
9338 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9339 it actually improves performance.
9341 @node Other Optimization Switches
9342 @subsection Other Optimization Switches
9343 @cindex Optimization Switches
9345 Since @code{GNAT} uses the @code{gcc} back end, all the specialized
9346 @code{gcc} optimization switches are potentially usable. These switches
9347 have not been extensively tested with GNAT but can generally be expected
9348 to work. Examples of switches in this category are
9349 @option{-funroll-loops} and
9350 the various target-specific @option{-m} options (in particular, it has been
9351 observed that @option{-march=pentium4} can significantly improve performance
9352 on appropriate machines). For full details of these switches, see the
9353 @code{gcc} manual.
9355 @node Optimization and Strict Aliasing
9356 @subsection Optimization and Strict Aliasing
9357 @cindex Aliasing
9358 @cindex Strict Aliasing
9359 @cindex No_Strict_Aliasing
9361 @noindent
9362 The strong typing capabilities of Ada allow an optimizer to generate
9363 efficient code in situations where other languages would be forced to
9364 make worst case assumptions preventing such optimizations. Consider
9365 the following example:
9367 @smallexample @c ada
9368 @cartouche
9369 procedure R is
9370    type Int1 is new Integer;
9371    type Int2 is new Integer;
9372    type Int1A is access Int1;
9373    type Int2A is access Int2;
9374    Int1V : Int1A;
9375    Int2V : Int2A;
9376    ...
9378 begin
9379    ...
9380    for J in Data'Range loop
9381       if Data (J) = Int1V.all then
9382          Int2V.all := Int2V.all + 1;
9383       end if;
9384    end loop;
9385    ...
9386 end R;
9387 @end cartouche
9388 @end smallexample
9390 @noindent
9391 In this example, since the variable @code{Int1V} can only access objects
9392 of type @code{Int1}, and @code{Int2V} can only access objects of type
9393 @code{Int2}, there is no possibility that the assignment to
9394 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9395 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9396 for all iterations of the loop and avoid the extra memory reference
9397 required to dereference it each time through the loop.
9399 This kind of optimization, called strict aliasing analysis, is
9400 triggered by specifying an optimization level of @option{-O2} or
9401 higher and allows @code{GNAT} to generate more efficient code
9402 when access values are involved.
9404 However, although this optimization is always correct in terms of
9405 the formal semantics of the Ada Reference Manual, difficulties can
9406 arise if features like @code{Unchecked_Conversion} are used to break
9407 the typing system. Consider the following complete program example:
9409 @smallexample @c ada
9410 @cartouche
9411 package p1 is
9412    type int1 is new integer;
9413    type int2 is new integer;
9414    type a1 is access int1;
9415    type a2 is access int2;
9416 end p1;
9418 with p1; use p1;
9419 package p2 is
9420    function to_a2 (Input : a1) return a2;
9421 end p2;
9423 with Unchecked_Conversion;
9424 package body p2 is
9425    function to_a2 (Input : a1) return a2 is
9426       function to_a2u is
9427         new Unchecked_Conversion (a1, a2);
9428    begin
9429       return to_a2u (Input);
9430    end to_a2;
9431 end p2;
9433 with p2; use p2;
9434 with p1; use p1;
9435 with Text_IO; use Text_IO;
9436 procedure m is
9437    v1 : a1 := new int1;
9438    v2 : a2 := to_a2 (v1);
9439 begin
9440    v1.all := 1;
9441    v2.all := 0;
9442    put_line (int1'image (v1.all));
9443 end;
9444 @end cartouche
9445 @end smallexample
9447 @noindent
9448 This program prints out 0 in @code{-O0} or @code{-O1}
9449 mode, but it prints out 1 in @code{-O2} mode. That's
9450 because in strict aliasing mode, the compiler can and
9451 does assume that the assignment to @code{v2.all} could not
9452 affect the value of @code{v1.all}, since different types
9453 are involved.
9455 This behavior is not a case of non-conformance with the standard, since
9456 the Ada RM specifies that an unchecked conversion where the resulting
9457 bit pattern is not a correct value of the target type can result in an
9458 abnormal value and attempting to reference an abnormal value makes the
9459 execution of a program erroneous.  That's the case here since the result
9460 does not point to an object of type @code{int2}.  This means that the
9461 effect is entirely unpredictable.
9463 However, although that explanation may satisfy a language
9464 lawyer, in practice an applications programmer expects an
9465 unchecked conversion involving pointers to create true
9466 aliases and the behavior of printing 1 seems plain wrong.
9467 In this case, the strict aliasing optimization is unwelcome.
9469 Indeed the compiler recognizes this possibility, and the
9470 unchecked conversion generates a warning:
9472 @smallexample
9473 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9474 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9475 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9476 @end smallexample
9478 @noindent
9479 Unfortunately the problem is recognized when compiling the body of
9480 package @code{p2}, but the actual "bad" code is generated while
9481 compiling the body of @code{m} and this latter compilation does not see
9482 the suspicious @code{Unchecked_Conversion}.
9484 As implied by the warning message, there are approaches you can use to
9485 avoid the unwanted strict aliasing optimization in a case like this.
9487 One possibility is to simply avoid the use of @code{-O2}, but
9488 that is a bit drastic, since it throws away a number of useful
9489 optimizations that do not involve strict aliasing assumptions.
9491 A less drastic approach is to compile the program using the
9492 option @code{-fno-strict-aliasing}. Actually it is only the
9493 unit containing the dereferencing of the suspicious pointer
9494 that needs to be compiled. So in this case, if we compile
9495 unit @code{m} with this switch, then we get the expected
9496 value of zero printed. Analyzing which units might need
9497 the switch can be painful, so a more reasonable approach
9498 is to compile the entire program with options @code{-O2}
9499 and @code{-fno-strict-aliasing}. If the performance is
9500 satisfactory with this combination of options, then the
9501 advantage is that the entire issue of possible "wrong"
9502 optimization due to strict aliasing is avoided.
9504 To avoid the use of compiler switches, the configuration
9505 pragma @code{No_Strict_Aliasing} with no parameters may be
9506 used to specify that for all access types, the strict
9507 aliasing optimization should be suppressed.
9509 However, these approaches are still overkill, in that they causes
9510 all manipulations of all access values to be deoptimized. A more
9511 refined approach is to concentrate attention on the specific
9512 access type identified as problematic.
9514 First, if a careful analysis of uses of the pointer shows
9515 that there are no possible problematic references, then
9516 the warning can be suppressed by bracketing the
9517 instantiation of @code{Unchecked_Conversion} to turn
9518 the warning off:
9520 @smallexample @c ada
9521    pragma Warnings (Off);
9522    function to_a2u is
9523      new Unchecked_Conversion (a1, a2);
9524    pragma Warnings (On);
9525 @end smallexample
9527 @noindent
9528 Of course that approach is not appropriate for this particular
9529 example, since indeed there is a problematic reference. In this
9530 case we can take one of two other approaches.
9532 The first possibility is to move the instantiation of unchecked
9533 conversion to the unit in which the type is declared. In
9534 this example, we would move the instantiation of
9535 @code{Unchecked_Conversion} from the body of package
9536 @code{p2} to the spec of package @code{p1}. Now the
9537 warning disappears. That's because any use of the
9538 access type knows there is a suspicious unchecked
9539 conversion, and the strict aliasing optimization
9540 is automatically suppressed for the type.
9542 If it is not practical to move the unchecked conversion to the same unit
9543 in which the destination access type is declared (perhaps because the
9544 source type is not visible in that unit), you may use pragma
9545 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9546 same declarative sequence as the declaration of the access type:
9548 @smallexample @c ada
9549    type a2 is access int2;
9550    pragma No_Strict_Aliasing (a2);
9551 @end smallexample
9553 @noindent
9554 Here again, the compiler now knows that the strict aliasing optimization
9555 should be suppressed for any reference to type @code{a2} and the
9556 expected behavior is obtained.
9558 Finally, note that although the compiler can generate warnings for
9559 simple cases of unchecked conversions, there are tricker and more
9560 indirect ways of creating type incorrect aliases which the compiler
9561 cannot detect. Examples are the use of address overlays and unchecked
9562 conversions involving composite types containing access types as
9563 components. In such cases, no warnings are generated, but there can
9564 still be aliasing problems. One safe coding practice is to forbid the
9565 use of address clauses for type overlaying, and to allow unchecked
9566 conversion only for primitive types. This is not really a significant
9567 restriction since any possible desired effect can be achieved by
9568 unchecked conversion of access values.
9570 @ifset vms
9571 @node Coverage Analysis
9572 @subsection Coverage Analysis
9574 @noindent
9575 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
9576 the user to determine the distribution of execution time across a program,
9577 @pxref{Profiling} for details of usage.
9578 @end ifset
9580 @node Reducing the Size of Ada Executables with gnatelim
9581 @section Reducing the Size of Ada Executables with @code{gnatelim}
9582 @findex gnatelim
9584 @noindent
9585 This section describes @command{gnatelim}, a tool which detects unused
9586 subprograms and helps the compiler to create a smaller executable for your
9587 program.
9589 @menu
9590 * About gnatelim::
9591 * Running gnatelim::
9592 * Correcting the List of Eliminate Pragmas::
9593 * Making Your Executables Smaller::
9594 * Summary of the gnatelim Usage Cycle::
9595 @end menu
9597 @node About gnatelim
9598 @subsection About @code{gnatelim}
9600 @noindent
9601 When a program shares a set of Ada
9602 packages with other programs, it may happen that this program uses
9603 only a fraction of the subprograms defined in these packages. The code
9604 created for these unused subprograms increases the size of the executable.
9606 @code{gnatelim} tracks unused subprograms in an Ada program and
9607 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9608 subprograms that are declared but never called. By placing the list of
9609 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9610 recompiling your program, you may decrease the size of its executable,
9611 because the compiler will not generate the code for 'eliminated' subprograms.
9612 See GNAT Reference Manual for more information about this pragma.
9614 @code{gnatelim} needs as its input data the name of the main subprogram
9615 and a bind file for a main subprogram.
9617 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9618 the main subprogram. @code{gnatelim} can work with both Ada and C
9619 bind files; when both are present, it uses the Ada bind file.
9620 The following commands will build the program and create the bind file:
9622 @smallexample
9623 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9624 $ gnatbind main_prog
9625 @end smallexample
9627 Note that @code{gnatelim} needs neither object nor ALI files.
9629 @node Running gnatelim
9630 @subsection Running @code{gnatelim}
9632 @noindent
9633 @code{gnatelim} has the following command-line interface:
9635 @smallexample
9636 $ gnatelim [options] name
9637 @end smallexample
9639 @noindent
9640 @code{name} should be a name of a source file that contains the main subprogram
9641 of a program (partition).
9643 @code{gnatelim} has the following switches:
9645 @table @option
9646 @c !sort!
9647 @item ^-q^/QUIET^
9648 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9649 Quiet mode: by default @code{gnatelim} outputs to the standard error
9650 stream the number of program units left to be processed. This option turns
9651 this trace off.
9653 @item ^-v^/VERBOSE^
9654 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9655 Verbose mode: @code{gnatelim} version information is printed as Ada
9656 comments to the standard output stream. Also, in addition to the number of
9657 program units left @code{gnatelim} will output the name of the current unit
9658 being processed.
9660 @item ^-a^/ALL^
9661 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9662 Also look for subprograms from the GNAT run time that can be eliminated. Note
9663 that when @file{gnat.adc} is produced using this switch, the entire program
9664 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
9666 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9667 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9668 When looking for source files also look in directory @var{dir}. Specifying
9669 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9670 sources in the current directory.
9672 @item ^-b^/BIND_FILE=^@var{bind_file}
9673 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9674 Specifies @var{bind_file} as the bind file to process. If not set, the name
9675 of the bind file is computed from the full expanded Ada name
9676 of a main subprogram.
9678 @item ^-C^/CONFIG_FILE=^@var{config_file}
9679 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9680 Specifies a file @var{config_file} that contains configuration pragmas. The
9681 file must be specified with full path.
9683 @item ^--GCC^/COMPILER^=@var{compiler_name}
9684 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9685 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
9686 available on the path.
9688 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9689 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9690 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
9691 available on the path.
9692 @end table
9694 @noindent
9695 @code{gnatelim} sends its output to the standard output stream, and all the
9696 tracing and debug information is sent to the standard error stream.
9697 In order to produce a proper GNAT configuration file
9698 @file{gnat.adc}, redirection must be used:
9700 @smallexample
9701 @ifset vms
9702 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9703 @end ifset
9704 @ifclear vms
9705 $ gnatelim main_prog.adb > gnat.adc
9706 @end ifclear
9707 @end smallexample
9709 @ifclear vms
9710 @noindent
9713 @smallexample
9714 $ gnatelim main_prog.adb >> gnat.adc
9715 @end smallexample
9717 @noindent
9718 in order to append the @code{gnatelim} output to the existing contents of
9719 @file{gnat.adc}.
9720 @end ifclear
9722 @node Correcting the List of Eliminate Pragmas
9723 @subsection Correcting the List of Eliminate Pragmas
9725 @noindent
9726 In some rare cases @code{gnatelim} may try to eliminate
9727 subprograms that are actually called in the program. In this case, the
9728 compiler will generate an error message of the form:
9730 @smallexample
9731 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9732 @end smallexample
9734 @noindent
9735 You will need to manually remove the wrong @code{Eliminate} pragmas from
9736 the @file{gnat.adc} file. You should recompile your program
9737 from scratch after that, because you need a consistent @file{gnat.adc} file
9738 during the entire compilation.
9740 @node Making Your Executables Smaller
9741 @subsection Making Your Executables Smaller
9743 @noindent
9744 In order to get a smaller executable for your program you now have to
9745 recompile the program completely with the new @file{gnat.adc} file
9746 created by @code{gnatelim} in your current directory:
9748 @smallexample
9749 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9750 @end smallexample
9752 @noindent
9753 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9754 recompile everything
9755 with the set of pragmas @code{Eliminate} that you have obtained with
9756 @command{gnatelim}).
9758 Be aware that the set of @code{Eliminate} pragmas is specific to each
9759 program. It is not recommended to merge sets of @code{Eliminate}
9760 pragmas created for different programs in one @file{gnat.adc} file.
9762 @node Summary of the gnatelim Usage Cycle
9763 @subsection Summary of the gnatelim Usage Cycle
9765 @noindent
9766 Here is a quick summary of the steps to be taken in order to reduce
9767 the size of your executables with @code{gnatelim}. You may use
9768 other GNAT options to control the optimization level,
9769 to produce the debugging information, to set search path, etc.
9771 @enumerate
9772 @item
9773 Produce a bind file
9775 @smallexample
9776 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9777 $ gnatbind main_prog
9778 @end smallexample
9780 @item
9781 Generate a list of @code{Eliminate} pragmas
9782 @smallexample
9783 @ifset vms
9784 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9785 @end ifset
9786 @ifclear vms
9787 $ gnatelim main_prog >[>] gnat.adc
9788 @end ifclear
9789 @end smallexample
9791 @item
9792 Recompile the application
9794 @smallexample
9795 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9796 @end smallexample
9798 @end enumerate
9800 @node Reducing the Size of Executables with unused subprogram/data elimination
9801 @section Reducing the Size of Executables with Unused Subprogram/Data Elimination
9802 @findex unused subprogram/data elimination
9804 @noindent
9805 This section describes how you can eliminate unused subprograms and data from
9806 your executable just by setting options at compilation time.
9808 @menu
9809 * About unused subprogram/data elimination::
9810 * Compilation options::
9811 @end menu
9813 @node About unused subprogram/data elimination
9814 @subsection About unused subprogram/data elimination
9816 @noindent
9817 By default, an executable contains all code and data of its composing objects
9818 (directly linked or coming from statically linked libraries), even data or code
9819 never used by this executable.
9821 This feature will allow you to eliminate such unused code from your
9822 executable, making it smaller (in disk and in memory).
9824 This functionality is only available on native x86 GNU/Linux platform for the
9825 moment.
9827 @node Compilation options
9828 @subsection Compilation options
9830 @noindent
9831 The operation of eliminating the unused code and data from the final executable
9832 is directly performed by the linker.
9834 In order to do this, it has to work with objects compiled with the
9835 following options:
9836 @option{-ffunction-sections} @option{-fdata-sections}.
9837 @cindex @option{-ffunction-sections} (@command{gcc})
9838 @cindex @option{-fdata-sections} (@command{gcc})
9839 These options are usable with C and Ada files.
9840 They will place respectively each
9841 function or data in a separate section in the resulting object file.
9843 Once the objects and static libraries are created with these options, the
9844 linker can perform the dead code elimination. You can do this by setting
9845 the @option{-Wl,--gc-sections} option to gcc command or in the
9846 @option{-largs} section of gnatmake. This will create the final executable,
9847 without including the code and data determined as never accessed.
9849 Note that objects compiled without the @option{-ffunction-sections} and
9850 @option{-fdata-sections} options can still be linked with the executable.
9851 However, no dead code elimination will be performed on those objects (they will
9852 be linked as is).
9854 The GNAT static library is now compiled with -ffunction-sections and
9855 -fdata-sections. This allows you to eliminate the unused code of the GNAT
9856 library from your executable.
9858 @c ********************************
9859 @node Renaming Files Using gnatchop
9860 @chapter Renaming Files Using @code{gnatchop}
9861 @findex gnatchop
9863 @noindent
9864 This chapter discusses how to handle files with multiple units by using
9865 the @code{gnatchop} utility. This utility is also useful in renaming
9866 files to meet the standard GNAT default file naming conventions.
9868 @menu
9869 * Handling Files with Multiple Units::
9870 * Operating gnatchop in Compilation Mode::
9871 * Command Line for gnatchop::
9872 * Switches for gnatchop::
9873 * Examples of gnatchop Usage::
9874 @end menu
9876 @node Handling Files with Multiple Units
9877 @section Handling Files with Multiple Units
9879 @noindent
9880 The basic compilation model of GNAT requires that a file submitted to the
9881 compiler have only one unit and there be a strict correspondence
9882 between the file name and the unit name.
9884 The @code{gnatchop} utility allows both of these rules to be relaxed,
9885 allowing GNAT to process files which contain multiple compilation units
9886 and files with arbitrary file names. @code{gnatchop}
9887 reads the specified file and generates one or more output files,
9888 containing one unit per file. The unit and the file name correspond,
9889 as required by GNAT.
9891 If you want to permanently restructure a set of ``foreign'' files so that
9892 they match the GNAT rules, and do the remaining development using the
9893 GNAT structure, you can simply use @command{gnatchop} once, generate the
9894 new set of files and work with them from that point on.
9896 Alternatively, if you want to keep your files in the ``foreign'' format,
9897 perhaps to maintain compatibility with some other Ada compilation
9898 system, you can set up a procedure where you use @command{gnatchop} each
9899 time you compile, regarding the source files that it writes as temporary
9900 files that you throw away.
9902 @node Operating gnatchop in Compilation Mode
9903 @section Operating gnatchop in Compilation Mode
9905 @noindent
9906 The basic function of @code{gnatchop} is to take a file with multiple units
9907 and split it into separate files. The boundary between files is reasonably
9908 clear, except for the issue of comments and pragmas. In default mode, the
9909 rule is that any pragmas between units belong to the previous unit, except
9910 that configuration pragmas always belong to the following unit. Any comments
9911 belong to the following unit. These rules
9912 almost always result in the right choice of
9913 the split point without needing to mark it explicitly and most users will
9914 find this default to be what they want. In this default mode it is incorrect to
9915 submit a file containing only configuration pragmas, or one that ends in
9916 configuration pragmas, to @code{gnatchop}.
9918 However, using a special option to activate ``compilation mode'',
9919 @code{gnatchop}
9920 can perform another function, which is to provide exactly the semantics
9921 required by the RM for handling of configuration pragmas in a compilation.
9922 In the absence of configuration pragmas (at the main file level), this
9923 option has no effect, but it causes such configuration pragmas to be handled
9924 in a quite different manner.
9926 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9927 only configuration pragmas, then this file is appended to the
9928 @file{gnat.adc} file in the current directory. This behavior provides
9929 the required behavior described in the RM for the actions to be taken
9930 on submitting such a file to the compiler, namely that these pragmas
9931 should apply to all subsequent compilations in the same compilation
9932 environment. Using GNAT, the current directory, possibly containing a
9933 @file{gnat.adc} file is the representation
9934 of a compilation environment. For more information on the
9935 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
9937 Second, in compilation mode, if @code{gnatchop}
9938 is given a file that starts with
9939 configuration pragmas, and contains one or more units, then these
9940 configuration pragmas are prepended to each of the chopped files. This
9941 behavior provides the required behavior described in the RM for the
9942 actions to be taken on compiling such a file, namely that the pragmas
9943 apply to all units in the compilation, but not to subsequently compiled
9944 units.
9946 Finally, if configuration pragmas appear between units, they are appended
9947 to the previous unit. This results in the previous unit being illegal,
9948 since the compiler does not accept configuration pragmas that follow
9949 a unit. This provides the required RM behavior that forbids configuration
9950 pragmas other than those preceding the first compilation unit of a
9951 compilation.
9953 For most purposes, @code{gnatchop} will be used in default mode. The
9954 compilation mode described above is used only if you need exactly
9955 accurate behavior with respect to compilations, and you have files
9956 that contain multiple units and configuration pragmas. In this
9957 circumstance the use of @code{gnatchop} with the compilation mode
9958 switch provides the required behavior, and is for example the mode
9959 in which GNAT processes the ACVC tests.
9961 @node Command Line for gnatchop
9962 @section Command Line for @code{gnatchop}
9964 @noindent
9965 The @code{gnatchop} command has the form:
9967 @smallexample
9968 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9969       [@var{directory}]
9970 @end smallexample
9972 @noindent
9973 The only required argument is the file name of the file to be chopped.
9974 There are no restrictions on the form of this file name. The file itself
9975 contains one or more Ada units, in normal GNAT format, concatenated
9976 together. As shown, more than one file may be presented to be chopped.
9978 When run in default mode, @code{gnatchop} generates one output file in
9979 the current directory for each unit in each of the files.
9981 @var{directory}, if specified, gives the name of the directory to which
9982 the output files will be written. If it is not specified, all files are
9983 written to the current directory.
9985 For example, given a
9986 file called @file{hellofiles} containing
9988 @smallexample @c ada
9989 @group
9990 @cartouche
9991 procedure hello;
9993 with Text_IO; use Text_IO;
9994 procedure hello is
9995 begin
9996    Put_Line ("Hello");
9997 end hello;
9998 @end cartouche
9999 @end group
10000 @end smallexample
10002 @noindent
10003 the command
10005 @smallexample
10006 $ gnatchop ^hellofiles^HELLOFILES.^
10007 @end smallexample
10009 @noindent
10010 generates two files in the current directory, one called
10011 @file{hello.ads} containing the single line that is the procedure spec,
10012 and the other called @file{hello.adb} containing the remaining text. The
10013 original file is not affected. The generated files can be compiled in
10014 the normal manner.
10016 @noindent
10017 When gnatchop is invoked on a file that is empty or that contains only empty
10018 lines and/or comments, gnatchop will not fail, but will not produce any
10019 new sources.
10021 For example, given a
10022 file called @file{toto.txt} containing
10024 @smallexample @c ada
10025 @group
10026 @cartouche
10027 --  Just a comment
10028 @end cartouche
10029 @end group
10030 @end smallexample
10032 @noindent
10033 the command
10035 @smallexample
10036 $ gnatchop ^toto.txt^TOT.TXT^
10037 @end smallexample
10039 @noindent
10040 will not produce any new file and will result in the following warnings:
10042 @smallexample
10043 toto.txt:1:01: warning: empty file, contains no compilation units
10044 no compilation units found
10045 no source files written
10046 @end smallexample
10048 @node Switches for gnatchop
10049 @section Switches for @code{gnatchop}
10051 @noindent
10052 @command{gnatchop} recognizes the following switches:
10054 @table @option
10055 @c !sort!
10057 @item ^-c^/COMPILATION^
10058 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
10059 Causes @code{gnatchop} to operate in compilation mode, in which
10060 configuration pragmas are handled according to strict RM rules. See
10061 previous section for a full description of this mode.
10063 @ifclear vms
10064 @item -gnatxxx
10065 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
10066 used to parse the given file. Not all @code{xxx} options make sense,
10067 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
10068 process a source file that uses Latin-2 coding for identifiers.
10069 @end ifclear
10071 @item ^-h^/HELP^
10072 Causes @code{gnatchop} to generate a brief help summary to the standard
10073 output file showing usage information.
10075 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
10076 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
10077 Limit generated file names to the specified number @code{mm}
10078 of characters.
10079 This is useful if the
10080 resulting set of files is required to be interoperable with systems
10081 which limit the length of file names.
10082 @ifset vms
10083 If no value is given, or
10084 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
10085 a default of 39, suitable for OpenVMS Alpha
10086 Systems, is assumed
10087 @end ifset
10088 @ifclear vms
10089 No space is allowed between the @option{-k} and the numeric value. The numeric
10090 value may be omitted in which case a default of @option{-k8},
10091 suitable for use
10092 with DOS-like file systems, is used. If no @option{-k} switch
10093 is present then
10094 there is no limit on the length of file names.
10095 @end ifclear
10097 @item ^-p^/PRESERVE^
10098 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
10099 Causes the file ^modification^creation^ time stamp of the input file to be
10100 preserved and used for the time stamp of the output file(s). This may be
10101 useful for preserving coherency of time stamps in an environment where
10102 @code{gnatchop} is used as part of a standard build process.
10104 @item ^-q^/QUIET^
10105 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
10106 Causes output of informational messages indicating the set of generated
10107 files to be suppressed. Warnings and error messages are unaffected.
10109 @item ^-r^/REFERENCE^
10110 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
10111 @findex Source_Reference
10112 Generate @code{Source_Reference} pragmas. Use this switch if the output
10113 files are regarded as temporary and development is to be done in terms
10114 of the original unchopped file. This switch causes
10115 @code{Source_Reference} pragmas to be inserted into each of the
10116 generated files to refers back to the original file name and line number.
10117 The result is that all error messages refer back to the original
10118 unchopped file.
10119 In addition, the debugging information placed into the object file (when
10120 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
10121 specified)
10122 also refers back to this original file so that tools like profilers and
10123 debuggers will give information in terms of the original unchopped file.
10125 If the original file to be chopped itself contains
10126 a @code{Source_Reference}
10127 pragma referencing a third file, then gnatchop respects
10128 this pragma, and the generated @code{Source_Reference} pragmas
10129 in the chopped file refer to the original file, with appropriate
10130 line numbers. This is particularly useful when @code{gnatchop}
10131 is used in conjunction with @code{gnatprep} to compile files that
10132 contain preprocessing statements and multiple units.
10134 @item ^-v^/VERBOSE^
10135 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
10136 Causes @code{gnatchop} to operate in verbose mode. The version
10137 number and copyright notice are output, as well as exact copies of
10138 the gnat1 commands spawned to obtain the chop control information.
10140 @item ^-w^/OVERWRITE^
10141 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
10142 Overwrite existing file names. Normally @code{gnatchop} regards it as a
10143 fatal error if there is already a file with the same name as a
10144 file it would otherwise output, in other words if the files to be
10145 chopped contain duplicated units. This switch bypasses this
10146 check, and causes all but the last instance of such duplicated
10147 units to be skipped.
10149 @ifclear vms
10150 @item --GCC=xxxx
10151 @cindex @option{--GCC=} (@code{gnatchop})
10152 Specify the path of the GNAT parser to be used. When this switch is used,
10153 no attempt is made to add the prefix to the GNAT parser executable.
10154 @end ifclear
10155 @end table
10157 @node Examples of gnatchop Usage
10158 @section Examples of @code{gnatchop} Usage
10160 @table @code
10161 @ifset vms
10162 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
10163 @end ifset
10164 @ifclear vms
10165 @item gnatchop -w hello_s.ada prerelease/files
10166 @end ifclear
10168 Chops the source file @file{hello_s.ada}. The output files will be
10169 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
10170 overwriting any
10171 files with matching names in that directory (no files in the current
10172 directory are modified).
10174 @item gnatchop ^archive^ARCHIVE.^
10175 Chops the source file @file{^archive^ARCHIVE.^}
10176 into the current directory. One
10177 useful application of @code{gnatchop} is in sending sets of sources
10178 around, for example in email messages. The required sources are simply
10179 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
10180 command), and then
10181 @code{gnatchop} is used at the other end to reconstitute the original
10182 file names.
10184 @item gnatchop file1 file2 file3 direc
10185 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
10186 the resulting files in the directory @file{direc}. Note that if any units
10187 occur more than once anywhere within this set of files, an error message
10188 is generated, and no files are written. To override this check, use the
10189 @option{^-w^/OVERWRITE^} switch,
10190 in which case the last occurrence in the last file will
10191 be the one that is output, and earlier duplicate occurrences for a given
10192 unit will be skipped.
10193 @end table
10195 @node Configuration Pragmas
10196 @chapter Configuration Pragmas
10197 @cindex Configuration pragmas
10198 @cindex Pragmas, configuration
10200 @noindent
10201 In Ada 95, configuration pragmas include those pragmas described as
10202 such in the Ada 95 Reference Manual, as well as
10203 implementation-dependent pragmas that are configuration pragmas. See the
10204 individual descriptions of pragmas in the GNAT Reference Manual for
10205 details on these additional GNAT-specific configuration pragmas. Most
10206 notably, the pragma @code{Source_File_Name}, which allows
10207 specifying non-default names for source files, is a configuration
10208 pragma. The following is a complete list of configuration pragmas
10209 recognized by @code{GNAT}:
10211 @smallexample
10212    Ada_83
10213    Ada_95
10214    Ada_05
10215    C_Pass_By_Copy
10216    Component_Alignment
10217    Detect_Blocking
10218    Discard_Names
10219    Elaboration_Checks
10220    Eliminate
10221    Extend_System
10222    External_Name_Casing
10223    Float_Representation
10224    Initialize_Scalars
10225    Interrupt_State
10226    License
10227    Locking_Policy
10228    Long_Float
10229    Normalize_Scalars
10230    Persistent_BSS
10231    Polling
10232    Profile
10233    Profile_Warnings
10234    Propagate_Exceptions
10235    Queuing_Policy
10236    Ravenscar
10237    Restricted_Run_Time
10238    Restrictions
10239    Restrictions_Warnings
10240    Reviewable
10241    Source_File_Name
10242    Style_Checks
10243    Suppress
10244    Task_Dispatching_Policy
10245    Universal_Data
10246    Unsuppress
10247    Use_VADS_Size
10248    Warnings
10249    Validity_Checks
10250 @end smallexample
10252 @menu
10253 * Handling of Configuration Pragmas::
10254 * The Configuration Pragmas Files::
10255 @end menu
10257 @node Handling of Configuration Pragmas
10258 @section Handling of Configuration Pragmas
10260 Configuration pragmas may either appear at the start of a compilation
10261 unit, in which case they apply only to that unit, or they may apply to
10262 all compilations performed in a given compilation environment.
10264 GNAT also provides the @code{gnatchop} utility to provide an automatic
10265 way to handle configuration pragmas following the semantics for
10266 compilations (that is, files with multiple units), described in the RM.
10267 See @ref{Operating gnatchop in Compilation Mode} for details.
10268 However, for most purposes, it will be more convenient to edit the
10269 @file{gnat.adc} file that contains configuration pragmas directly,
10270 as described in the following section.
10272 @node The Configuration Pragmas Files
10273 @section The Configuration Pragmas Files
10274 @cindex @file{gnat.adc}
10276 @noindent
10277 In GNAT a compilation environment is defined by the current
10278 directory at the time that a compile command is given. This current
10279 directory is searched for a file whose name is @file{gnat.adc}. If
10280 this file is present, it is expected to contain one or more
10281 configuration pragmas that will be applied to the current compilation.
10282 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10283 considered.
10285 Configuration pragmas may be entered into the @file{gnat.adc} file
10286 either by running @code{gnatchop} on a source file that consists only of
10287 configuration pragmas, or more conveniently  by
10288 direct editing of the @file{gnat.adc} file, which is a standard format
10289 source file.
10291 In addition to @file{gnat.adc}, one additional file containing configuration
10292 pragmas may be applied to the current compilation using the switch
10293 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10294 contains only configuration pragmas. These configuration pragmas are
10295 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10296 is present and switch @option{-gnatA} is not used).
10298 It is allowed to specify several switches @option{-gnatec}, however only
10299 the last one on the command line will be taken into account.
10301 If you are using project file, a separate mechanism is provided using
10302 project attributes, see @ref{Specifying Configuration Pragmas} for more
10303 details.
10305 @ifset vms
10306 Of special interest to GNAT OpenVMS Alpha is the following
10307 configuration pragma:
10309 @smallexample @c ada
10310 @cartouche
10311 pragma Extend_System (Aux_DEC);
10312 @end cartouche
10313 @end smallexample
10315 @noindent
10316 In the presence of this pragma, GNAT adds to the definition of the
10317 predefined package SYSTEM all the additional types and subprograms that are
10318 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
10319 @end ifset
10321 @node Handling Arbitrary File Naming Conventions Using gnatname
10322 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10323 @cindex Arbitrary File Naming Conventions
10325 @menu
10326 * Arbitrary File Naming Conventions::
10327 * Running gnatname::
10328 * Switches for gnatname::
10329 * Examples of gnatname Usage::
10330 @end menu
10332 @node Arbitrary File Naming Conventions
10333 @section Arbitrary File Naming Conventions
10335 @noindent
10336 The GNAT compiler must be able to know the source file name of a compilation
10337 unit.  When using the standard GNAT default file naming conventions
10338 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10339 does not need additional information.
10341 @noindent
10342 When the source file names do not follow the standard GNAT default file naming
10343 conventions, the GNAT compiler must be given additional information through
10344 a configuration pragmas file (@pxref{Configuration Pragmas})
10345 or a project file.
10346 When the non standard file naming conventions are well-defined,
10347 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10348 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10349 if the file naming conventions are irregular or arbitrary, a number
10350 of pragma @code{Source_File_Name} for individual compilation units
10351 must be defined.
10352 To help maintain the correspondence between compilation unit names and
10353 source file names within the compiler,
10354 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10355 set of files.
10357 @node Running gnatname
10358 @section Running @code{gnatname}
10360 @noindent
10361 The usual form of the @code{gnatname} command is
10363 @smallexample
10364 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10365 @end smallexample
10367 @noindent
10368 All of the arguments are optional. If invoked without any argument,
10369 @code{gnatname} will display its usage.
10371 @noindent
10372 When used with at least one naming pattern, @code{gnatname} will attempt to
10373 find all the compilation units in files that follow at least one of the
10374 naming patterns. To find these compilation units,
10375 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10376 regular files.
10378 @noindent
10379 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10380 Each Naming Pattern is enclosed between double quotes.
10381 A Naming Pattern is a regular expression similar to the wildcard patterns
10382 used in file names by the Unix shells or the DOS prompt.
10384 @noindent
10385 Examples of Naming Patterns are
10387 @smallexample
10388    "*.[12].ada"
10389    "*.ad[sb]*"
10390    "body_*"    "spec_*"
10391 @end smallexample
10393 @noindent
10394 For a more complete description of the syntax of Naming Patterns,
10395 see the second kind of regular expressions described in @file{g-regexp.ads}
10396 (the ``Glob'' regular expressions).
10398 @noindent
10399 When invoked with no switches, @code{gnatname} will create a configuration
10400 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10401 @code{Source_File_Name} for each file that contains a valid Ada unit.
10403 @node Switches for gnatname
10404 @section Switches for @code{gnatname}
10406 @noindent
10407 Switches for @code{gnatname} must precede any specified Naming Pattern.
10409 @noindent
10410 You may specify any of the following switches to @code{gnatname}:
10412 @table @option
10413 @c !sort!
10415 @item ^-c^/CONFIG_FILE=^@file{file}
10416 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10417 Create a configuration pragmas file @file{file} (instead of the default
10418 @file{gnat.adc}).
10419 @ifclear vms
10420 There may be zero, one or more space between @option{-c} and
10421 @file{file}.
10422 @end ifclear
10423 @file{file} may include directory information. @file{file} must be
10424 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10425 When a switch @option{^-c^/CONFIG_FILE^} is
10426 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10428 @item ^-d^/SOURCE_DIRS=^@file{dir}
10429 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10430 Look for source files in directory @file{dir}. There may be zero, one or more
10431 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10432 When a switch @option{^-d^/SOURCE_DIRS^}
10433 is specified, the current working directory will not be searched for source
10434 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10435 or @option{^-D^/DIR_FILES^} switch.
10436 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10437 If @file{dir} is a relative path, it is relative to the directory of
10438 the configuration pragmas file specified with switch
10439 @option{^-c^/CONFIG_FILE^},
10440 or to the directory of the project file specified with switch
10441 @option{^-P^/PROJECT_FILE^} or,
10442 if neither switch @option{^-c^/CONFIG_FILE^}
10443 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10444 current working directory. The directory
10445 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10447 @item ^-D^/DIRS_FILE=^@file{file}
10448 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10449 Look for source files in all directories listed in text file @file{file}.
10450 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10451 and @file{file}.
10452 @file{file} must be an existing, readable text file.
10453 Each non empty line in @file{file} must be a directory.
10454 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10455 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10456 @file{file}.
10458 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10459 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10460 Foreign patterns. Using this switch, it is possible to add sources of languages
10461 other than Ada to the list of sources of a project file.
10462 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10463 For example,
10464 @smallexample
10465 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10466 @end smallexample
10467 @noindent
10468 will look for Ada units in all files with the @file{.ada} extension,
10469 and will add to the list of file for project @file{prj.gpr} the C files
10470 with extension ".^c^C^".
10472 @item ^-h^/HELP^
10473 @cindex @option{^-h^/HELP^} (@code{gnatname})
10474 Output usage (help) information. The output is written to @file{stdout}.
10476 @item ^-P^/PROJECT_FILE=^@file{proj}
10477 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10478 Create or update project file @file{proj}. There may be zero, one or more space
10479 between @option{-P} and @file{proj}. @file{proj} may include directory
10480 information. @file{proj} must be writable.
10481 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10482 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10483 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10485 @item ^-v^/VERBOSE^
10486 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10487 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10488 This includes name of the file written, the name of the directories to search
10489 and, for each file in those directories whose name matches at least one of
10490 the Naming Patterns, an indication of whether the file contains a unit,
10491 and if so the name of the unit.
10493 @item ^-v -v^/VERBOSE /VERBOSE^
10494 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10495 Very Verbose mode. In addition to the output produced in verbose mode,
10496 for each file in the searched directories whose name matches none of
10497 the Naming Patterns, an indication is given that there is no match.
10499 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10500 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10501 Excluded patterns. Using this switch, it is possible to exclude some files
10502 that would match the name patterns. For example,
10503 @smallexample
10504 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10505 @end smallexample
10506 @noindent
10507 will look for Ada units in all files with the @file{.ada} extension,
10508 except those whose names end with @file{_nt.ada}.
10510 @end table
10512 @node Examples of gnatname Usage
10513 @section Examples of @code{gnatname} Usage
10515 @ifset vms
10516 @smallexample
10517 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10518 @end smallexample
10519 @end ifset
10521 @ifclear vms
10522 @smallexample
10523 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10524 @end smallexample
10525 @end ifclear
10527 @noindent
10528 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10529 and be writable. In addition, the directory
10530 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10531 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10533 @ifclear vms
10534 Note the optional spaces after @option{-c} and @option{-d}.
10535 @end ifclear
10537 @smallexample
10538 @ifclear vms
10539 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10540   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10541 @end ifclear
10542 @ifset vms
10543 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10544   /EXCLUDED_PATTERN=*_nt_body.ada
10545   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10546   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10547 @end ifset
10548 @end smallexample
10550 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10551 even in conjunction with one or several switches
10552 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10553 are used in this example.
10555 @c *****************************************
10556 @c * G N A T  P r o j e c t  M a n a g e r *
10557 @c *****************************************
10558 @node GNAT Project Manager
10559 @chapter GNAT Project Manager
10561 @menu
10562 * Introduction::
10563 * Examples of Project Files::
10564 * Project File Syntax::
10565 * Objects and Sources in Project Files::
10566 * Importing Projects::
10567 * Project Extension::
10568 * Project Hierarchy Extension::
10569 * External References in Project Files::
10570 * Packages in Project Files::
10571 * Variables from Imported Projects::
10572 * Naming Schemes::
10573 * Library Projects::
10574 * Stand-alone Library Projects::
10575 * Switches Related to Project Files::
10576 * Tools Supporting Project Files::
10577 * An Extended Example::
10578 * Project File Complete Syntax::
10579 @end menu
10581 @c ****************
10582 @c * Introduction *
10583 @c ****************
10585 @node Introduction
10586 @section Introduction
10588 @noindent
10589 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10590 you to manage complex builds involving a number of source files, directories,
10591 and compilation options for different system configurations. In particular,
10592 project files allow you to specify:
10593 @itemize @bullet
10594 @item
10595 The directory or set of directories containing the source files, and/or the
10596 names of the specific source files themselves
10597 @item
10598 The directory in which the compiler's output
10599 (@file{ALI} files, object files, tree files) is to be placed
10600 @item
10601 The directory in which the executable programs is to be placed
10602 @item
10603 ^Switch^Switch^ settings for any of the project-enabled tools
10604 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10605 @code{gnatfind}); you can apply these settings either globally or to individual
10606 compilation units.
10607 @item
10608 The source files containing the main subprogram(s) to be built
10609 @item
10610 The source programming language(s) (currently Ada and/or C)
10611 @item
10612 Source file naming conventions; you can specify these either globally or for
10613 individual compilation units
10614 @end itemize
10616 @menu
10617 * Project Files::
10618 @end menu
10620 @node Project Files
10621 @subsection Project Files
10623 @noindent
10624 Project files are written in a syntax close to that of Ada, using  familiar
10625 notions such as packages, context clauses, declarations, default values,
10626 assignments, and inheritance. Finally, project files can be built
10627 hierarchically from other project files, simplifying complex system
10628 integration and project reuse.
10630 A @dfn{project} is a specific set of values for various compilation properties.
10631 The settings for a given project are described by means of
10632 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10633 Property values in project files are either strings or lists of strings.
10634 Properties that are not explicitly set receive default values.  A project
10635 file may interrogate the values of @dfn{external variables} (user-defined
10636 command-line switches or environment variables), and it may specify property
10637 settings conditionally, based on the value of such variables.
10639 In simple cases, a project's source files depend only on other source files
10640 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10641 used in
10642 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10643 the Project Manager also allows more sophisticated arrangements,
10644 where the source files in one project depend on source files in other
10645 projects:
10646 @itemize @bullet
10647 @item
10648 One project can @emph{import} other projects containing needed source files.
10649 @item
10650 You can organize GNAT projects in a hierarchy: a @emph{child} project
10651 can extend a @emph{parent} project, inheriting the parent's source files and
10652 optionally overriding any of them with alternative versions
10653 @end itemize
10655 @noindent
10656 More generally, the Project Manager lets you structure large development
10657 efforts into hierarchical subsystems, where build decisions are delegated
10658 to the subsystem level, and thus different compilation environments
10659 (^switch^switch^ settings) used for different subsystems.
10661 The Project Manager is invoked through the
10662 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10663 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10664 @ifclear vms
10665 There may be zero, one or more spaces between @option{-P} and
10666 @option{@emph{projectfile}}.
10667 @end ifclear
10668 If you want to define (on the command line) an external variable that is
10669 queried by the project file, you must use the
10670 @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10671 The Project Manager parses and interprets the project file, and drives the
10672 invoked tool based on the project settings.
10674 The Project Manager supports a wide range of development strategies,
10675 for systems of all sizes.  Here are some typical practices that are
10676 easily handled:
10677 @itemize @bullet
10678 @item
10679 Using a common set of source files, but generating object files in different
10680 directories via different ^switch^switch^ settings
10681 @item
10682 Using a mostly-shared set of source files, but with different versions of
10683 some unit or units
10684 @end itemize
10686 @noindent
10687 The destination of an executable can be controlled inside a project file
10688 using the @option{^-o^-o^}
10689 ^switch^switch^.
10690 In the absence of such a ^switch^switch^ either inside
10691 the project file or on the command line, any executable files generated by
10692 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10693 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10694 in the object directory of the project.
10696 You can use project files to achieve some of the effects of a source
10697 versioning system (for example, defining separate projects for
10698 the different sets of sources that comprise different releases) but the
10699 Project Manager is independent of any source configuration management tools
10700 that might be used by the developers.
10702 The next section introduces the main features of GNAT's project facility
10703 through a sequence of examples; subsequent sections will present the syntax
10704 and semantics in more detail. A more formal description of the project
10705 facility appears in the GNAT Reference Manual.
10707 @c *****************************
10708 @c * Examples of Project Files *
10709 @c *****************************
10711 @node Examples of Project Files
10712 @section Examples of Project Files
10713 @noindent
10714 This section illustrates some of the typical uses of project files and
10715 explains their basic structure and behavior.
10717 @menu
10718 * Common Sources with Different ^Switches^Switches^ and Directories::
10719 * Using External Variables::
10720 * Importing Other Projects::
10721 * Extending a Project::
10722 @end menu
10724 @node Common Sources with Different ^Switches^Switches^ and Directories
10725 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10727 @menu
10728 * Source Files::
10729 * Specifying the Object Directory::
10730 * Specifying the Exec Directory::
10731 * Project File Packages::
10732 * Specifying ^Switch^Switch^ Settings::
10733 * Main Subprograms::
10734 * Executable File Names::
10735 * Source File Naming Conventions::
10736 * Source Language(s)::
10737 @end menu
10739 @noindent
10740 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10741 @file{proc.adb} are in the @file{/common} directory.  The file
10742 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10743 package @code{Pack}.  We want to compile these source files under two sets
10744 of ^switches^switches^:
10745 @itemize @bullet
10746 @item
10747 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10748 and the @option{^-gnata^-gnata^},
10749 @option{^-gnato^-gnato^},
10750 and @option{^-gnatE^-gnatE^} switches to the
10751 compiler; the compiler's output is to appear in @file{/common/debug}
10752 @item
10753 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10754 to the compiler; the compiler's output is to appear in @file{/common/release}
10755 @end itemize
10757 @noindent
10758 The GNAT project files shown below, respectively @file{debug.gpr} and
10759 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10761 Schematically:
10762 @smallexample
10763 @group
10764 ^/common^[COMMON]^
10765   debug.gpr
10766   release.gpr
10767   pack.ads
10768   pack.adb
10769   proc.adb
10770 @end group
10771 @group
10772 ^/common/debug^[COMMON.DEBUG]^
10773   proc.ali, proc.o
10774   pack.ali, pack.o
10775 @end group
10776 @group
10777 ^/common/release^[COMMON.RELEASE]^
10778   proc.ali, proc.o
10779   pack.ali, pack.o
10780 @end group
10781 @end smallexample
10782 Here are the corresponding project files:
10784 @smallexample @c projectfile
10785 @group
10786 project Debug is
10787   for Object_Dir use "debug";
10788   for Main use ("proc");
10790   package Builder is
10791     for ^Default_Switches^Default_Switches^ ("Ada")
10792         use ("^-g^-g^");
10793     for Executable ("proc.adb") use "proc1";
10794   end Builder;
10795 @end group
10797 @group
10798   package Compiler is
10799     for ^Default_Switches^Default_Switches^ ("Ada")
10800        use ("-fstack-check",
10801             "^-gnata^-gnata^",
10802             "^-gnato^-gnato^",
10803             "^-gnatE^-gnatE^");
10804   end Compiler;
10805 end Debug;
10806 @end group
10807 @end smallexample
10809 @smallexample @c projectfile
10810 @group
10811 project Release is
10812   for Object_Dir use "release";
10813   for Exec_Dir use ".";
10814   for Main use ("proc");
10816   package Compiler is
10817     for ^Default_Switches^Default_Switches^ ("Ada")
10818         use ("^-O2^-O2^");
10819   end Compiler;
10820 end Release;
10821 @end group
10822 @end smallexample
10824 @noindent
10825 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10826 insensitive), and analogously the project defined by @file{release.gpr} is
10827 @code{"Release"}.  For consistency the file should have the same name as the
10828 project, and the project file's extension should be @code{"gpr"}. These
10829 conventions are not required, but a warning is issued if they are not followed.
10831 If the current directory is @file{^/temp^[TEMP]^}, then the command
10832 @smallexample
10833 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10834 @end smallexample
10836 @noindent
10837 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10838 as well as the @code{^proc1^PROC1.EXE^} executable,
10839 using the ^switch^switch^ settings defined in the project file.
10841 Likewise, the command
10842 @smallexample
10843 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10844 @end smallexample
10846 @noindent
10847 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10848 and the @code{^proc^PROC.EXE^}
10849 executable in @file{^/common^[COMMON]^},
10850 using the ^switch^switch^ settings from the project file.
10852 @node Source Files
10853 @unnumberedsubsubsec Source Files
10855 @noindent
10856 If a project file does not explicitly specify a set of source directories or
10857 a set of source files, then by default the project's source files are the
10858 Ada source files in the project file directory.  Thus @file{pack.ads},
10859 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10861 @node Specifying the Object Directory
10862 @unnumberedsubsubsec Specifying the Object Directory
10864 @noindent
10865 Several project properties are modeled by Ada-style @emph{attributes};
10866 a property is defined by supplying the equivalent of an Ada attribute
10867 definition clause in the project file.
10868 A project's object directory is another such a property; the corresponding
10869 attribute is @code{Object_Dir}, and its value is also a string expression,
10870 specified either as absolute or relative. In the later case,
10871 it is relative to the project file directory. Thus the compiler's
10872 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10873 (for the @code{Debug} project)
10874 and to @file{^/common/release^[COMMON.RELEASE]^}
10875 (for the @code{Release} project).
10876 If @code{Object_Dir} is not specified, then the default is the project file
10877 directory itself.
10879 @node Specifying the Exec Directory
10880 @unnumberedsubsubsec Specifying the Exec Directory
10882 @noindent
10883 A project's exec directory is another property; the corresponding
10884 attribute is @code{Exec_Dir}, and its value is also a string expression,
10885 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10886 then the default is the object directory (which may also be the project file
10887 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10888 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10889 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10890 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10892 @node Project File Packages
10893 @unnumberedsubsubsec Project File Packages
10895 @noindent
10896 A GNAT tool that is integrated with the Project Manager is modeled by a
10897 corresponding package in the project file. In the example above,
10898 The @code{Debug} project defines the packages @code{Builder}
10899 (for @command{gnatmake}) and @code{Compiler};
10900 the @code{Release} project defines only the @code{Compiler} package.
10902 The Ada-like package syntax is not to be taken literally.  Although packages in
10903 project files bear a surface resemblance to packages in Ada source code, the
10904 notation is simply a way to convey a grouping of properties for a named
10905 entity.  Indeed, the package names permitted in project files are restricted
10906 to a predefined set, corresponding to the project-aware tools, and the contents
10907 of packages are limited to a small set of constructs.
10908 The packages in the example above contain attribute definitions.
10910 @node Specifying ^Switch^Switch^ Settings
10911 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10913 @noindent
10914 ^Switch^Switch^ settings for a project-aware tool can be specified through
10915 attributes in the package that corresponds to the tool.
10916 The example above illustrates one of the relevant attributes,
10917 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10918 in both project files.
10919 Unlike simple attributes like @code{Source_Dirs},
10920 @code{^Default_Switches^Default_Switches^} is
10921 known as an @emph{associative array}.  When you define this attribute, you must
10922 supply an ``index'' (a literal string), and the effect of the attribute
10923 definition is to set the value of the array at the specified index.
10924 For the @code{^Default_Switches^Default_Switches^} attribute,
10925 the index is a programming language (in our case, Ada),
10926 and the value specified (after @code{use}) must be a list
10927 of string expressions.
10929 The attributes permitted in project files are restricted to a predefined set.
10930 Some may appear at project level, others in packages.
10931 For any attribute that is an associative array, the index must always be a
10932 literal string, but the restrictions on this string (e.g., a file name or a
10933 language name) depend on the individual attribute.
10934 Also depending on the attribute, its specified value will need to be either a
10935 string or a string list.
10937 In the @code{Debug} project, we set the switches for two tools,
10938 @command{gnatmake} and the compiler, and thus we include the two corresponding
10939 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10940 attribute with index @code{"Ada"}.
10941 Note that the package corresponding to
10942 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10943 similar, but only includes the @code{Compiler} package.
10945 In project @code{Debug} above, the ^switches^switches^ starting with
10946 @option{-gnat} that are specified in package @code{Compiler}
10947 could have been placed in package @code{Builder}, since @command{gnatmake}
10948 transmits all such ^switches^switches^ to the compiler.
10950 @node Main Subprograms
10951 @unnumberedsubsubsec Main Subprograms
10953 @noindent
10954 One of the specifiable properties of a project is a list of files that contain
10955 main subprograms.  This property is captured in the @code{Main} attribute,
10956 whose value is a list of strings.  If a project defines the @code{Main}
10957 attribute, it is not necessary to identify the main subprogram(s) when
10958 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
10960 @node Executable File Names
10961 @unnumberedsubsubsec Executable File Names
10963 @noindent
10964 By default, the executable file name corresponding to a main source is
10965 deduced from the main source file name. Through the attributes
10966 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10967 it is possible to change this default.
10968 In project @code{Debug} above, the executable file name
10969 for main source @file{^proc.adb^PROC.ADB^} is
10970 @file{^proc1^PROC1.EXE^}.
10971 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10972 of the executable files, when no attribute @code{Executable} applies:
10973 its value replace the platform-specific executable suffix.
10974 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10975 specify a non default executable file name when several mains are built at once
10976 in a single @command{gnatmake} command.
10978 @node Source File Naming Conventions
10979 @unnumberedsubsubsec Source File Naming Conventions
10981 @noindent
10982 Since the project files above do not specify any source file naming
10983 conventions, the GNAT defaults are used.  The mechanism for defining source
10984 file naming conventions -- a package named @code{Naming} --
10985 is described below (@pxref{Naming Schemes}).
10987 @node Source Language(s)
10988 @unnumberedsubsubsec Source Language(s)
10990 @noindent
10991 Since the project files do not specify a @code{Languages} attribute, by
10992 default the GNAT tools assume that the language of the project file is Ada.
10993 More generally, a project can comprise source files
10994 in Ada, C, and/or other languages.
10996 @node Using External Variables
10997 @subsection Using External Variables
10999 @noindent
11000 Instead of supplying different project files for debug and release, we can
11001 define a single project file that queries an external variable (set either
11002 on the command line or via an ^environment variable^logical name^) in order to
11003 conditionally define the appropriate settings.  Again, assume that the
11004 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
11005 located in directory @file{^/common^[COMMON]^}.  The following project file,
11006 @file{build.gpr}, queries the external variable named @code{STYLE} and
11007 defines an object directory and ^switch^switch^ settings based on whether
11008 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
11009 the default is @code{"deb"}.
11011 @smallexample @c projectfile
11012 @group
11013 project Build is
11014   for Main use ("proc");
11016   type Style_Type is ("deb", "rel");
11017   Style : Style_Type := external ("STYLE", "deb");
11019   case Style is
11020     when "deb" =>
11021       for Object_Dir use "debug";
11023     when "rel" =>
11024       for Object_Dir use "release";
11025       for Exec_Dir use ".";
11026   end case;
11027 @end group
11029 @group
11030   package Builder is
11032     case Style is
11033       when "deb" =>
11034         for ^Default_Switches^Default_Switches^ ("Ada")
11035             use ("^-g^-g^");
11036         for Executable ("proc") use "proc1";
11037       when others =>
11038         null;
11039     end case;
11041   end Builder;
11042 @end group
11044 @group
11045   package Compiler is
11047     case Style is
11048       when "deb" =>
11049         for ^Default_Switches^Default_Switches^ ("Ada")
11050             use ("^-gnata^-gnata^",
11051                  "^-gnato^-gnato^",
11052                  "^-gnatE^-gnatE^");
11054       when "rel" =>
11055         for ^Default_Switches^Default_Switches^ ("Ada")
11056             use ("^-O2^-O2^");
11057     end case;
11059   end Compiler;
11061 end Build;
11062 @end group
11063 @end smallexample
11065 @noindent
11066 @code{Style_Type} is an example of a @emph{string type}, which is the project
11067 file analog of an Ada enumeration type but whose components are string literals
11068 rather than identifiers.  @code{Style} is declared as a variable of this type.
11070 The form @code{external("STYLE", "deb")} is known as an
11071 @emph{external reference}; its first argument is the name of an
11072 @emph{external variable}, and the second argument is a default value to be
11073 used if the external variable doesn't exist.  You can define an external
11074 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
11075 or you can use ^an environment variable^a logical name^
11076 as an external variable.
11078 Each @code{case} construct is expanded by the Project Manager based on the
11079 value of @code{Style}. Thus the command
11080 @ifclear vms
11081 @smallexample
11082 gnatmake -P/common/build.gpr -XSTYLE=deb
11083 @end smallexample
11084 @end ifclear
11086 @ifset vms
11087 @smallexample
11088 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
11089 @end smallexample
11090 @end ifset
11092 @noindent
11093 is equivalent to the @command{gnatmake} invocation using the project file
11094 @file{debug.gpr} in the earlier example.  So is the command
11095 @smallexample
11096 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
11097 @end smallexample
11099 @noindent
11100 since @code{"deb"} is the default for @code{STYLE}.
11102 Analogously,
11104 @ifclear vms
11105 @smallexample
11106 gnatmake -P/common/build.gpr -XSTYLE=rel
11107 @end smallexample
11108 @end ifclear
11110 @ifset vms
11111 @smallexample
11112 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
11113 @end smallexample
11114 @end ifset
11116 @noindent
11117 is equivalent to the @command{gnatmake} invocation using the project file
11118 @file{release.gpr} in the earlier example.
11120 @node Importing Other Projects
11121 @subsection Importing Other Projects
11122 @cindex @code{ADA_PROJECT_PATH}
11124 @noindent
11125 A compilation unit in a source file in one project may depend on compilation
11126 units in source files in other projects.  To compile this unit under
11127 control of a project file, the
11128 dependent project must @emph{import} the projects containing the needed source
11129 files.
11130 This effect is obtained using syntax similar to an Ada @code{with} clause,
11131 but where @code{with}ed entities are strings that denote project files.
11133 As an example, suppose that the two projects @code{GUI_Proj} and
11134 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
11135 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
11136 and @file{^/comm^[COMM]^}, respectively.
11137 Suppose that the source files for @code{GUI_Proj} are
11138 @file{gui.ads} and @file{gui.adb}, and that the source files for
11139 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
11140 files is located in its respective project file directory.  Schematically:
11142 @smallexample
11143 @group
11144 ^/gui^[GUI]^
11145   gui_proj.gpr
11146   gui.ads
11147   gui.adb
11148 @end group
11150 @group
11151 ^/comm^[COMM]^
11152   comm_proj.gpr
11153   comm.ads
11154   comm.adb
11155 @end group
11156 @end smallexample
11158 @noindent
11159 We want to develop an application in directory @file{^/app^[APP]^} that
11160 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
11161 the corresponding project files (e.g. the ^switch^switch^ settings
11162 and object directory).
11163 Skeletal code for a main procedure might be something like the following:
11165 @smallexample @c ada
11166 @group
11167 with GUI, Comm;
11168 procedure App_Main is
11169    ...
11170 begin
11171    ...
11172 end App_Main;
11173 @end group
11174 @end smallexample
11176 @noindent
11177 Here is a project file, @file{app_proj.gpr}, that achieves the desired
11178 effect:
11180 @smallexample @c projectfile
11181 @group
11182 with "/gui/gui_proj", "/comm/comm_proj";
11183 project App_Proj is
11184    for Main use ("app_main");
11185 end App_Proj;
11186 @end group
11187 @end smallexample
11189 @noindent
11190 Building an executable is achieved through the command:
11191 @smallexample
11192 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
11193 @end smallexample
11194 @noindent
11195 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
11196 in the directory where @file{app_proj.gpr} resides.
11198 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
11199 (as illustrated above) the @code{with} clause can omit the extension.
11201 Our example specified an absolute path for each imported project file.
11202 Alternatively, the directory name of an imported object can be omitted
11203 if either
11204 @itemize @bullet
11205 @item
11206 The imported project file is in the same directory as the importing project
11207 file, or
11208 @item
11209 You have defined ^an environment variable^a logical name^
11210 that includes the directory containing
11211 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
11212 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
11213 directory names separated by colons (semicolons on Windows).
11214 @end itemize
11216 @noindent
11217 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
11218 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
11219 as follows:
11221 @smallexample @c projectfile
11222 @group
11223 with "gui_proj", "comm_proj";
11224 project App_Proj is
11225    for Main use ("app_main");
11226 end App_Proj;
11227 @end group
11228 @end smallexample
11230 @noindent
11231 Importing other projects can create ambiguities.
11232 For example, the same unit might be present in different imported projects, or
11233 it might be present in both the importing project and in an imported project.
11234 Both of these conditions are errors.  Note that in the current version of
11235 the Project Manager, it is illegal to have an ambiguous unit even if the
11236 unit is never referenced by the importing project.  This restriction may be
11237 relaxed in a future release.
11239 @node Extending a Project
11240 @subsection Extending a Project
11242 @noindent
11243 In large software systems it is common to have multiple
11244 implementations of a common interface; in Ada terms, multiple versions of a
11245 package body for the same specification.  For example, one implementation
11246 might be safe for use in tasking programs, while another might only be used
11247 in sequential applications.  This can be modeled in GNAT using the concept
11248 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11249 another project (the ``parent'') then by default all source files of the
11250 parent project are inherited by the child, but the child project can
11251 override any of the parent's source files with new versions, and can also
11252 add new files.  This facility is the project analog of a type extension in
11253 Object-Oriented Programming.  Project hierarchies are permitted (a child
11254 project may be the parent of yet another project), and a project that
11255 inherits one project can also import other projects.
11257 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11258 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11259 @file{pack.adb}, and @file{proc.adb}:
11261 @smallexample
11262 @group
11263 ^/seq^[SEQ]^
11264   pack.ads
11265   pack.adb
11266   proc.adb
11267   seq_proj.gpr
11268 @end group
11269 @end smallexample
11271 @noindent
11272 Note that the project file can simply be empty (that is, no attribute or
11273 package is defined):
11275 @smallexample @c projectfile
11276 @group
11277 project Seq_Proj is
11278 end Seq_Proj;
11279 @end group
11280 @end smallexample
11282 @noindent
11283 implying that its source files are all the Ada source files in the project
11284 directory.
11286 Suppose we want to supply an alternate version of @file{pack.adb}, in
11287 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11288 @file{pack.ads} and @file{proc.adb}.  We can define a project
11289 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11291 @smallexample
11292 @group
11293 ^/tasking^[TASKING]^
11294   pack.adb
11295   tasking_proj.gpr
11296 @end group
11298 @group
11299 project Tasking_Proj extends "/seq/seq_proj" is
11300 end Tasking_Proj;
11301 @end group
11302 @end smallexample
11304 @noindent
11305 The version of @file{pack.adb} used in a build depends on which project file
11306 is specified.
11308 Note that we could have obtained the desired behavior using project import
11309 rather than project inheritance; a @code{base} project would contain the
11310 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11311 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11312 would import @code{base} and add a different version of @file{pack.adb}.  The
11313 choice depends on whether other sources in the original project need to be
11314 overridden.  If they do, then project extension is necessary, otherwise,
11315 importing is sufficient.
11317 @noindent
11318 In a project file that extends another project file, it is possible to
11319 indicate that an inherited source is not part of the sources of the extending
11320 project. This is necessary sometimes when a package spec has been overloaded
11321 and no longer requires a body: in this case, it is necessary to indicate that
11322 the inherited body is not part of the sources of the project, otherwise there
11323 will be a compilation error when compiling the spec.
11325 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11326 Its value is a string list: a list of file names.
11328 @smallexample @c @projectfile
11329 project B extends "a" is
11330    for Source_Files use ("pkg.ads");
11331    --  New spec of Pkg does not need a completion
11332    for Locally_Removed_Files use ("pkg.adb");
11333 end B;
11334 @end smallexample
11336 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11337 is still needed: if it is possible to build using @command{gnatmake} when such
11338 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11339 it is possible to remove the source completely from a system that includes
11340 project P.
11342 @c ***********************
11343 @c * Project File Syntax *
11344 @c ***********************
11346 @node Project File Syntax
11347 @section Project File Syntax
11349 @menu
11350 * Basic Syntax::
11351 * Packages::
11352 * Expressions::
11353 * String Types::
11354 * Variables::
11355 * Attributes::
11356 * Associative Array Attributes::
11357 * case Constructions::
11358 @end menu
11360 @noindent
11361 This section describes the structure of project files.
11363 A project may be an @emph{independent project}, entirely defined by a single
11364 project file. Any Ada source file in an independent project depends only
11365 on the predefined library and other Ada source files in the same project.
11367 @noindent
11368 A project may also @dfn{depend on} other projects, in either or both of
11369 the following ways:
11370 @itemize @bullet
11371 @item It may import any number of projects
11372 @item It may extend at most one other project
11373 @end itemize
11375 @noindent
11376 The dependence relation is a directed acyclic graph (the subgraph reflecting
11377 the ``extends'' relation is a tree).
11379 A project's @dfn{immediate sources} are the source files directly defined by
11380 that project, either implicitly by residing in the project file's directory,
11381 or explicitly through any of the source-related attributes described below.
11382 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11383 of @var{proj} together with the immediate sources (unless overridden) of any
11384 project on which @var{proj} depends (either directly or indirectly).
11386 @node Basic Syntax
11387 @subsection Basic Syntax
11389 @noindent
11390 As seen in the earlier examples, project files have an Ada-like syntax.
11391 The minimal project file is:
11392 @smallexample @c projectfile
11393 @group
11394 project Empty is
11396 end Empty;
11397 @end group
11398 @end smallexample
11400 @noindent
11401 The identifier @code{Empty} is the name of the project.
11402 This project name must be present after the reserved
11403 word @code{end} at the end of the project file, followed by a semi-colon.
11405 Any name in a project file, such as the project name or a variable name,
11406 has the same syntax as an Ada identifier.
11408 The reserved words of project files are the Ada reserved words plus
11409 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11410 reserved words currently used in project file syntax are:
11412 @itemize @bullet
11413 @item
11414 @code{case}
11415 @item
11416 @code{end}
11417 @item
11418 @code{for}
11419 @item
11420 @code{is}
11421 @item
11422 @code{others}
11423 @item
11424 @code{package}
11425 @item
11426 @code{renames}
11427 @item
11428 @code{type}
11429 @item
11430 @code{use}
11431 @item
11432 @code{when}
11433 @item
11434 @code{with}
11435 @end itemize
11437 @noindent
11438 Comments in project files have the same syntax as in Ada, two consecutives
11439 hyphens through the end of the line.
11441 @node Packages
11442 @subsection Packages
11444 @noindent
11445 A project file may contain @emph{packages}. The name of a package must be one
11446 of the identifiers from the following list. A package
11447 with a given name may only appear once in a project file. Package names are
11448 case insensitive. The following package names are legal:
11450 @itemize @bullet
11451 @item
11452 @code{Naming}
11453 @item
11454 @code{Builder}
11455 @item
11456 @code{Compiler}
11457 @item
11458 @code{Binder}
11459 @item
11460 @code{Linker}
11461 @item
11462 @code{Finder}
11463 @item
11464 @code{Cross_Reference}
11465 @item
11466 @code{Eliminate}
11467 @item
11468 @code{Pretty_Printer}
11469 @item
11470 @code{Metrics}
11471 @item
11472 @code{gnatls}
11473 @item
11474 @code{gnatstub}
11475 @item
11476 @code{IDE}
11477 @item
11478 @code{Language_Processing}
11479 @end itemize
11481 @noindent
11482 In its simplest form, a package may be empty:
11484 @smallexample @c projectfile
11485 @group
11486 project Simple is
11487   package Builder is
11488   end Builder;
11489 end Simple;
11490 @end group
11491 @end smallexample
11493 @noindent
11494 A package may contain @emph{attribute declarations},
11495 @emph{variable declarations} and @emph{case constructions}, as will be
11496 described below.
11498 When there is ambiguity between a project name and a package name,
11499 the name always designates the project. To avoid possible confusion, it is
11500 always a good idea to avoid naming a project with one of the
11501 names allowed for packages or any name that starts with @code{gnat}.
11503 @node Expressions
11504 @subsection Expressions
11506 @noindent
11507 An @emph{expression} is either a @emph{string expression} or a
11508 @emph{string list expression}.
11510 A @emph{string expression} is either a @emph{simple string expression} or a
11511 @emph{compound string expression}.
11513 A @emph{simple string expression} is one of the following:
11514 @itemize @bullet
11515 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11516 @item A string-valued variable reference (@pxref{Variables})
11517 @item A string-valued attribute reference (@pxref{Attributes})
11518 @item An external reference (@pxref{External References in Project Files})
11519 @end itemize
11521 @noindent
11522 A @emph{compound string expression} is a concatenation of string expressions,
11523 using the operator @code{"&"}
11524 @smallexample
11525        Path & "/" & File_Name & ".ads"
11526 @end smallexample
11528 @noindent
11529 A @emph{string list expression} is either a
11530 @emph{simple string list expression} or a
11531 @emph{compound string list expression}.
11533 A @emph{simple string list expression} is one of the following:
11534 @itemize @bullet
11535 @item A parenthesized list of zero or more string expressions,
11536 separated by commas
11537 @smallexample
11538    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11539    Empty_List := ();
11540 @end smallexample
11541 @item A string list-valued variable reference
11542 @item A string list-valued attribute reference
11543 @end itemize
11545 @noindent
11546 A @emph{compound string list expression} is the concatenation (using
11547 @code{"&"}) of a simple string list expression and an expression.  Note that
11548 each term in a compound string list expression, except the first, may be
11549 either a string expression or a string list expression.
11551 @smallexample @c projectfile
11552 @group
11553    File_Name_List := () & File_Name; --  One string in this list
11554    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11555    --  Two strings
11556    Big_List := File_Name_List & Extended_File_Name_List;
11557    --  Concatenation of two string lists: three strings
11558    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11559    --  Illegal: must start with a string list
11560 @end group
11561 @end smallexample
11563 @node String Types
11564 @subsection String Types
11566 @noindent
11567 A @emph{string type declaration} introduces a discrete set of string literals.
11568 If a string variable is declared to have this type, its value
11569 is restricted to the given set of literals.
11571 Here is an example of a string type declaration:
11573 @smallexample @c projectfile
11574    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11575 @end smallexample
11577 @noindent
11578 Variables of a string type are called @emph{typed variables}; all other
11579 variables are called @emph{untyped variables}. Typed variables are
11580 particularly useful in @code{case} constructions, to support conditional
11581 attribute declarations.
11582 (@pxref{case Constructions}).
11584 The string literals in the list are case sensitive and must all be different.
11585 They may include any graphic characters allowed in Ada, including spaces.
11587 A string type may only be declared at the project level, not inside a package.
11589 A string type may be referenced by its name if it has been declared in the same
11590 project file, or by an expanded name whose prefix is the name of the project
11591 in which it is declared.
11593 @node Variables
11594 @subsection Variables
11596 @noindent
11597 A variable may be declared at the project file level, or within a package.
11598 Here are some examples of variable declarations:
11600 @smallexample @c projectfile
11601 @group
11602    This_OS : OS := external ("OS"); --  a typed variable declaration
11603    That_OS := "GNU/Linux";          --  an untyped variable declaration
11604 @end group
11605 @end smallexample
11607 @noindent
11608 The syntax of a @emph{typed variable declaration} is identical to the Ada
11609 syntax for an object declaration. By contrast, the syntax of an untyped
11610 variable declaration is identical to an Ada assignment statement. In fact,
11611 variable declarations in project files have some of the characteristics of
11612 an assignment, in that successive declarations for the same variable are
11613 allowed. Untyped variable declarations do establish the expected kind of the
11614 variable (string or string list), and successive declarations for it must
11615 respect the initial kind.
11617 @noindent
11618 A string variable declaration (typed or untyped) declares a variable
11619 whose value is a string. This variable may be used as a string expression.
11620 @smallexample @c projectfile
11621    File_Name       := "readme.txt";
11622    Saved_File_Name := File_Name & ".saved";
11623 @end smallexample
11625 @noindent
11626 A string list variable declaration declares a variable whose value is a list
11627 of strings. The list may contain any number (zero or more) of strings.
11629 @smallexample @c projectfile
11630    Empty_List := ();
11631    List_With_One_Element := ("^-gnaty^-gnaty^");
11632    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11633    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11634                  "pack2.ada", "util_.ada", "util.ada");
11635 @end smallexample
11637 @noindent
11638 The same typed variable may not be declared more than once at project level,
11639 and it may not be declared more than once in any package; it is in effect
11640 a constant.
11642 The same untyped variable may be declared several times. Declarations are
11643 elaborated in the order in which they appear, so  the new value replaces
11644 the old one, and any subsequent reference to the variable uses the new value.
11645 However, as noted above, if a variable has been declared as a string, all
11646 subsequent
11647 declarations must give it a string value. Similarly, if a variable has
11648 been declared as a string list, all subsequent declarations
11649 must give it a string list value.
11651 A @emph{variable reference} may take several forms:
11653 @itemize @bullet
11654 @item The simple variable name, for a variable in the current package (if any)
11655 or in the current project
11656 @item An expanded name, whose prefix is a context name.
11657 @end itemize
11659 @noindent
11660 A @emph{context} may be one of the following:
11662 @itemize @bullet
11663 @item The name of an existing package in the current project
11664 @item The name of an imported project of the current project
11665 @item The name of an ancestor project (i.e., a project extended by the current
11666 project, either directly or indirectly)
11667 @item An expanded name whose prefix is an imported/parent project name, and
11668 whose selector is a package name in that project.
11669 @end itemize
11671 @noindent
11672 A variable reference may be used in an expression.
11674 @node Attributes
11675 @subsection Attributes
11677 @noindent
11678 A project (and its packages) may have @emph{attributes} that define
11679 the project's properties.  Some attributes have values that are strings;
11680 others have values that are string lists.
11682 There are two categories of attributes: @emph{simple attributes}
11683 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
11685 Legal project attribute names, and attribute names for each legal package are
11686 listed below. Attributes names are case-insensitive.
11688 The following attributes are defined on projects (all are simple attributes):
11690 @multitable @columnfractions .4 .3
11691 @item @emph{Attribute Name}
11692 @tab @emph{Value}
11693 @item @code{Source_Files}
11694 @tab string list
11695 @item @code{Source_Dirs}
11696 @tab string list
11697 @item @code{Source_List_File}
11698 @tab string
11699 @item @code{Object_Dir}
11700 @tab string
11701 @item @code{Exec_Dir}
11702 @tab string
11703 @item @code{Locally_Removed_Files}
11704 @tab string list
11705 @item @code{Languages}
11706 @tab string list
11707 @item @code{Main}
11708 @tab string list
11709 @item @code{Library_Dir}
11710 @tab string
11711 @item @code{Library_Name}
11712 @tab string
11713 @item @code{Library_Kind}
11714 @tab string
11715 @item @code{Library_Version}
11716 @tab string
11717 @item @code{Library_Interface}
11718 @tab string
11719 @item @code{Library_Auto_Init}
11720 @tab string
11721 @item @code{Library_Options}
11722 @tab string list
11723 @item @code{Library_Src_Dir}
11724 @tab string
11725 @item @code{Library_ALI_Dir}
11726 @tab string
11727 @item @code{Library_GCC}
11728 @tab string
11729 @item @code{Library_Symbol_File}
11730 @tab string
11731 @item @code{Library_Symbol_Policy}
11732 @tab string
11733 @item @code{Library_Reference_Symbol_File}
11734 @tab string
11735 @item @code{Externally_Built}
11736 @tab string
11737 @end multitable
11739 @noindent
11740 The following attributes are defined for package  @code{Naming}
11741 (@pxref{Naming Schemes}):
11743 @multitable @columnfractions .4 .2 .2 .2
11744 @item Attribute Name @tab Category @tab Index @tab Value
11745 @item @code{Spec_Suffix}
11746 @tab associative array
11747 @tab language name
11748 @tab string
11749 @item @code{Body_Suffix}
11750 @tab associative array
11751 @tab language name
11752 @tab string
11753 @item @code{Separate_Suffix}
11754 @tab simple attribute
11755 @tab n/a
11756 @tab string
11757 @item @code{Casing}
11758 @tab simple attribute
11759 @tab n/a
11760 @tab string
11761 @item @code{Dot_Replacement}
11762 @tab simple attribute
11763 @tab n/a
11764 @tab string
11765 @item @code{Spec}
11766 @tab associative array
11767 @tab Ada unit name
11768 @tab string
11769 @item @code{Body}
11770 @tab associative array
11771 @tab Ada unit name
11772 @tab string
11773 @item @code{Specification_Exceptions}
11774 @tab associative array
11775 @tab language name
11776 @tab string list
11777 @item @code{Implementation_Exceptions}
11778 @tab associative array
11779 @tab language name
11780 @tab string list
11781 @end multitable
11783 @noindent
11784 The following attributes are defined for packages @code{Builder},
11785 @code{Compiler}, @code{Binder},
11786 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11787 (@pxref{^Switches^Switches^ and Project Files}).
11789 @multitable @columnfractions .4 .2 .2 .2
11790 @item Attribute Name @tab Category @tab Index @tab Value
11791 @item @code{^Default_Switches^Default_Switches^}
11792 @tab associative array
11793 @tab language name
11794 @tab string list
11795 @item @code{^Switches^Switches^}
11796 @tab associative array
11797 @tab file name
11798 @tab string list
11799 @end multitable
11801 @noindent
11802 In addition, package @code{Compiler} has a single string attribute
11803 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11804 string attribute @code{Global_Configuration_Pragmas}.
11806 @noindent
11807 Each simple attribute has a default value: the empty string (for string-valued
11808 attributes) and the empty list (for string list-valued attributes).
11810 An attribute declaration defines a new value for an attribute.
11812 Examples of simple attribute declarations:
11814 @smallexample @c projectfile
11815    for Object_Dir use "objects";
11816    for Source_Dirs use ("units", "test/drivers");
11817 @end smallexample
11819 @noindent
11820 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11821 attribute definition clause in Ada.
11823 Attributes references may be appear in expressions.
11824 The general form for such a reference is @code{<entity>'<attribute>}:
11825 Associative array attributes are functions. Associative
11826 array attribute references must have an argument that is a string literal.
11828 Examples are:
11830 @smallexample @c projectfile
11831   project'Object_Dir
11832   Naming'Dot_Replacement
11833   Imported_Project'Source_Dirs
11834   Imported_Project.Naming'Casing
11835   Builder'^Default_Switches^Default_Switches^("Ada")
11836 @end smallexample
11838 @noindent
11839 The prefix of an attribute may be:
11840 @itemize @bullet
11841 @item @code{project} for an attribute of the current project
11842 @item The name of an existing package of the current project
11843 @item The name of an imported project
11844 @item The name of a parent project that is extended by the current project
11845 @item An expanded name whose prefix is imported/parent project name,
11846       and whose selector is a package name
11847 @end itemize
11849 @noindent
11850 Example:
11851 @smallexample @c projectfile
11852 @group
11853    project Prj is
11854      for Source_Dirs use project'Source_Dirs & "units";
11855      for Source_Dirs use project'Source_Dirs & "test/drivers"
11856    end Prj;
11857 @end group
11858 @end smallexample
11860 @noindent
11861 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11862 has the default value: an empty string list. After this declaration,
11863 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11864 After the second attribute declaration @code{Source_Dirs} is a string list of
11865 two elements: @code{"units"} and @code{"test/drivers"}.
11867 Note: this example is for illustration only. In practice,
11868 the project file would contain only one attribute declaration:
11870 @smallexample @c projectfile
11871    for Source_Dirs use ("units", "test/drivers");
11872 @end smallexample
11874 @node Associative Array Attributes
11875 @subsection Associative Array Attributes
11877 @noindent
11878 Some attributes are defined as @emph{associative arrays}. An associative
11879 array may be regarded as a function that takes a string as a parameter
11880 and delivers a string or string list value as its result.
11882 Here are some examples of single associative array attribute associations:
11884 @smallexample @c projectfile
11885    for Body ("main") use "Main.ada";
11886    for ^Switches^Switches^ ("main.ada")
11887        use ("^-v^-v^",
11888             "^-gnatv^-gnatv^");
11889    for ^Switches^Switches^ ("main.ada")
11890             use Builder'^Switches^Switches^ ("main.ada")
11891               & "^-g^-g^";
11892 @end smallexample
11894 @noindent
11895 Like untyped variables and simple attributes, associative array attributes
11896 may be declared several times. Each declaration supplies a new value for the
11897 attribute, and replaces the previous setting.
11899 @noindent
11900 An associative array attribute may be declared as a full associative array
11901 declaration, with the value of the same attribute in an imported or extended
11902 project.
11904 @smallexample @c projectfile
11905    package Builder is
11906       for Default_Switches use Default.Builder'Default_Switches;
11907    end Builder;
11908 @end smallexample
11910 @noindent
11911 In this example, @code{Default} must be either a project imported by the
11912 current project, or the project that the current project extends. If the
11913 attribute is in a package (in this case, in package @code{Builder}), the same
11914 package needs to be specified.
11916 @noindent
11917 A full associative array declaration replaces any other declaration for the
11918 attribute, including other full associative array declaration. Single
11919 associative array associations may be declare after a full associative
11920 declaration, modifying the value for a single association of the attribute.
11922 @node case Constructions
11923 @subsection @code{case} Constructions
11925 @noindent
11926 A @code{case} construction is used in a project file to effect conditional
11927 behavior.
11928 Here is a typical example:
11930 @smallexample @c projectfile
11931 @group
11932 project MyProj is
11933    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11935    OS : OS_Type := external ("OS", "GNU/Linux");
11936 @end group
11938 @group
11939    package Compiler is
11940      case OS is
11941        when "GNU/Linux" | "Unix" =>
11942          for ^Default_Switches^Default_Switches^ ("Ada")
11943              use ("^-gnath^-gnath^");
11944        when "NT" =>
11945          for ^Default_Switches^Default_Switches^ ("Ada")
11946              use ("^-gnatP^-gnatP^");
11947        when others =>
11948      end case;
11949    end Compiler;
11950 end MyProj;
11951 @end group
11952 @end smallexample
11954 @noindent
11955 The syntax of a @code{case} construction is based on the Ada case statement
11956 (although there is no @code{null} construction for empty alternatives).
11958 The case expression must be a typed string variable.
11959 Each alternative comprises the reserved word @code{when}, either a list of
11960 literal strings separated by the @code{"|"} character or the reserved word
11961 @code{others},  and the @code{"=>"} token.
11962 Each literal string must belong to the string type that is the type of the
11963 case variable.
11964 An @code{others} alternative, if present, must occur last.
11966 After each @code{=>}, there are zero or more constructions.  The only
11967 constructions allowed in a case construction are other case constructions and
11968 attribute declarations. String type declarations, variable declarations and
11969 package declarations are not allowed.
11971 The value of the case variable is often given by an external reference
11972 (@pxref{External References in Project Files}).
11974 @c ****************************************
11975 @c * Objects and Sources in Project Files *
11976 @c ****************************************
11978 @node Objects and Sources in Project Files
11979 @section Objects and Sources in Project Files
11981 @menu
11982 * Object Directory::
11983 * Exec Directory::
11984 * Source Directories::
11985 * Source File Names::
11986 @end menu
11988 @noindent
11989 Each project has exactly one object directory and one or more source
11990 directories. The source directories must contain at least one source file,
11991 unless  the project file explicitly specifies that no source files are present
11992 (@pxref{Source File Names}).
11994 @node Object Directory
11995 @subsection Object Directory
11997 @noindent
11998 The object directory for a project is the directory containing the compiler's
11999 output (such as @file{ALI} files and object files) for the project's immediate
12000 sources.
12002 The object directory is given by the value of the attribute @code{Object_Dir}
12003 in the project file.
12005 @smallexample @c projectfile
12006    for Object_Dir use "objects";
12007 @end smallexample
12009 @noindent
12010 The attribute @var{Object_Dir} has a string value, the path name of the object
12011 directory. The path name may be absolute or relative to the directory of the
12012 project file. This directory must already exist, and be readable and writable.
12014 By default, when the attribute @code{Object_Dir} is not given an explicit value
12015 or when its value is the empty string, the object directory is the same as the
12016 directory containing the project file.
12018 @node Exec Directory
12019 @subsection Exec Directory
12021 @noindent
12022 The exec directory for a project is the directory containing the executables
12023 for the project's main subprograms.
12025 The exec directory is given by the value of the attribute @code{Exec_Dir}
12026 in the project file.
12028 @smallexample @c projectfile
12029    for Exec_Dir use "executables";
12030 @end smallexample
12032 @noindent
12033 The attribute @var{Exec_Dir} has a string value, the path name of the exec
12034 directory. The path name may be absolute or relative to the directory of the
12035 project file. This directory must already exist, and be writable.
12037 By default, when the attribute @code{Exec_Dir} is not given an explicit value
12038 or when its value is the empty string, the exec directory is the same as the
12039 object directory of the project file.
12041 @node Source Directories
12042 @subsection Source Directories
12044 @noindent
12045 The source directories of a project are specified by the project file
12046 attribute @code{Source_Dirs}.
12048 This attribute's value is a string list. If the attribute is not given an
12049 explicit value, then there is only one source directory, the one where the
12050 project file resides.
12052 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
12053 as in
12055 @smallexample @c projectfile
12056     for Source_Dirs use ();
12057 @end smallexample
12059 @noindent
12060 indicates that the project contains no source files.
12062 Otherwise, each string in the string list designates one or more
12063 source directories.
12065 @smallexample @c projectfile
12066    for Source_Dirs use ("sources", "test/drivers");
12067 @end smallexample
12069 @noindent
12070 If a string in the list ends with @code{"/**"},  then the directory whose path
12071 name precedes the two asterisks, as well as all its subdirectories
12072 (recursively), are source directories.
12074 @smallexample @c projectfile
12075    for Source_Dirs use ("/system/sources/**");
12076 @end smallexample
12078 @noindent
12079 Here the directory @code{/system/sources} and all of its subdirectories
12080 (recursively) are source directories.
12082 To specify that the source directories are the directory of the project file
12083 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
12084 @smallexample @c projectfile
12085    for Source_Dirs use ("./**");
12086 @end smallexample
12088 @noindent
12089 Each of the source directories must exist and be readable.
12091 @node Source File Names
12092 @subsection Source File Names
12094 @noindent
12095 In a project that contains source files, their names may be specified by the
12096 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
12097 (a string). Source file names never include any directory information.
12099 If the attribute @code{Source_Files} is given an explicit value, then each
12100 element of the list is a source file name.
12102 @smallexample @c projectfile
12103    for Source_Files use ("main.adb");
12104    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
12105 @end smallexample
12107 @noindent
12108 If the attribute @code{Source_Files} is not given an explicit value,
12109 but the attribute @code{Source_List_File} is given a string value,
12110 then the source file names are contained in the text file whose path name
12111 (absolute or relative to the directory of the project file) is the
12112 value of the attribute @code{Source_List_File}.
12114 Each line in the file that is not empty or is not a comment
12115 contains a source file name.
12117 @smallexample @c projectfile
12118    for Source_List_File use "source_list.txt";
12119 @end smallexample
12121 @noindent
12122 By default, if neither the attribute @code{Source_Files} nor the attribute
12123 @code{Source_List_File} is given an explicit value, then each file in the
12124 source directories that conforms to the project's naming scheme
12125 (@pxref{Naming Schemes}) is an immediate source of the project.
12127 A warning is issued if both attributes @code{Source_Files} and
12128 @code{Source_List_File} are given explicit values. In this case, the attribute
12129 @code{Source_Files} prevails.
12131 Each source file name must be the name of one existing source file
12132 in one of the source directories.
12134 A @code{Source_Files} attribute whose value is an empty list
12135 indicates that there are no source files in the project.
12137 If the order of the source directories is known statically, that is if
12138 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
12139 be several files with the same source file name. In this case, only the file
12140 in the first directory is considered as an immediate source of the project
12141 file. If the order of the source directories is not known statically, it is
12142 an error to have several files with the same source file name.
12144 Projects can be specified to have no Ada source
12145 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
12146 list, or the @code{"Ada"} may be absent from @code{Languages}:
12148 @smallexample @c projectfile
12149    for Source_Dirs use ();
12150    for Source_Files use ();
12151    for Languages use ("C", "C++");
12152 @end smallexample
12154 @noindent
12155 Otherwise, a project must contain at least one immediate source.
12157 Projects with no source files are useful as template packages
12158 (@pxref{Packages in Project Files}) for other projects; in particular to
12159 define a package @code{Naming} (@pxref{Naming Schemes}).
12161 @c ****************************
12162 @c * Importing Projects *
12163 @c ****************************
12165 @node  Importing Projects
12166 @section Importing Projects
12167 @cindex @code{ADA_PROJECT_PATH}
12169 @noindent
12170 An immediate source of a project P may depend on source files that
12171 are neither immediate sources of P nor in the predefined library.
12172 To get this effect, P must @emph{import} the projects that contain the needed
12173 source files.
12175 @smallexample @c projectfile
12176 @group
12177   with "project1", "utilities.gpr";
12178   with "/namings/apex.gpr";
12179   project Main is
12180     ...
12181 @end group
12182 @end smallexample
12184 @noindent
12185 As can be seen in this example, the syntax for importing projects is similar
12186 to the syntax for importing compilation units in Ada. However, project files
12187 use literal strings instead of names, and the @code{with} clause identifies
12188 project files rather than packages.
12190 Each literal string is the file name or path name (absolute or relative) of a
12191 project file. If a string corresponds to a file name, with no path or a
12192 relative path, then its location is determined by the @emph{project path}. The
12193 latter can be queried using @code{gnatls -v}. It contains:
12195 @itemize @bullet
12196 @item
12197 In first position, the directory containing the current project file.
12198 @item
12199 In last position, the default project directory. This default project directory
12200 is part of the GNAT installation and is the standard place to install project
12201 files giving access to standard support libraries.
12202 @ifclear vms
12203 @ref{Installing a library}
12204 @end ifclear
12206 @item
12207 In between, all the directories referenced in the
12208 ^environment variable^logical name^ @env{ADA_PROJECT_PATH} if it exists.
12209 @end itemize
12211 @noindent
12212 If a relative pathname is used, as in
12214 @smallexample @c projectfile
12215   with "tests/proj";
12216 @end smallexample
12218 @noindent
12219 then the full path for the project is constructed by concatenating this
12220 relative path to those in the project path, in order, until a matching file is
12221 found. Any symbolic link will be fully resolved in the directory of the
12222 importing project file before the imported project file is examined.
12224 If the @code{with}'ed project file name does not have an extension,
12225 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
12226 then the file name as specified in the @code{with} clause (no extension) will
12227 be used. In the above example, if a file @code{project1.gpr} is found, then it
12228 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
12229 then it will be used; if neither file exists, this is an error.
12231 A warning is issued if the name of the project file does not match the
12232 name of the project; this check is case insensitive.
12234 Any source file that is an immediate source of the imported project can be
12235 used by the immediate sources of the importing project, transitively. Thus
12236 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
12237 sources of @code{A} may depend on the immediate sources of @code{C}, even if
12238 @code{A} does not import @code{C} explicitly. However, this is not recommended,
12239 because if and when @code{B} ceases to import @code{C}, some sources in
12240 @code{A} will no longer compile.
12242 A side effect of this capability is that normally cyclic dependencies are not
12243 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
12244 is not allowed to import @code{A}. However, there are cases when cyclic
12245 dependencies would be beneficial. For these cases, another form of import
12246 between projects exists, the @code{limited with}: a project @code{A} that
12247 imports a project @code{B} with a straight @code{with} may also be imported,
12248 directly or indirectly, by @code{B} on the condition that imports from @code{B}
12249 to @code{A} include at least one @code{limited with}.
12251 @smallexample @c 0projectfile
12252 with "../b/b.gpr";
12253 with "../c/c.gpr";
12254 project A is
12255 end A;
12257 limited with "../a/a.gpr";
12258 project B is
12259 end B;
12261 with "../d/d.gpr";
12262 project C is
12263 end C;
12265 limited with "../a/a.gpr";
12266 project D is
12267 end D;
12268 @end smallexample
12270 @noindent
12271 In the above legal example, there are two project cycles:
12272 @itemize @bullet
12273 @item A-> B-> A
12274 @item A -> C -> D -> A
12275 @end itemize
12277 @noindent
12278 In each of these cycle there is one @code{limited with}: import of @code{A}
12279 from @code{B} and import of @code{A} from @code{D}.
12281 The difference between straight @code{with} and @code{limited with} is that
12282 the name of a project imported with a @code{limited with} cannot be used in the
12283 project that imports it. In particular, its packages cannot be renamed and
12284 its variables cannot be referred to.
12286 An exception to the above rules for @code{limited with} is that for the main
12287 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12288 @code{limited with} is equivalent to a straight @code{with}. For example,
12289 in the example above, projects @code{B} and @code{D} could not be main
12290 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12291 each have a @code{limited with} that is the only one in a cycle of importing
12292 projects.
12294 @c *********************
12295 @c * Project Extension *
12296 @c *********************
12298 @node Project Extension
12299 @section Project Extension
12301 @noindent
12302 During development of a large system, it is sometimes necessary to use
12303 modified versions of some of the source files, without changing the original
12304 sources. This can be achieved through the @emph{project extension} facility.
12306 @smallexample @c projectfile
12307    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12308 @end smallexample
12310 @noindent
12311 A project extension declaration introduces an extending project
12312 (the @emph{child}) and a project being extended (the @emph{parent}).
12314 By default, a child project inherits all the sources of its parent.
12315 However, inherited sources can be overridden: a unit in a parent is hidden
12316 by a unit of the same name in the child.
12318 Inherited sources are considered to be sources (but not immediate sources)
12319 of the child project; see @ref{Project File Syntax}.
12321 An inherited source file retains any switches specified in the parent project.
12323 For example if the project @code{Utilities} contains the specification and the
12324 body of an Ada package @code{Util_IO}, then the project
12325 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12326 The original body of @code{Util_IO} will not be considered in program builds.
12327 However, the package specification will still be found in the project
12328 @code{Utilities}.
12330 A child project can have only one parent but it may import any number of other
12331 projects.
12333 A project is not allowed to import directly or indirectly at the same time a
12334 child project and any of its ancestors.
12336 @c *******************************
12337 @c * Project Hierarchy Extension *
12338 @c *******************************
12340 @node Project Hierarchy Extension
12341 @section Project Hierarchy Extension
12343 @noindent
12344 When extending a large system spanning multiple projects, it is often
12345 inconvenient to extend every project in the hierarchy that is impacted by a
12346 small change introduced. In such cases, it is possible to create a virtual
12347 extension of entire hierarchy using @code{extends all} relationship.
12349 When the project is extended using @code{extends all} inheritance, all projects
12350 that are imported by it, both directly and indirectly, are considered virtually
12351 extended. That is, the Project Manager creates "virtual projects"
12352 that extend every project in the hierarchy; all these virtual projects have
12353 no sources of their own and have as object directory the object directory of
12354 the root of "extending all" project.
12356 It is possible to explicitly extend one or more projects in the hierarchy
12357 in order to modify the sources. These extending projects must be imported by
12358 the "extending all" project, which will replace the corresponding virtual
12359 projects with the explicit ones.
12361 When building such a project hierarchy extension, the Project Manager will
12362 ensure that both modified sources and sources in virtual extending projects
12363 that depend on them, are recompiled.
12365 By means of example, consider the following hierarchy of projects.
12367 @enumerate
12368 @item
12369 project A, containing package P1
12370 @item
12371 project B importing A and containing package P2 which depends on P1
12372 @item
12373 project C importing B and containing package P3 which depends on P2
12374 @end enumerate
12376 @noindent
12377 We want to modify packages P1 and P3.
12379 This project hierarchy will need to be extended as follows:
12381 @enumerate
12382 @item
12383 Create project A1 that extends A, placing modified P1 there:
12385 @smallexample @c 0projectfile
12386 project A1 extends "(...)/A" is
12387 end A1;
12388 @end smallexample
12390 @item
12391 Create project C1 that "extends all" C and imports A1, placing modified
12392 P3 there:
12394 @smallexample @c 0projectfile
12395 with "(...)/A1";
12396 project C1 extends all "(...)/C" is
12397 end C1;
12398 @end smallexample
12399 @end enumerate
12401 When you build project C1, your entire modified project space will be
12402 recompiled, including the virtual project B1 that has been impacted by the
12403 "extending all" inheritance of project C.
12405 Note that if a Library Project in the hierarchy is virtually extended,
12406 the virtual project that extends the Library Project is not a Library Project.
12408 @c ****************************************
12409 @c * External References in Project Files *
12410 @c ****************************************
12412 @node  External References in Project Files
12413 @section External References in Project Files
12415 @noindent
12416 A project file may contain references to external variables; such references
12417 are called @emph{external references}.
12419 An external variable is either defined as part of the environment (an
12420 environment variable in Unix, for example) or else specified on the command
12421 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12422 If both, then the command line value is used.
12424 The value of an external reference is obtained by means of the built-in
12425 function @code{external}, which returns a string value.
12426 This function has two forms:
12427 @itemize @bullet
12428 @item @code{external (external_variable_name)}
12429 @item @code{external (external_variable_name, default_value)}
12430 @end itemize
12432 @noindent
12433 Each parameter must be a string literal.  For example:
12435 @smallexample @c projectfile
12436    external ("USER")
12437    external ("OS", "GNU/Linux")
12438 @end smallexample
12440 @noindent
12441 In the form with one parameter, the function returns the value of
12442 the external variable given as parameter. If this name is not present in the
12443 environment, the function returns an empty string.
12445 In the form with two string parameters, the second argument is
12446 the value returned when the variable given as the first argument is not
12447 present in the environment. In the example above, if @code{"OS"} is not
12448 the name of ^an environment variable^a logical name^ and is not passed on
12449 the command line, then the returned value is @code{"GNU/Linux"}.
12451 An external reference may be part of a string expression or of a string
12452 list expression, and can therefore appear in a variable declaration or
12453 an attribute declaration.
12455 @smallexample @c projectfile
12456 @group
12457    type Mode_Type is ("Debug", "Release");
12458    Mode : Mode_Type := external ("MODE");
12459    case Mode is
12460      when "Debug" =>
12461         ...
12462 @end group
12463 @end smallexample
12465 @c *****************************
12466 @c * Packages in Project Files *
12467 @c *****************************
12469 @node  Packages in Project Files
12470 @section Packages in Project Files
12472 @noindent
12473 A @emph{package} defines the settings for project-aware tools within a
12474 project.
12475 For each such tool one can declare a package; the names for these
12476 packages are preset (@pxref{Packages}).
12477 A package may contain variable declarations, attribute declarations, and case
12478 constructions.
12480 @smallexample @c projectfile
12481 @group
12482    project Proj is
12483       package Builder is  -- used by gnatmake
12484          for ^Default_Switches^Default_Switches^ ("Ada")
12485              use ("^-v^-v^",
12486                   "^-g^-g^");
12487       end Builder;
12488    end Proj;
12489 @end group
12490 @end smallexample
12492 @noindent
12493 The syntax of package declarations mimics that of package in Ada.
12495 Most of the packages have an attribute
12496 @code{^Default_Switches^Default_Switches^}.
12497 This attribute is an associative array, and its value is a string list.
12498 The index of the associative array is the name of a programming language (case
12499 insensitive). This attribute indicates the ^switch^switch^
12500 or ^switches^switches^ to be used
12501 with the corresponding tool.
12503 Some packages also have another attribute, @code{^Switches^Switches^},
12504 an associative array whose value is a string list.
12505 The index is the name of a source file.
12506 This attribute indicates the ^switch^switch^
12507 or ^switches^switches^ to be used by the corresponding
12508 tool when dealing with this specific file.
12510 Further information on these ^switch^switch^-related attributes is found in
12511 @ref{^Switches^Switches^ and Project Files}.
12513 A package may be declared as a @emph{renaming} of another package; e.g., from
12514 the project file for an imported project.
12516 @smallexample @c projectfile
12517 @group
12518   with "/global/apex.gpr";
12519   project Example is
12520     package Naming renames Apex.Naming;
12521     ...
12522   end Example;
12523 @end group
12524 @end smallexample
12526 @noindent
12527 Packages that are renamed in other project files often come from project files
12528 that have no sources: they are just used as templates. Any modification in the
12529 template will be reflected automatically in all the project files that rename
12530 a package from the template.
12532 In addition to the tool-oriented packages, you can also declare a package
12533 named @code{Naming} to establish specialized source file naming conventions
12534 (@pxref{Naming Schemes}).
12536 @c ************************************
12537 @c * Variables from Imported Projects *
12538 @c ************************************
12540 @node Variables from Imported Projects
12541 @section Variables from Imported Projects
12543 @noindent
12544 An attribute or variable defined in an imported or parent project can
12545 be used in expressions in the importing / extending project.
12546 Such an attribute or variable is denoted by an expanded name whose prefix
12547 is either the name of the project or the expanded name of a package within
12548 a project.
12550 @smallexample @c projectfile
12551 @group
12552   with "imported";
12553   project Main extends "base" is
12554      Var1 := Imported.Var;
12555      Var2 := Base.Var & ".new";
12556 @end group
12558 @group
12559      package Builder is
12560         for ^Default_Switches^Default_Switches^ ("Ada")
12561             use Imported.Builder.Ada_^Switches^Switches^ &
12562                 "^-gnatg^-gnatg^" &
12563                 "^-v^-v^";
12564      end Builder;
12565 @end group
12567 @group
12568      package Compiler is
12569         for ^Default_Switches^Default_Switches^ ("Ada")
12570             use Base.Compiler.Ada_^Switches^Switches^;
12571      end Compiler;
12572   end Main;
12573 @end group
12574 @end smallexample
12576 @noindent
12577 In this example:
12579 @itemize @bullet
12580 @item
12581 The value of @code{Var1} is a copy of the variable @code{Var} defined
12582 in the project file @file{"imported.gpr"}
12583 @item
12584 the value of @code{Var2} is a copy of the value of variable @code{Var}
12585 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12586 @item
12587 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12588 @code{Builder} is a string list that includes in its value a copy of the value
12589 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12590 in project file @file{imported.gpr} plus two new elements:
12591 @option{"^-gnatg^-gnatg^"}
12592 and @option{"^-v^-v^"};
12593 @item
12594 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12595 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12596 defined in the @code{Compiler} package in project file @file{base.gpr},
12597 the project being extended.
12598 @end itemize
12600 @c ******************
12601 @c * Naming Schemes *
12602 @c ******************
12604 @node  Naming Schemes
12605 @section Naming Schemes
12607 @noindent
12608 Sometimes an Ada software system is ported from a foreign compilation
12609 environment to GNAT, and the file names do not use the default GNAT
12610 conventions. Instead of changing all the file names (which for a variety
12611 of reasons might not be possible), you can define the relevant file
12612 naming scheme in the @code{Naming} package in your project file.
12614 @noindent
12615 Note that the use of pragmas described in
12616 @ref{Alternative File Naming Schemes} by mean of a configuration
12617 pragmas file is not supported when using project files. You must use
12618 the features described in this paragraph. You can however use specify
12619 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
12621 @ifclear vms
12622 For example, the following
12623 package models the Apex file naming rules:
12625 @smallexample @c projectfile
12626 @group
12627   package Naming is
12628     for Casing               use "lowercase";
12629     for Dot_Replacement      use ".";
12630     for Spec_Suffix ("Ada")  use ".1.ada";
12631     for Body_Suffix ("Ada")  use ".2.ada";
12632   end Naming;
12633 @end group
12634 @end smallexample
12635 @end ifclear
12637 @ifset vms
12638 For example, the following package models the HP Ada file naming rules:
12640 @smallexample @c projectfile
12641 @group
12642   package Naming is
12643     for Casing               use "lowercase";
12644     for Dot_Replacement      use "__";
12645     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12646     for Body_Suffix ("Ada")  use ".^ada^ada^";
12647   end Naming;
12648 @end group
12649 @end smallexample
12651 @noindent
12652 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12653 names in lower case)
12654 @end ifset
12656 @noindent
12657 You can define the following attributes in package @code{Naming}:
12659 @table @code
12661 @item @var{Casing}
12662 This must be a string with one of the three values @code{"lowercase"},
12663 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12665 @noindent
12666 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12668 @item @var{Dot_Replacement}
12669 This must be a string whose value satisfies the following conditions:
12671 @itemize @bullet
12672 @item It must not be empty
12673 @item It cannot start or end with an alphanumeric character
12674 @item It cannot be a single underscore
12675 @item It cannot start with an underscore followed by an alphanumeric
12676 @item It cannot contain a dot @code{'.'} except if the entire string
12677 is @code{"."}
12678 @end itemize
12680 @noindent
12681 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12683 @item @var{Spec_Suffix}
12684 This is an associative array (indexed by the programming language name, case
12685 insensitive) whose value is a string that must satisfy the following
12686 conditions:
12688 @itemize @bullet
12689 @item It must not be empty
12690 @item It must include at least one dot
12691 @end itemize
12692 @noindent
12693 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12694 @code{"^.ads^.ADS^"}.
12696 @item @var{Body_Suffix}
12697 This is an associative array (indexed by the programming language name, case
12698 insensitive) whose value is a string that must satisfy the following
12699 conditions:
12701 @itemize @bullet
12702 @item It must not be empty
12703 @item It must include at least one dot
12704 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12705 @end itemize
12706 @noindent
12707 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12708 @code{"^.adb^.ADB^"}.
12710 @item @var{Separate_Suffix}
12711 This must be a string whose value satisfies the same conditions as
12712 @code{Body_Suffix}.
12714 @noindent
12715 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12716 value as @code{Body_Suffix ("Ada")}.
12718 @item @var{Spec}
12719 @noindent
12720 You can use the associative array attribute @code{Spec}  to define
12721 the source file name for an individual Ada compilation unit's spec. The array
12722 index must be a string literal that identifies the Ada unit (case insensitive).
12723 The value of this attribute must be a string that identifies the file that
12724 contains this unit's spec (case sensitive or insensitive depending on the
12725 operating system).
12727 @smallexample @c projectfile
12728    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12729 @end smallexample
12731 @item @var{Body}
12733 You can use the associative array attribute @code{Body} to
12734 define the source file name for an individual Ada compilation unit's body
12735 (possibly a subunit).  The array index must be a string literal that identifies
12736 the Ada unit (case insensitive).  The value of this attribute must be a string
12737 that identifies the file that contains this unit's body or subunit (case
12738 sensitive or insensitive depending on the operating system).
12740 @smallexample @c projectfile
12741    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12742 @end smallexample
12743 @end table
12745 @c ********************
12746 @c * Library Projects *
12747 @c ********************
12749 @node Library Projects
12750 @section Library Projects
12752 @noindent
12753 @emph{Library projects} are projects whose object code is placed in a library.
12754 (Note that this facility is not yet supported on all platforms)
12756 To create a library project, you need to define in its project file
12757 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12758 Additionally, you may define other library-related attributes such as
12759 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12760 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12762 The @code{Library_Name} attribute has a string value. There is no restriction
12763 on the name of a library. It is the responsibility of the developer to
12764 choose a name that will be accepted by the platform. It is recommended to
12765 choose names that could be Ada identifiers; such names are almost guaranteed
12766 to be acceptable on all platforms.
12768 The @code{Library_Dir} attribute has a string value that designates the path
12769 (absolute or relative) of the directory where the library will reside.
12770 It must designate an existing directory, and this directory must be writable,
12771 different from the project's object directory and from any source directory
12772 in the project tree.
12774 If both @code{Library_Name} and @code{Library_Dir} are specified and
12775 are legal, then the project file defines a library project.  The optional
12776 library-related attributes are checked only for such project files.
12778 The @code{Library_Kind} attribute has a string value that must be one of the
12779 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12780 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
12781 attribute is not specified, the library is a static library, that is
12782 an archive of object files that can be potentially linked into a
12783 static executable. Otherwise, the library may be dynamic or
12784 relocatable, that is a library that is loaded only at the start of execution.
12786 If you need to build both a static and a dynamic library, you should use two
12787 different object directories, since in some cases some extra code needs to
12788 be generated for the latter. For such cases, it is recommended to either use
12789 two different project files, or a single one which uses external variables
12790 to indicate what kind of library should be build.
12792 The @code{Library_ALI_Dir} attribute may be specified to indicate the
12793 directory where the ALI files of the library will be copied. When it is
12794 not specified, the ALI files are copied ti the directory specified in
12795 attribute @code{Library_Dir}. The directory specified by @code{Library_ALI_Dir}
12796 must be writable and different from the project's object directory and from
12797 any source directory in the project tree.
12799 The @code{Library_Version} attribute has a string value whose interpretation
12800 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12801 used only for dynamic/relocatable libraries as the internal name of the
12802 library (the @code{"soname"}). If the library file name (built from the
12803 @code{Library_Name}) is different from the @code{Library_Version}, then the
12804 library file will be a symbolic link to the actual file whose name will be
12805 @code{Library_Version}.
12807 Example (on Unix):
12809 @smallexample @c projectfile
12810 @group
12811 project Plib is
12813    Version := "1";
12815    for Library_Dir use "lib_dir";
12816    for Library_Name use "dummy";
12817    for Library_Kind use "relocatable";
12818    for Library_Version use "libdummy.so." & Version;
12820 end Plib;
12821 @end group
12822 @end smallexample
12824 @noindent
12825 Directory @file{lib_dir} will contain the internal library file whose name
12826 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12827 @file{libdummy.so.1}.
12829 When @command{gnatmake} detects that a project file
12830 is a library project file, it will check all immediate sources of the project
12831 and rebuild the library if any of the sources have been recompiled.
12833 Standard project files can import library project files. In such cases,
12834 the libraries will only be rebuilt if some of its sources are recompiled
12835 because they are in the closure of some other source in an importing project.
12836 Sources of the library project files that are not in such a closure will
12837 not be checked, unless the full library is checked, because one of its sources
12838 needs to be recompiled.
12840 For instance, assume the project file @code{A} imports the library project file
12841 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12842 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12843 @file{l2.ads}, @file{l2.adb}.
12845 If @file{l1.adb} has been modified, then the library associated with @code{L}
12846 will be rebuilt when compiling all the immediate sources of @code{A} only
12847 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12848 @code{"with L1;"}.
12850 To be sure that all the sources in the library associated with @code{L} are
12851 up to date, and that all the sources of project @code{A} are also up to date,
12852 the following two commands needs to be used:
12854 @smallexample
12855 gnatmake -Pl.gpr
12856 gnatmake -Pa.gpr
12857 @end smallexample
12859 When a library is built or rebuilt, an attempt is made first to delete all
12860 files in the library directory.
12861 All @file{ALI} files will also be copied from the object directory to the
12862 library directory. To build executables, @command{gnatmake} will use the
12863 library rather than the individual object files.
12865 @ifclear vms
12866 It is also possible to create library project files for third-party libraries
12867 that are precompiled and cannot be compiled locally thanks to the
12868 @code{externally_built} attribute. (See @ref{Installing a library}).
12869 @end ifclear
12871 @c *******************************
12872 @c * Stand-alone Library Projects *
12873 @c *******************************
12875 @node Stand-alone Library Projects
12876 @section Stand-alone Library Projects
12878 @noindent
12879 A Stand-alone Library is a library that contains the necessary code to
12880 elaborate the Ada units that are included in the library. A Stand-alone
12881 Library is suitable to be used in an executable when the main is not
12882 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12883 subprogram.
12885 A Stand-alone Library Project is a Library Project where the library is
12886 a Stand-alone Library.
12888 To be a Stand-alone Library Project, in addition to the two attributes
12889 that make a project a Library Project (@code{Library_Name} and
12890 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12891 @code{Library_Interface} must be defined.
12893 @smallexample @c projectfile
12894 @group
12895    for Library_Dir use "lib_dir";
12896    for Library_Name use "dummy";
12897    for Library_Interface use ("int1", "int1.child");
12898 @end group
12899 @end smallexample
12901 Attribute @code{Library_Interface} has a non empty string list value,
12902 each string in the list designating a unit contained in an immediate source
12903 of the project file.
12905 When a Stand-alone Library is built, first the binder is invoked to build
12906 a package whose name depends on the library name
12907 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12908 This binder-generated package includes initialization and
12909 finalization procedures whose
12910 names depend on the library name (dummyinit and dummyfinal in the example
12911 above). The object corresponding to this package is included in the library.
12913 A dynamic or relocatable Stand-alone Library is automatically initialized
12914 if automatic initialization of Stand-alone Libraries is supported on the
12915 platform and if attribute @code{Library_Auto_Init} is not specified or
12916 is specified with the value "true". A static Stand-alone Library is never
12917 automatically initialized.
12919 Single string attribute @code{Library_Auto_Init} may be specified with only
12920 two possible values: "false" or "true" (case-insensitive). Specifying
12921 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12922 initialization of dynamic or relocatable libraries.
12924 When a non automatically initialized Stand-alone Library is used
12925 in an executable, its initialization procedure must be called before
12926 any service of the library is used.
12927 When the main subprogram is in Ada, it may mean that the initialization
12928 procedure has to be called during elaboration of another package.
12930 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12931 (those that are listed in attribute @code{Library_Interface}) are copied to
12932 the Library Directory. As a consequence, only the Interface Units may be
12933 imported from Ada units outside of the library. If other units are imported,
12934 the binding phase will fail.
12936 When a Stand-Alone Library is bound, the switches that are specified in
12937 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12938 used in the call to @command{gnatbind}.
12940 The string list attribute @code{Library_Options} may be used to specified
12941 additional switches to the call to @command{gcc} to link the library.
12943 The attribute @code{Library_Src_Dir}, may be specified for a
12944 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12945 single string value. Its value must be the path (absolute or relative to the
12946 project directory) of an existing directory. This directory cannot be the
12947 object directory or one of the source directories, but it can be the same as
12948 the library directory. The sources of the Interface
12949 Units of the library, necessary to an Ada client of the library, will be
12950 copied to the designated directory, called Interface Copy directory.
12951 These sources includes the specs of the Interface Units, but they may also
12952 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12953 are used, or when there is a generic units in the spec. Before the sources
12954 are copied to the Interface Copy directory, an attempt is made to delete all
12955 files in the Interface Copy directory.
12957 @c *************************************
12958 @c * Switches Related to Project Files *
12959 @c *************************************
12960 @node Switches Related to Project Files
12961 @section Switches Related to Project Files
12963 @noindent
12964 The following switches are used by GNAT tools that support project files:
12966 @table @option
12968 @item ^-P^/PROJECT_FILE=^@var{project}
12969 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12970 Indicates the name of a project file. This project file will be parsed with
12971 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12972 if any, and using the external references indicated
12973 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12974 @ifclear vms
12975 There may zero, one or more spaces between @option{-P} and @var{project}.
12976 @end ifclear
12978 @noindent
12979 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12981 @noindent
12982 Since the Project Manager parses the project file only after all the switches
12983 on the command line are checked, the order of the switches
12984 @option{^-P^/PROJECT_FILE^},
12985 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12986 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12988 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12989 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12990 Indicates that external variable @var{name} has the value @var{value}.
12991 The Project Manager will use this value for occurrences of
12992 @code{external(name)} when parsing the project file.
12994 @ifclear vms
12995 @noindent
12996 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12997 put between quotes.
12998 @smallexample
12999   -XOS=NT
13000   -X"user=John Doe"
13001 @end smallexample
13002 @end ifclear
13004 @noindent
13005 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
13006 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
13007 @var{name}, only the last one is used.
13009 @noindent
13010 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
13011 takes precedence over the value of the same name in the environment.
13013 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
13014 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
13015 @c Previous line uses code vs option command, to stay less than 80 chars
13016 Indicates the verbosity of the parsing of GNAT project files.
13018 @ifclear vms
13019 @option{-vP0} means Default;
13020 @option{-vP1} means Medium;
13021 @option{-vP2} means High.
13022 @end ifclear
13024 @ifset vms
13025 There are three possible options for this qualifier: DEFAULT, MEDIUM and
13026 HIGH.
13027 @end ifset
13029 @noindent
13030 The default is ^Default^DEFAULT^: no output for syntactically correct
13031 project files.
13032 @noindent
13033 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
13034 only the last one is used.
13036 @end table
13038 @c **********************************
13039 @c * Tools Supporting Project Files *
13040 @c **********************************
13042 @node  Tools Supporting Project Files
13043 @section Tools Supporting Project Files
13045 @menu
13046 * gnatmake and Project Files::
13047 * The GNAT Driver and Project Files::
13048 @ifclear vms
13049 * Glide and Project Files::
13050 @end ifclear
13051 @end menu
13053 @node gnatmake and Project Files
13054 @subsection gnatmake and Project Files
13056 @noindent
13057 This section covers several topics related to @command{gnatmake} and
13058 project files: defining ^switches^switches^ for @command{gnatmake}
13059 and for the tools that it invokes; specifying configuration pragmas;
13060 the use of the @code{Main} attribute; building and rebuilding library project
13061 files.
13063 @menu
13064 * ^Switches^Switches^ and Project Files::
13065 * Specifying Configuration Pragmas::
13066 * Project Files and Main Subprograms::
13067 * Library Project Files::
13068 @end menu
13070 @node ^Switches^Switches^ and Project Files
13071 @subsubsection ^Switches^Switches^ and Project Files
13073 @ifset vms
13074 It is not currently possible to specify VMS style qualifiers in the project
13075 files; only Unix style ^switches^switches^ may be specified.
13076 @end ifset
13078 @noindent
13079 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
13080 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
13081 attribute, a @code{^Switches^Switches^} attribute, or both;
13082 as their names imply, these ^switch^switch^-related
13083 attributes affect the ^switches^switches^ that are used for each of these GNAT
13084 components when
13085 @command{gnatmake} is invoked.  As will be explained below, these
13086 component-specific ^switches^switches^ precede
13087 the ^switches^switches^ provided on the @command{gnatmake} command line.
13089 The @code{^Default_Switches^Default_Switches^} attribute is an associative
13090 array indexed by language name (case insensitive) whose value is a string list.
13091 For example:
13093 @smallexample @c projectfile
13094 @group
13095 package Compiler is
13096   for ^Default_Switches^Default_Switches^ ("Ada")
13097       use ("^-gnaty^-gnaty^",
13098            "^-v^-v^");
13099 end Compiler;
13100 @end group
13101 @end smallexample
13103 @noindent
13104 The @code{^Switches^Switches^} attribute is also an associative array,
13105 indexed by a file name (which may or may not be case sensitive, depending
13106 on the operating system) whose value is a string list.  For example:
13108 @smallexample @c projectfile
13109 @group
13110 package Builder is
13111    for ^Switches^Switches^ ("main1.adb")
13112        use ("^-O2^-O2^");
13113    for ^Switches^Switches^ ("main2.adb")
13114        use ("^-g^-g^");
13115 end Builder;
13116 @end group
13117 @end smallexample
13119 @noindent
13120 For the @code{Builder} package, the file names must designate source files
13121 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
13122 file names must designate @file{ALI} or source files for main subprograms.
13123 In each case just the file name without an explicit extension is acceptable.
13125 For each tool used in a program build (@command{gnatmake}, the compiler, the
13126 binder, and the linker), the corresponding package @dfn{contributes} a set of
13127 ^switches^switches^ for each file on which the tool is invoked, based on the
13128 ^switch^switch^-related attributes defined in the package.
13129 In particular, the ^switches^switches^
13130 that each of these packages contributes for a given file @var{f} comprise:
13132 @itemize @bullet
13133 @item
13134 the value of attribute @code{^Switches^Switches^ (@var{f})},
13135 if it is specified in the package for the given file,
13136 @item
13137 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
13138 if it is specified in the package.
13139 @end itemize
13141 @noindent
13142 If neither of these attributes is defined in the package, then the package does
13143 not contribute any ^switches^switches^ for the given file.
13145 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
13146 two sets, in the following order: those contributed for the file
13147 by the @code{Builder} package;
13148 and the switches passed on the command line.
13150 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
13151 the ^switches^switches^ passed to the tool comprise three sets,
13152 in the following order:
13154 @enumerate
13155 @item
13156 the applicable ^switches^switches^ contributed for the file
13157 by the @code{Builder} package in the project file supplied on the command line;
13159 @item
13160 those contributed for the file by the package (in the relevant project file --
13161 see below) corresponding to the tool; and
13163 @item
13164 the applicable switches passed on the command line.
13165 @end enumerate
13167 @noindent
13168 The term @emph{applicable ^switches^switches^} reflects the fact that
13169 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
13170 tools, depending on the individual ^switch^switch^.
13172 @command{gnatmake} may invoke the compiler on source files from different
13173 projects. The Project Manager will use the appropriate project file to
13174 determine the @code{Compiler} package for each source file being compiled.
13175 Likewise for the @code{Binder} and @code{Linker} packages.
13177 As an example, consider the following package in a project file:
13179 @smallexample @c projectfile
13180 @group
13181 project Proj1 is
13182    package Compiler is
13183       for ^Default_Switches^Default_Switches^ ("Ada")
13184           use ("^-g^-g^");
13185       for ^Switches^Switches^ ("a.adb")
13186           use ("^-O1^-O1^");
13187       for ^Switches^Switches^ ("b.adb")
13188           use ("^-O2^-O2^",
13189                "^-gnaty^-gnaty^");
13190    end Compiler;
13191 end Proj1;
13192 @end group
13193 @end smallexample
13195 @noindent
13196 If @command{gnatmake} is invoked with this project file, and it needs to
13197 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
13198 @file{a.adb} will be compiled with the ^switch^switch^
13199 @option{^-O1^-O1^},
13200 @file{b.adb} with ^switches^switches^
13201 @option{^-O2^-O2^}
13202 and @option{^-gnaty^-gnaty^},
13203 and @file{c.adb} with @option{^-g^-g^}.
13205 The following example illustrates the ordering of the ^switches^switches^
13206 contributed by different packages:
13208 @smallexample @c projectfile
13209 @group
13210 project Proj2 is
13211    package Builder is
13212       for ^Switches^Switches^ ("main.adb")
13213           use ("^-g^-g^",
13214                "^-O1^-)1^",
13215                "^-f^-f^");
13216    end Builder;
13217 @end group
13219 @group
13220    package Compiler is
13221       for ^Switches^Switches^ ("main.adb")
13222           use ("^-O2^-O2^");
13223    end Compiler;
13224 end Proj2;
13225 @end group
13226 @end smallexample
13228 @noindent
13229 If you issue the command:
13231 @smallexample
13232     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13233 @end smallexample
13235 @noindent
13236 then the compiler will be invoked on @file{main.adb} with the following
13237 sequence of ^switches^switches^
13239 @smallexample
13240    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13241 @end smallexample
13243 with the last @option{^-O^-O^}
13244 ^switch^switch^ having precedence over the earlier ones;
13245 several other ^switches^switches^
13246 (such as @option{^-c^-c^}) are added implicitly.
13248 The ^switches^switches^
13249 @option{^-g^-g^}
13250 and @option{^-O1^-O1^} are contributed by package
13251 @code{Builder},  @option{^-O2^-O2^} is contributed
13252 by the package @code{Compiler}
13253 and @option{^-O0^-O0^} comes from the command line.
13255 The @option{^-g^-g^}
13256 ^switch^switch^ will also be passed in the invocation of
13257 @command{Gnatlink.}
13259 A final example illustrates switch contributions from packages in different
13260 project files:
13262 @smallexample @c projectfile
13263 @group
13264 project Proj3 is
13265    for Source_Files use ("pack.ads", "pack.adb");
13266    package Compiler is
13267       for ^Default_Switches^Default_Switches^ ("Ada")
13268           use ("^-gnata^-gnata^");
13269    end Compiler;
13270 end Proj3;
13271 @end group
13273 @group
13274 with "Proj3";
13275 project Proj4 is
13276    for Source_Files use ("foo_main.adb", "bar_main.adb");
13277    package Builder is
13278       for ^Switches^Switches^ ("foo_main.adb")
13279           use ("^-s^-s^",
13280                "^-g^-g^");
13281    end Builder;
13282 end Proj4;
13283 @end group
13285 @group
13286 -- Ada source file:
13287 with Pack;
13288 procedure Foo_Main is
13289    ...
13290 end Foo_Main;
13291 @end group
13292 @end smallexample
13294 If the command is
13295 @smallexample
13296 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13297 @end smallexample
13299 @noindent
13300 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13301 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13302 @option{^-gnato^-gnato^} (passed on the command line).
13303 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13304 are @option{^-g^-g^} from @code{Proj4.Builder},
13305 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13306 and @option{^-gnato^-gnato^} from the command line.
13308 @noindent
13309 When using @command{gnatmake} with project files, some ^switches^switches^ or
13310 arguments may be expressed as relative paths. As the working directory where
13311 compilation occurs may change, these relative paths are converted to absolute
13312 paths. For the ^switches^switches^ found in a project file, the relative paths
13313 are relative to the project file directory, for the switches on the command
13314 line, they are relative to the directory where @command{gnatmake} is invoked.
13315 The ^switches^switches^ for which this occurs are:
13316 ^-I^-I^,
13317 ^-A^-A^,
13318 ^-L^-L^,
13319 ^-aO^-aO^,
13320 ^-aL^-aL^,
13321 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13322 ^switch^switch^
13323 ^-o^-o^, object files specified in package @code{Linker} or after
13324 -largs on the command line). The exception to this rule is the ^switch^switch^
13325 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13327 @node Specifying Configuration Pragmas
13328 @subsubsection Specifying Configuration Pragmas
13330 When using @command{gnatmake} with project files, if there exists a file
13331 @file{gnat.adc} that contains configuration pragmas, this file will be
13332 ignored.
13334 Configuration pragmas can be defined by means of the following attributes in
13335 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13336 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13338 Both these attributes are single string attributes. Their values is the path
13339 name of a file containing configuration pragmas. If a path name is relative,
13340 then it is relative to the project directory of the project file where the
13341 attribute is defined.
13343 When compiling a source, the configuration pragmas used are, in order,
13344 those listed in the file designated by attribute
13345 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13346 project file, if it is specified, and those listed in the file designated by
13347 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13348 the project file of the source, if it exists.
13350 @node Project Files and Main Subprograms
13351 @subsubsection Project Files and Main Subprograms
13353 @noindent
13354 When using a project file, you can invoke @command{gnatmake}
13355 with one or several main subprograms, by specifying their source files on the
13356 command line.
13358 @smallexample
13359     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13360 @end smallexample
13362 @noindent
13363 Each of these needs to be a source file of the same project, except
13364 when the switch ^-u^/UNIQUE^ is used.
13366 @noindent
13367 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13368 same project, one of the project in the tree rooted at the project specified
13369 on the command line. The package @code{Builder} of this common project, the
13370 "main project" is the one that is considered by @command{gnatmake}.
13372 @noindent
13373 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13374 imported directly or indirectly by the project specified on the command line.
13375 Note that if such a source file is not part of the project specified on the
13376 command line, the ^switches^switches^ found in package @code{Builder} of the
13377 project specified on the command line, if any, that are transmitted
13378 to the compiler will still be used, not those found in the project file of
13379 the source file.
13381 @noindent
13382 When using a project file, you can also invoke @command{gnatmake} without
13383 explicitly specifying any main, and the effect depends on whether you have
13384 defined the @code{Main} attribute.  This attribute has a string list value,
13385 where each element in the list is the name of a source file (the file
13386 extension is optional) that contains a unit that can be a main subprogram.
13388 If the @code{Main} attribute is defined in a project file as a non-empty
13389 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13390 line, then invoking @command{gnatmake} with this project file but without any
13391 main on the command line is equivalent to invoking @command{gnatmake} with all
13392 the file names in the @code{Main} attribute on the command line.
13394 Example:
13395 @smallexample @c projectfile
13396 @group
13397    project Prj is
13398       for Main use ("main1", "main2", "main3");
13399    end Prj;
13400 @end group
13401 @end smallexample
13403 @noindent
13404 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13405 is equivalent to
13406 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13408 When the project attribute @code{Main} is not specified, or is specified
13409 as an empty string list, or when the switch @option{-u} is used on the command
13410 line, then invoking @command{gnatmake} with no main on the command line will
13411 result in all immediate sources of the project file being checked, and
13412 potentially recompiled. Depending on the presence of the switch @option{-u},
13413 sources from other project files on which the immediate sources of the main
13414 project file depend are also checked and potentially recompiled. In other
13415 words, the @option{-u} switch is applied to all of the immediate sources of the
13416 main project file.
13418 When no main is specified on the command line and attribute @code{Main} exists
13419 and includes several mains, or when several mains are specified on the
13420 command line, the default ^switches^switches^ in package @code{Builder} will
13421 be used for all mains, even if there are specific ^switches^switches^
13422 specified for one or several mains.
13424 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13425 the specific ^switches^switches^ for each main, if they are specified.
13427 @node Library Project Files
13428 @subsubsection Library Project Files
13430 @noindent
13431 When @command{gnatmake} is invoked with a main project file that is a library
13432 project file, it is not allowed to specify one or more mains on the command
13433 line.
13435 @noindent
13436 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13437 ^-l^/ACTION=LINK^ have special meanings.
13439 @itemize @bullet
13440 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13441 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13442 library.
13444 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13445 to @command{gnatmake} that the binder generated file should be compiled
13446 (in the case of a stand-alone library) and that the library should be built.
13448 @end itemize
13450 @node The GNAT Driver and Project Files
13451 @subsection The GNAT Driver and Project Files
13453 @noindent
13454 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13455 are project-aware:
13456 @command{^gnatbind^gnatbind^},
13457 @command{^gnatfind^gnatfind^},
13458 @command{^gnatlink^gnatlink^},
13459 @command{^gnatls^gnatls^},
13460 @command{^gnatelim^gnatelim^},
13461 @command{^gnatpp^gnatpp^},
13462 @command{^gnatmetric^gnatmetric^},
13463 @command{^gnatstub^gnatstub^},
13464 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13465 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13466 They must be invoked through the @command{gnat} driver.
13468 The @command{gnat} driver is a front-end that accepts a number of commands and
13469 call the corresponding tool. It has been designed initially for VMS to convert
13470 VMS style qualifiers to Unix style switches, but it is now available to all
13471 the GNAT supported platforms.
13473 On non VMS platforms, the @command{gnat} driver accepts the following commands
13474 (case insensitive):
13476 @itemize @bullet
13477 @item
13478 BIND to invoke @command{^gnatbind^gnatbind^}
13479 @item
13480 CHOP to invoke @command{^gnatchop^gnatchop^}
13481 @item
13482 CLEAN to invoke @command{^gnatclean^gnatclean^}
13483 @item
13484 COMP or COMPILE to invoke the compiler
13485 @item
13486 ELIM to invoke @command{^gnatelim^gnatelim^}
13487 @item
13488 FIND to invoke @command{^gnatfind^gnatfind^}
13489 @item
13490 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13491 @item
13492 LINK to invoke @command{^gnatlink^gnatlink^}
13493 @item
13494 LS or LIST to invoke @command{^gnatls^gnatls^}
13495 @item
13496 MAKE to invoke @command{^gnatmake^gnatmake^}
13497 @item
13498 NAME to invoke @command{^gnatname^gnatname^}
13499 @item
13500 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13501 @item
13502 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13503 @item
13504 METRIC to invoke @command{^gnatmetric^gnatmetric^}
13505 @item
13506 STUB to invoke @command{^gnatstub^gnatstub^}
13507 @item
13508 XREF to invoke @command{^gnatxref^gnatxref^}
13509 @end itemize
13511 @noindent
13512 (note that the compiler is invoked using the command
13513 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13515 @noindent
13516 On non VMS platforms, between @command{gnat} and the command, two
13517 special switches may be used:
13519 @itemize @bullet
13520 @item
13521 @command{-v} to display the invocation of the tool.
13522 @item
13523 @command{-dn} to prevent the @command{gnat} driver from removing
13524 the temporary files it has created. These temporary files are
13525 configuration files and temporary file list files.
13526 @end itemize
13528 @noindent
13529 The command may be followed by switches and arguments for the invoked
13530 tool.
13532 @smallexample
13533   gnat bind -C main.ali
13534   gnat ls -a main
13535   gnat chop foo.txt
13536 @end smallexample
13538 @noindent
13539 Switches may also be put in text files, one switch per line, and the text
13540 files may be specified with their path name preceded by '@@'.
13542 @smallexample
13543    gnat bind @@args.txt main.ali
13544 @end smallexample
13546 @noindent
13547 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13548 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13549 (@option{^-P^/PROJECT_FILE^},
13550 @option{^-X^/EXTERNAL_REFERENCE^} and
13551 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13552 the switches of the invoking tool.
13554 @noindent
13555 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13556 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13557 the immediate sources of the specified project file.
13559 @noindent
13560 When GNAT METRIC is used with a project file, but with no source
13561 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13562 with all the immediate sources of the specified project file and with
13563 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13564 of the project.
13566 @noindent
13567 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13568 a project file, no source is specified on the command line and
13569 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13570 the underlying tool (^gnatpp^gnatpp^ or
13571 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13572 not only for the immediate sources of the main project.
13573 @ifclear vms
13574 (-U stands for Universal or Union of the project files of the project tree)
13575 @end ifclear
13577 @noindent
13578 For each of the following commands, there is optionally a corresponding
13579 package in the main project.
13581 @itemize @bullet
13582 @item
13583 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13585 @item
13586 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13588 @item
13589 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13591 @item
13592 package @code{Eliminate} for command ELIM (invoking
13593 @code{^gnatelim^gnatelim^})
13595 @item
13596 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13598 @item
13599 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13601 @item
13602 package @code{Metrics} for command METRIC
13603 (invoking @code{^gnatmetric^gnatmetric^})
13605 @item
13606 package @code{Pretty_Printer} for command PP or PRETTY
13607 (invoking @code{^gnatpp^gnatpp^})
13609 @item
13610 package @code{Gnatstub} for command STUB
13611 (invoking @code{^gnatstub^gnatstub^})
13613 @item
13614 package @code{Cross_Reference} for command XREF (invoking
13615 @code{^gnatxref^gnatxref^})
13617 @end itemize
13619 @noindent
13620 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13621 a simple variable with a string list value. It contains ^switches^switches^
13622 for the invocation of @code{^gnatls^gnatls^}.
13624 @smallexample @c projectfile
13625 @group
13626 project Proj1 is
13627    package gnatls is
13628       for ^Switches^Switches^
13629           use ("^-a^-a^",
13630                "^-v^-v^");
13631    end gnatls;
13632 end Proj1;
13633 @end group
13634 @end smallexample
13636 @noindent
13637 All other packages have two attribute @code{^Switches^Switches^} and
13638 @code{^Default_Switches^Default_Switches^}.
13640 @noindent
13641 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13642 source file name, that has a string list value: the ^switches^switches^ to be
13643 used when the tool corresponding to the package is invoked for the specific
13644 source file.
13646 @noindent
13647 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13648 indexed by  the programming language that has a string list value.
13649 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13650 ^switches^switches^ for the invocation of the tool corresponding
13651 to the package, except if a specific @code{^Switches^Switches^} attribute
13652 is specified for the source file.
13654 @smallexample @c projectfile
13655 @group
13656 project Proj is
13658    for Source_Dirs use ("./**");
13660    package gnatls is
13661       for ^Switches^Switches^ use
13662           ("^-a^-a^",
13663            "^-v^-v^");
13664    end gnatls;
13665 @end group
13666 @group
13668    package Compiler is
13669       for ^Default_Switches^Default_Switches^ ("Ada")
13670           use ("^-gnatv^-gnatv^",
13671                "^-gnatwa^-gnatwa^");
13672    end Binder;
13673 @end group
13674 @group
13676    package Binder is
13677       for ^Default_Switches^Default_Switches^ ("Ada")
13678           use ("^-C^-C^",
13679                "^-e^-e^");
13680    end Binder;
13681 @end group
13682 @group
13684    package Linker is
13685       for ^Default_Switches^Default_Switches^ ("Ada")
13686           use ("^-C^-C^");
13687       for ^Switches^Switches^ ("main.adb")
13688           use ("^-C^-C^",
13689                "^-v^-v^",
13690                "^-v^-v^");
13691    end Linker;
13692 @end group
13693 @group
13695    package Finder is
13696       for ^Default_Switches^Default_Switches^ ("Ada")
13697            use ("^-a^-a^",
13698                 "^-f^-f^");
13699    end Finder;
13700 @end group
13701 @group
13703    package Cross_Reference is
13704       for ^Default_Switches^Default_Switches^ ("Ada")
13705           use ("^-a^-a^",
13706                "^-f^-f^",
13707                "^-d^-d^",
13708                "^-u^-u^");
13709    end Cross_Reference;
13710 end Proj;
13711 @end group
13712 @end smallexample
13714 @noindent
13715 With the above project file, commands such as
13717 @smallexample
13718    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13719    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13720    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13721    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13722    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13723 @end smallexample
13725 @noindent
13726 will set up the environment properly and invoke the tool with the switches
13727 found in the package corresponding to the tool:
13728 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13729 except @code{^Switches^Switches^ ("main.adb")}
13730 for @code{^gnatlink^gnatlink^}.
13732 @ifclear vms
13733 @node Glide and Project Files
13734 @subsection Glide and Project Files
13736 @noindent
13737 Glide will automatically recognize the @file{.gpr} extension for
13738 project files, and will
13739 convert them to its own internal format automatically. However, it
13740 doesn't provide a syntax-oriented editor for modifying these
13741 files.
13742 The project file will be loaded as text when you select the menu item
13743 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13744 You can edit this text and save the @file{gpr} file;
13745 when you next select this project file in Glide it
13746 will be automatically reloaded.
13747 @end ifclear
13749 @c **********************
13750 @node An Extended Example
13751 @section An Extended Example
13753 @noindent
13754 Suppose that we have two programs, @var{prog1} and @var{prog2},
13755 whose sources are in corresponding directories. We would like
13756 to build them with a single @command{gnatmake} command, and we want to place
13757 their object files into @file{build} subdirectories of the source directories.
13758 Furthermore, we want to have to have two separate subdirectories
13759 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13760 the object files compiled with different set of compilation flags.
13762 In other words, we have the following structure:
13764 @smallexample
13765 @group
13766    main
13767      |- prog1
13768      |    |- build
13769      |         | debug
13770      |         | release
13771      |- prog2
13772           |- build
13773                | debug
13774                | release
13775 @end group
13776 @end smallexample
13778 @noindent
13779 Here are the project files that we must place in a directory @file{main}
13780 to maintain this structure:
13782 @enumerate
13784 @item We create a @code{Common} project with a package @code{Compiler} that
13785 specifies the compilation ^switches^switches^:
13787 @smallexample
13788 File "common.gpr":
13789 @group
13790 @b{project} Common @b{is}
13792    @b{for} Source_Dirs @b{use} (); -- No source files
13793 @end group
13795 @group
13796    @b{type} Build_Type @b{is} ("release", "debug");
13797    Build : Build_Type := External ("BUILD", "debug");
13798 @end group
13799 @group
13800    @b{package} Compiler @b{is}
13801       @b{case} Build @b{is}
13802          @b{when} "release" =>
13803            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13804                    @b{use} ("^-O2^-O2^");
13805          @b{when} "debug"   =>
13806            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13807                    @b{use} ("^-g^-g^");
13808       @b{end case};
13809    @b{end} Compiler;
13811 @b{end} Common;
13812 @end group
13813 @end smallexample
13815 @item We create separate projects for the two programs:
13817 @smallexample
13818 @group
13819 File "prog1.gpr":
13821 @b{with} "common";
13822 @b{project} Prog1 @b{is}
13824     @b{for} Source_Dirs @b{use} ("prog1");
13825     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13827     @b{package} Compiler @b{renames} Common.Compiler;
13829 @b{end} Prog1;
13830 @end group
13831 @end smallexample
13833 @smallexample
13834 @group
13835 File "prog2.gpr":
13837 @b{with} "common";
13838 @b{project} Prog2 @b{is}
13840     @b{for} Source_Dirs @b{use} ("prog2");
13841     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13843     @b{package} Compiler @b{renames} Common.Compiler;
13845 @end group
13846 @b{end} Prog2;
13847 @end smallexample
13849 @item We create a wrapping project @code{Main}:
13851 @smallexample
13852 @group
13853 File "main.gpr":
13855 @b{with} "common";
13856 @b{with} "prog1";
13857 @b{with} "prog2";
13858 @b{project} Main @b{is}
13860    @b{package} Compiler @b{renames} Common.Compiler;
13862 @b{end} Main;
13863 @end group
13864 @end smallexample
13866 @item Finally we need to create a dummy procedure that @code{with}s (either
13867 explicitly or implicitly) all the sources of our two programs.
13869 @end enumerate
13871 @noindent
13872 Now we can build the programs using the command
13874 @smallexample
13875    gnatmake ^-P^/PROJECT_FILE=^main dummy
13876 @end smallexample
13878 @noindent
13879 for the Debug mode, or
13881 @ifclear vms
13882 @smallexample
13883    gnatmake -Pmain -XBUILD=release
13884 @end smallexample
13885 @end ifclear
13887 @ifset vms
13888 @smallexample
13889    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13890 @end smallexample
13891 @end ifset
13893 @noindent
13894 for the Release mode.
13896 @c ********************************
13897 @c * Project File Complete Syntax *
13898 @c ********************************
13900 @node Project File Complete Syntax
13901 @section Project File Complete Syntax
13903 @smallexample
13904 project ::=
13905   context_clause project_declaration
13907 context_clause ::=
13908   @{with_clause@}
13910 with_clause ::=
13911   @b{with} path_name @{ , path_name @} ;
13913 path_name ::=
13914    string_literal
13916 project_declaration ::=
13917   simple_project_declaration | project_extension
13919 simple_project_declaration ::=
13920   @b{project} <project_>simple_name @b{is}
13921     @{declarative_item@}
13922   @b{end} <project_>simple_name;
13924 project_extension ::=
13925   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13926     @{declarative_item@}
13927   @b{end} <project_>simple_name;
13929 declarative_item ::=
13930   package_declaration |
13931   typed_string_declaration |
13932   other_declarative_item
13934 package_declaration ::=
13935   package_specification | package_renaming
13937 package_specification ::=
13938   @b{package} package_identifier @b{is}
13939     @{simple_declarative_item@}
13940   @b{end} package_identifier ;
13942 package_identifier ::=
13943   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13944   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13945   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13947 package_renaming ::==
13948   @b{package} package_identifier @b{renames}
13949        <project_>simple_name.package_identifier ;
13951 typed_string_declaration ::=
13952   @b{type} <typed_string_>_simple_name @b{is}
13953    ( string_literal @{, string_literal@} );
13955 other_declarative_item ::=
13956   attribute_declaration |
13957   typed_variable_declaration |
13958   variable_declaration |
13959   case_construction
13961 attribute_declaration ::=
13962   full_associative_array_declaration |
13963   @b{for} attribute_designator @b{use} expression ;
13965 full_associative_array_declaration ::=
13966   @b{for} <associative_array_attribute_>simple_name @b{use}
13967   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13969 attribute_designator ::=
13970   <simple_attribute_>simple_name |
13971   <associative_array_attribute_>simple_name ( string_literal )
13973 typed_variable_declaration ::=
13974   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13976 variable_declaration ::=
13977   <variable_>simple_name := expression;
13979 expression ::=
13980   term @{& term@}
13982 term ::=
13983   literal_string |
13984   string_list |
13985   <variable_>name |
13986   external_value |
13987   attribute_reference
13989 string_literal ::=
13990   (same as Ada)
13992 string_list ::=
13993   ( <string_>expression @{ , <string_>expression @} )
13995 external_value ::=
13996   @b{external} ( string_literal [, string_literal] )
13998 attribute_reference ::=
13999   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
14001 attribute_prefix ::=
14002   @b{project} |
14003   <project_>simple_name | package_identifier |
14004   <project_>simple_name . package_identifier
14006 case_construction ::=
14007   @b{case} <typed_variable_>name @b{is}
14008     @{case_item@}
14009   @b{end case} ;
14011 case_item ::=
14012   @b{when} discrete_choice_list =>
14013       @{case_construction | attribute_declaration@}
14015 discrete_choice_list ::=
14016   string_literal @{| string_literal@} |
14017   @b{others}
14019 name ::=
14020   simple_name @{. simple_name@}
14022 simple_name ::=
14023   identifier (same as Ada)
14025 @end smallexample
14027 @node The Cross-Referencing Tools gnatxref and gnatfind
14028 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
14029 @findex gnatxref
14030 @findex gnatfind
14032 @noindent
14033 The compiler generates cross-referencing information (unless
14034 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
14035 This information indicates where in the source each entity is declared and
14036 referenced. Note that entities in package Standard are not included, but
14037 entities in all other predefined units are included in the output.
14039 Before using any of these two tools, you need to compile successfully your
14040 application, so that GNAT gets a chance to generate the cross-referencing
14041 information.
14043 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
14044 information to provide the user with the capability to easily locate the
14045 declaration and references to an entity. These tools are quite similar,
14046 the difference being that @code{gnatfind} is intended for locating
14047 definitions and/or references to a specified entity or entities, whereas
14048 @code{gnatxref} is oriented to generating a full report of all
14049 cross-references.
14051 To use these tools, you must not compile your application using the
14052 @option{-gnatx} switch on the @command{gnatmake} command line
14053 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
14054 information will not be generated.
14056 @menu
14057 * gnatxref Switches::
14058 * gnatfind Switches::
14059 * Project Files for gnatxref and gnatfind::
14060 * Regular Expressions in gnatfind and gnatxref::
14061 * Examples of gnatxref Usage::
14062 * Examples of gnatfind Usage::
14063 @end menu
14065 @node gnatxref Switches
14066 @section @code{gnatxref} Switches
14068 @noindent
14069 The command invocation for @code{gnatxref} is:
14070 @smallexample
14071 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
14072 @end smallexample
14074 @noindent
14075 where
14077 @table @code
14078 @item sourcefile1, sourcefile2
14079 identifies the source files for which a report is to be generated. The
14080 ``with''ed units will be processed too. You must provide at least one file.
14082 These file names are considered to be regular expressions, so for instance
14083 specifying @file{source*.adb} is the same as giving every file in the current
14084 directory whose name starts with @file{source} and whose extension is
14085 @file{adb}.
14087 You shouldn't specify any directory name, just base names. @command{gnatxref}
14088 and @command{gnatfind} will be able to locate these files by themselves using
14089 the source path. If you specify directories, no result is produced.
14091 @end table
14093 @noindent
14094 The switches can be :
14095 @table @option
14096 @c !sort!
14097 @item ^-a^/ALL_FILES^
14098 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
14099 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14100 the read-only files found in the library search path. Otherwise, these files
14101 will be ignored. This option can be used to protect Gnat sources or your own
14102 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14103 much faster, and their output much smaller. Read-only here refers to access
14104 or permissions status in the file system for the current user.
14106 @item -aIDIR
14107 @cindex @option{-aIDIR} (@command{gnatxref})
14108 When looking for source files also look in directory DIR. The order in which
14109 source file search is undertaken is the same as for @command{gnatmake}.
14111 @item -aODIR
14112 @cindex @option{-aODIR} (@command{gnatxref})
14113 When searching for library and object files, look in directory
14114 DIR. The order in which library files are searched is the same as for
14115 @command{gnatmake}.
14117 @item -nostdinc
14118 @cindex @option{-nostdinc} (@command{gnatxref})
14119 Do not look for sources in the system default directory.
14121 @item -nostdlib
14122 @cindex @option{-nostdlib} (@command{gnatxref})
14123 Do not look for library files in the system default directory.
14125 @item --RTS=@var{rts-path}
14126 @cindex @option{--RTS} (@command{gnatxref})
14127 Specifies the default location of the runtime library. Same meaning as the
14128 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14130 @item ^-d^/DERIVED_TYPES^
14131 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
14132 If this switch is set @code{gnatxref} will output the parent type
14133 reference for each matching derived types.
14135 @item ^-f^/FULL_PATHNAME^
14136 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
14137 If this switch is set, the output file names will be preceded by their
14138 directory (if the file was found in the search path). If this switch is
14139 not set, the directory will not be printed.
14141 @item ^-g^/IGNORE_LOCALS^
14142 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
14143 If this switch is set, information is output only for library-level
14144 entities, ignoring local entities. The use of this switch may accelerate
14145 @code{gnatfind} and @code{gnatxref}.
14147 @item -IDIR
14148 @cindex @option{-IDIR} (@command{gnatxref})
14149 Equivalent to @samp{-aODIR -aIDIR}.
14151 @item -pFILE
14152 @cindex @option{-pFILE} (@command{gnatxref})
14153 Specify a project file to use @xref{Project Files}. These project files are
14154 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
14155 project files, you should use gnatxref through the GNAT driver
14156 (@command{gnat xref -Pproject}).
14158 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14159 project file in the current directory.
14161 If a project file is either specified or found by the tools, then the content
14162 of the source directory and object directory lines are added as if they
14163 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
14164 and @samp{^-aO^OBJECT_SEARCH^}.
14165 @item ^-u^/UNUSED^
14166 Output only unused symbols. This may be really useful if you give your
14167 main compilation unit on the command line, as @code{gnatxref} will then
14168 display every unused entity and 'with'ed package.
14170 @ifclear vms
14171 @item -v
14172 Instead of producing the default output, @code{gnatxref} will generate a
14173 @file{tags} file that can be used by vi. For examples how to use this
14174 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
14175 to the standard output, thus you will have to redirect it to a file.
14176 @end ifclear
14178 @end table
14180 @noindent
14181 All these switches may be in any order on the command line, and may even
14182 appear after the file names. They need not be separated by spaces, thus
14183 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14184 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14186 @node gnatfind Switches
14187 @section @code{gnatfind} Switches
14189 @noindent
14190 The command line for @code{gnatfind} is:
14192 @smallexample
14193 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
14194       [file1 file2 ...]
14195 @end smallexample
14197 @noindent
14198 where
14200 @table @code
14201 @item pattern
14202 An entity will be output only if it matches the regular expression found
14203 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
14205 Omitting the pattern is equivalent to specifying @samp{*}, which
14206 will match any entity. Note that if you do not provide a pattern, you
14207 have to provide both a sourcefile and a line.
14209 Entity names are given in Latin-1, with uppercase/lowercase equivalence
14210 for matching purposes. At the current time there is no support for
14211 8-bit codes other than Latin-1, or for wide characters in identifiers.
14213 @item sourcefile
14214 @code{gnatfind} will look for references, bodies or declarations
14215 of symbols referenced in @file{sourcefile}, at line @samp{line}
14216 and column @samp{column}. See @ref{Examples of gnatfind Usage}
14217 for syntax examples.
14219 @item line
14220 is a decimal integer identifying the line number containing
14221 the reference to the entity (or entities) to be located.
14223 @item column
14224 is a decimal integer identifying the exact location on the
14225 line of the first character of the identifier for the
14226 entity reference. Columns are numbered from 1.
14228 @item file1 file2 ...
14229 The search will be restricted to these source files. If none are given, then
14230 the search will be done for every library file in the search path.
14231 These file must appear only after the pattern or sourcefile.
14233 These file names are considered to be regular expressions, so for instance
14234 specifying 'source*.adb' is the same as giving every file in the current
14235 directory whose name starts with 'source' and whose extension is 'adb'.
14237 The location of the spec of the entity will always be displayed, even if it
14238 isn't in one of file1, file2,... The occurrences of the entity in the
14239 separate units of the ones given on the command line will also be displayed.
14241 Note that if you specify at least one file in this part, @code{gnatfind} may
14242 sometimes not be able to find the body of the subprograms...
14244 @end table
14246 @noindent
14247 At least one of 'sourcefile' or 'pattern' has to be present on
14248 the command line.
14250 The following switches are available:
14251 @table @option
14252 @c !sort!
14254 @item ^-a^/ALL_FILES^
14255 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14256 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14257 the read-only files found in the library search path. Otherwise, these files
14258 will be ignored. This option can be used to protect Gnat sources or your own
14259 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14260 much faster, and their output much smaller. Read-only here refers to access
14261 or permission status in the file system for the current user.
14263 @item -aIDIR
14264 @cindex @option{-aIDIR} (@command{gnatfind})
14265 When looking for source files also look in directory DIR. The order in which
14266 source file search is undertaken is the same as for @command{gnatmake}.
14268 @item -aODIR
14269 @cindex @option{-aODIR} (@command{gnatfind})
14270 When searching for library and object files, look in directory
14271 DIR. The order in which library files are searched is the same as for
14272 @command{gnatmake}.
14274 @item -nostdinc
14275 @cindex @option{-nostdinc} (@command{gnatfind})
14276 Do not look for sources in the system default directory.
14278 @item -nostdlib
14279 @cindex @option{-nostdlib} (@command{gnatfind})
14280 Do not look for library files in the system default directory.
14282 @item --RTS=@var{rts-path}
14283 @cindex @option{--RTS} (@command{gnatfind})
14284 Specifies the default location of the runtime library. Same meaning as the
14285 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14287 @item ^-d^/DERIVED_TYPE_INFORMATION^
14288 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14289 If this switch is set, then @code{gnatfind} will output the parent type
14290 reference for each matching derived types.
14292 @item ^-e^/EXPRESSIONS^
14293 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14294 By default, @code{gnatfind} accept the simple regular expression set for
14295 @samp{pattern}. If this switch is set, then the pattern will be
14296 considered as full Unix-style regular expression.
14298 @item ^-f^/FULL_PATHNAME^
14299 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14300 If this switch is set, the output file names will be preceded by their
14301 directory (if the file was found in the search path). If this switch is
14302 not set, the directory will not be printed.
14304 @item ^-g^/IGNORE_LOCALS^
14305 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14306 If this switch is set, information is output only for library-level
14307 entities, ignoring local entities. The use of this switch may accelerate
14308 @code{gnatfind} and @code{gnatxref}.
14310 @item -IDIR
14311 @cindex @option{-IDIR} (@command{gnatfind})
14312 Equivalent to @samp{-aODIR -aIDIR}.
14314 @item -pFILE
14315 @cindex @option{-pFILE} (@command{gnatfind})
14316 Specify a project file (@pxref{Project Files}) to use.
14317 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14318 project file in the current directory.
14320 If a project file is either specified or found by the tools, then the content
14321 of the source directory and object directory lines are added as if they
14322 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14323 @samp{^-aO^/OBJECT_SEARCH^}.
14325 @item ^-r^/REFERENCES^
14326 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14327 By default, @code{gnatfind} will output only the information about the
14328 declaration, body or type completion of the entities. If this switch is
14329 set, the @code{gnatfind} will locate every reference to the entities in
14330 the files specified on the command line (or in every file in the search
14331 path if no file is given on the command line).
14333 @item ^-s^/PRINT_LINES^
14334 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14335 If this switch is set, then @code{gnatfind} will output the content
14336 of the Ada source file lines were the entity was found.
14338 @item ^-t^/TYPE_HIERARCHY^
14339 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14340 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14341 the specified type. It act like -d option but recursively from parent
14342 type to parent type. When this switch is set it is not possible to
14343 specify more than one file.
14345 @end table
14347 @noindent
14348 All these switches may be in any order on the command line, and may even
14349 appear after the file names. They need not be separated by spaces, thus
14350 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14351 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14353 As stated previously, gnatfind will search in every directory in the
14354 search path. You can force it to look only in the current directory if
14355 you specify @code{*} at the end of the command line.
14357 @node Project Files for gnatxref and gnatfind
14358 @section Project Files for @command{gnatxref} and @command{gnatfind}
14360 @noindent
14361 Project files allow a programmer to specify how to compile its
14362 application, where to find sources, etc.  These files are used
14363 @ifclear vms
14364 primarily by the Glide Ada mode, but they can also be used
14365 @end ifclear
14366 by the two tools
14367 @code{gnatxref} and @code{gnatfind}.
14369 A project file name must end with @file{.gpr}. If a single one is
14370 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14371 extract the information from it. If multiple project files are found, none of
14372 them is read, and you have to use the @samp{-p} switch to specify the one
14373 you want to use.
14375 The following lines can be included, even though most of them have default
14376 values which can be used in most cases.
14377 The lines can be entered in any order in the file.
14378 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14379 each line. If you have multiple instances, only the last one is taken into
14380 account.
14382 @table @code
14383 @item src_dir=DIR
14384 [default: @code{"^./^[]^"}]
14385 specifies a directory where to look for source files. Multiple @code{src_dir}
14386 lines can be specified and they will be searched in the order they
14387 are specified.
14389 @item obj_dir=DIR
14390 [default: @code{"^./^[]^"}]
14391 specifies a directory where to look for object and library files. Multiple
14392 @code{obj_dir} lines can be specified, and they will be searched in the order
14393 they are specified
14395 @item comp_opt=SWITCHES
14396 [default: @code{""}]
14397 creates a variable which can be referred to subsequently by using
14398 the @code{$@{comp_opt@}} notation. This is intended to store the default
14399 switches given to @command{gnatmake} and @command{gcc}.
14401 @item bind_opt=SWITCHES
14402 [default: @code{""}]
14403 creates a variable which can be referred to subsequently by using
14404 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14405 switches given to @command{gnatbind}.
14407 @item link_opt=SWITCHES
14408 [default: @code{""}]
14409 creates a variable which can be referred to subsequently by using
14410 the @samp{$@{link_opt@}} notation. This is intended to store the default
14411 switches given to @command{gnatlink}.
14413 @item main=EXECUTABLE
14414 [default: @code{""}]
14415 specifies the name of the executable for the application. This variable can
14416 be referred to in the following lines by using the @samp{$@{main@}} notation.
14418 @ifset vms
14419 @item comp_cmd=COMMAND
14420 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14421 @end ifset
14422 @ifclear vms
14423 @item comp_cmd=COMMAND
14424 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14425 @end ifclear
14426 specifies the command used to compile a single file in the application.
14428 @ifset vms
14429 @item make_cmd=COMMAND
14430 [default: @code{"GNAT MAKE $@{main@}
14431 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14432 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14433 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14434 @end ifset
14435 @ifclear vms
14436 @item make_cmd=COMMAND
14437 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14438  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14439  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14440 @end ifclear
14441 specifies the command used to recompile the whole application.
14443 @item run_cmd=COMMAND
14444 [default: @code{"$@{main@}"}]
14445 specifies the command used to run the application.
14447 @item debug_cmd=COMMAND
14448 [default: @code{"gdb $@{main@}"}]
14449 specifies the command used to debug the application
14451 @end table
14453 @noindent
14454 @command{gnatxref} and @command{gnatfind} only take into account the
14455 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14457 @node Regular Expressions in gnatfind and gnatxref
14458 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14460 @noindent
14461 As specified in the section about @command{gnatfind}, the pattern can be a
14462 regular expression. Actually, there are to set of regular expressions
14463 which are recognized by the program :
14465 @table @code
14466 @item globbing patterns
14467 These are the most usual regular expression. They are the same that you
14468 generally used in a Unix shell command line, or in a DOS session.
14470 Here is a more formal grammar :
14471 @smallexample
14472 @group
14473 @iftex
14474 @leftskip=.5cm
14475 @end iftex
14476 regexp ::= term
14477 term   ::= elmt            -- matches elmt
14478 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14479 term   ::= *               -- any string of 0 or more characters
14480 term   ::= ?               -- matches any character
14481 term   ::= [char @{char@}] -- matches any character listed
14482 term   ::= [char - char]   -- matches any character in range
14483 @end group
14484 @end smallexample
14486 @item full regular expression
14487 The second set of regular expressions is much more powerful. This is the
14488 type of regular expressions recognized by utilities such a @file{grep}.
14490 The following is the form of a regular expression, expressed in Ada
14491 reference manual style BNF is as follows
14493 @smallexample
14494 @iftex
14495 @leftskip=.5cm
14496 @end iftex
14497 @group
14498 regexp ::= term @{| term@} -- alternation (term or term ...)
14500 term ::= item @{item@}     -- concatenation (item then item)
14502 item ::= elmt              -- match elmt
14503 item ::= elmt *            -- zero or more elmt's
14504 item ::= elmt +            -- one or more elmt's
14505 item ::= elmt ?            -- matches elmt or nothing
14506 @end group
14507 @group
14508 elmt ::= nschar            -- matches given character
14509 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14510 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14511 elmt ::= [char - char]     -- matches chars in given range
14512 elmt ::= \ char            -- matches given character
14513 elmt ::= .                 -- matches any single character
14514 elmt ::= ( regexp )        -- parens used for grouping
14516 char ::= any character, including special characters
14517 nschar ::= any character except ()[].*+?^^^
14518 @end group
14519 @end smallexample
14521 Following are a few examples :
14523 @table @samp
14524 @item abcde|fghi
14525 will match any of the two strings 'abcde' and 'fghi'.
14527 @item abc*d
14528 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14530 @item [a-z]+
14531 will match any string which has only lowercase characters in it (and at
14532 least one character
14534 @end table
14535 @end table
14537 @node Examples of gnatxref Usage
14538 @section Examples of @code{gnatxref} Usage
14540 @subsection General Usage
14542 @noindent
14543 For the following examples, we will consider the following units :
14545 @smallexample @c ada
14546 @group
14547 @cartouche
14548 main.ads:
14549 1: with Bar;
14550 2: package Main is
14551 3:     procedure Foo (B : in Integer);
14552 4:     C : Integer;
14553 5: private
14554 6:     D : Integer;
14555 7: end Main;
14557 main.adb:
14558 1: package body Main is
14559 2:     procedure Foo (B : in Integer) is
14560 3:     begin
14561 4:        C := B;
14562 5:        D := B;
14563 6:        Bar.Print (B);
14564 7:        Bar.Print (C);
14565 8:     end Foo;
14566 9: end Main;
14568 bar.ads:
14569 1: package Bar is
14570 2:     procedure Print (B : Integer);
14571 3: end bar;
14572 @end cartouche
14573 @end group
14574 @end smallexample
14576 @table @code
14578 @noindent
14579 The first thing to do is to recompile your application (for instance, in
14580 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14581 the cross-referencing information.
14582 You can then issue any of the following commands:
14584 @item gnatxref main.adb
14585 @code{gnatxref} generates cross-reference information for main.adb
14586 and every unit 'with'ed by main.adb.
14588 The output would be:
14589 @smallexample
14590 @iftex
14591 @leftskip=0cm
14592 @end iftex
14593 B                                                      Type: Integer
14594   Decl: bar.ads           2:22
14595 B                                                      Type: Integer
14596   Decl: main.ads          3:20
14597   Body: main.adb          2:20
14598   Ref:  main.adb          4:13     5:13     6:19
14599 Bar                                                    Type: Unit
14600   Decl: bar.ads           1:9
14601   Ref:  main.adb          6:8      7:8
14602        main.ads           1:6
14603 C                                                      Type: Integer
14604   Decl: main.ads          4:5
14605   Modi: main.adb          4:8
14606   Ref:  main.adb          7:19
14607 D                                                      Type: Integer
14608   Decl: main.ads          6:5
14609   Modi: main.adb          5:8
14610 Foo                                                    Type: Unit
14611   Decl: main.ads          3:15
14612   Body: main.adb          2:15
14613 Main                                                    Type: Unit
14614   Decl: main.ads          2:9
14615   Body: main.adb          1:14
14616 Print                                                   Type: Unit
14617   Decl: bar.ads           2:15
14618   Ref:  main.adb          6:12     7:12
14619 @end smallexample
14621 @noindent
14622 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14623 its body is in main.adb, line 1, column 14 and is not referenced any where.
14625 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14626 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14628 @item gnatxref package1.adb package2.ads
14629 @code{gnatxref} will generates cross-reference information for
14630 package1.adb, package2.ads and any other package 'with'ed by any
14631 of these.
14633 @end table
14635 @ifclear vms
14636 @subsection Using gnatxref with vi
14638 @code{gnatxref} can generate a tags file output, which can be used
14639 directly from @file{vi}. Note that the standard version of @file{vi}
14640 will not work properly with overloaded symbols. Consider using another
14641 free implementation of @file{vi}, such as @file{vim}.
14643 @smallexample
14644 $ gnatxref -v gnatfind.adb > tags
14645 @end smallexample
14647 @noindent
14648 will generate the tags file for @code{gnatfind} itself (if the sources
14649 are in the search path!).
14651 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14652 (replacing @i{entity} by whatever you are looking for), and vi will
14653 display a new file with the corresponding declaration of entity.
14654 @end ifclear
14656 @node Examples of gnatfind Usage
14657 @section Examples of @code{gnatfind} Usage
14659 @table @code
14661 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14662 Find declarations for all entities xyz referenced at least once in
14663 main.adb. The references are search in every library file in the search
14664 path.
14666 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14667 switch is set)
14669 The output will look like:
14670 @smallexample
14671 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14672 ^directory/^[directory]^main.adb:24:10: xyz <= body
14673 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14674 @end smallexample
14676 @noindent
14677 that is to say, one of the entities xyz found in main.adb is declared at
14678 line 12 of main.ads (and its body is in main.adb), and another one is
14679 declared at line 45 of foo.ads
14681 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14682 This is the same command as the previous one, instead @code{gnatfind} will
14683 display the content of the Ada source file lines.
14685 The output will look like:
14687 @smallexample
14688 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14689    procedure xyz;
14690 ^directory/^[directory]^main.adb:24:10: xyz <= body
14691    procedure xyz is
14692 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14693    xyz : Integer;
14694 @end smallexample
14696 @noindent
14697 This can make it easier to find exactly the location your are looking
14698 for.
14700 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14701 Find references to all entities containing an x that are
14702 referenced on line 123 of main.ads.
14703 The references will be searched only in main.ads and foo.adb.
14705 @item gnatfind main.ads:123
14706 Find declarations and bodies for all entities that are referenced on
14707 line 123 of main.ads.
14709 This is the same as @code{gnatfind "*":main.adb:123}.
14711 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14712 Find the declaration for the entity referenced at column 45 in
14713 line 123 of file main.adb in directory mydir. Note that it
14714 is usual to omit the identifier name when the column is given,
14715 since the column position identifies a unique reference.
14717 The column has to be the beginning of the identifier, and should not
14718 point to any character in the middle of the identifier.
14720 @end table
14722 @c *********************************
14723 @node The GNAT Pretty-Printer gnatpp
14724 @chapter The GNAT Pretty-Printer @command{gnatpp}
14725 @findex gnatpp
14726 @cindex Pretty-Printer
14728 @noindent
14729 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14730 for source reformatting / pretty-printing.
14731 It takes an Ada source file as input and generates a reformatted
14732 version as output.
14733 You can specify various style directives via switches; e.g.,
14734 identifier case conventions, rules of indentation, and comment layout.
14736 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14737 tree for the input source and thus requires the input to be syntactically and
14738 semantically legal.
14739 If this condition is not met, @command{gnatpp} will terminate with an
14740 error message; no output file will be generated.
14742 If the compilation unit
14743 contained in the input source depends semantically upon units located
14744 outside the current directory, you have to provide the source search path
14745 when invoking @command{gnatpp}, if these units are contained in files with
14746 names that do not follow the GNAT file naming rules, you have to provide
14747 the configuration file describing the corresponding naming scheme;
14748 see the description of the @command{gnatpp}
14749 switches below. Another possibility is to use a project file and to
14750 call @command{gnatpp} through the @command{gnat} driver
14752 The @command{gnatpp} command has the form
14754 @smallexample
14755 $ gnatpp [@var{switches}] @var{filename}
14756 @end smallexample
14758 @noindent
14759 where
14760 @itemize @bullet
14761 @item
14762 @var{switches} is an optional sequence of switches defining such properties as
14763 the formatting rules, the source search path, and the destination for the
14764 output source file
14766 @item
14767 @var{filename} is the name (including the extension) of the source file to
14768 reformat; ``wildcards'' or several file names on the same gnatpp command are
14769 allowed.  The file name may contain path information; it does not have to
14770 follow the GNAT file naming rules
14771 @end itemize
14773 @menu
14774 * Switches for gnatpp::
14775 * Formatting Rules::
14776 @end menu
14778 @node Switches for gnatpp
14779 @section Switches for @command{gnatpp}
14781 @noindent
14782 The following subsections describe the various switches accepted by
14783 @command{gnatpp}, organized by category.
14785 @ifclear vms
14786 You specify a switch by supplying a name and generally also a value.
14787 In many cases the values for a switch with a given name are incompatible with
14788 each other
14789 (for example the switch that controls the casing of a reserved word may have
14790 exactly one value: upper case, lower case, or
14791 mixed case) and thus exactly one such switch can be in effect for an
14792 invocation of @command{gnatpp}.
14793 If more than one is supplied, the last one is used.
14794 However, some values for the same switch are mutually compatible.
14795 You may supply several such switches to @command{gnatpp}, but then
14796 each must be specified in full, with both the name and the value.
14797 Abbreviated forms (the name appearing once, followed by each value) are
14798 not permitted.
14799 For example, to set
14800 the alignment of the assignment delimiter both in declarations and in
14801 assignment statements, you must write @option{-A2A3}
14802 (or @option{-A2 -A3}), but not @option{-A23}.
14803 @end ifclear
14805 @ifset vms
14806 In many cases the set of options for a given qualifier are incompatible with
14807 each other (for example the qualifier that controls the casing of a reserved
14808 word may have exactly one option, which specifies either upper case, lower
14809 case, or mixed case), and thus exactly one such option can be in effect for
14810 an invocation of @command{gnatpp}.
14811 If more than one is supplied, the last one is used.
14812 However, some qualifiers have options that are mutually compatible,
14813 and then you may then supply several such options when invoking
14814 @command{gnatpp}.
14815 @end ifset
14817 In most cases, it is obvious whether or not the
14818 ^values for a switch with a given name^options for a given qualifier^
14819 are compatible with each other.
14820 When the semantics might not be evident, the summaries below explicitly
14821 indicate the effect.
14823 @menu
14824 * Alignment Control::
14825 * Casing Control::
14826 * Construct Layout Control::
14827 * General Text Layout Control::
14828 * Other Formatting Options::
14829 * Setting the Source Search Path::
14830 * Output File Control::
14831 * Other gnatpp Switches::
14832 @end menu
14834 @node Alignment Control
14835 @subsection Alignment Control
14836 @cindex Alignment control in @command{gnatpp}
14838 @noindent
14839 Programs can be easier to read if certain constructs are vertically aligned.
14840 By default all alignments are set ON.
14841 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14842 OFF, and then use one or more of the other
14843 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14844 to activate alignment for specific constructs.
14846 @table @option
14847 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14849 @ifset vms
14850 @item /ALIGN=ON
14851 Set all alignments to ON
14852 @end ifset
14854 @item ^-A0^/ALIGN=OFF^
14855 Set all alignments to OFF
14857 @item ^-A1^/ALIGN=COLONS^
14858 Align @code{:} in declarations
14860 @item ^-A2^/ALIGN=DECLARATIONS^
14861 Align @code{:=} in initializations in declarations
14863 @item ^-A3^/ALIGN=STATEMENTS^
14864 Align @code{:=} in assignment statements
14866 @item ^-A4^/ALIGN=ARROWS^
14867 Align @code{=>} in associations
14869 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
14870 Align @code{at} keywords in the component clauses in record
14871 representation clauses
14872 @end table
14874 @noindent
14875 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14876 is allowed.
14878 @node Casing Control
14879 @subsection Casing Control
14880 @cindex Casing control in @command{gnatpp}
14882 @noindent
14883 @command{gnatpp} allows you to specify the casing for reserved words,
14884 pragma names, attribute designators and identifiers.
14885 For identifiers you may define a
14886 general rule for name casing but also override this rule
14887 via a set of dictionary files.
14889 Three types of casing are supported: lower case, upper case, and mixed case.
14890 Lower and upper case are self-explanatory (but since some letters in
14891 Latin1 and other GNAT-supported character sets
14892 exist only in lower-case form, an upper case conversion will have no
14893 effect on them.)
14894 ``Mixed case'' means that the first letter, and also each letter immediately
14895 following an underscore, are converted to their uppercase forms;
14896 all the other letters are converted to their lowercase forms.
14898 @table @option
14899 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14900 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14901 Attribute designators are lower case
14903 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14904 Attribute designators are upper case
14906 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14907 Attribute designators are mixed case (this is the default)
14909 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14910 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14911 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14912 lower case (this is the default)
14914 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14915 Keywords are upper case
14917 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14918 @item ^-nD^/NAME_CASING=AS_DECLARED^
14919 Name casing for defining occurrences are as they appear in the source file
14920 (this is the default)
14922 @item ^-nU^/NAME_CASING=UPPER_CASE^
14923 Names are in upper case
14925 @item ^-nL^/NAME_CASING=LOWER_CASE^
14926 Names are in lower case
14928 @item ^-nM^/NAME_CASING=MIXED_CASE^
14929 Names are in mixed case
14931 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14932 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14933 Pragma names are lower case
14935 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14936 Pragma names are upper case
14938 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14939 Pragma names are mixed case (this is the default)
14941 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14942 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14943 Use @var{file} as a @emph{dictionary file} that defines
14944 the casing for a set of specified names,
14945 thereby overriding the effect on these names by
14946 any explicit or implicit
14947 ^-n^/NAME_CASING^ switch.
14948 To supply more than one dictionary file,
14949 use ^several @option{-D} switches^a list of files as options^.
14951 @noindent
14952 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14953 to define the casing for the Ada predefined names and
14954 the names declared in the GNAT libraries.
14956 @item ^-D-^/SPECIFIC_CASING^
14957 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14958 Do not use the default dictionary file;
14959 instead, use the casing
14960 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14961 dictionary file(s)
14962 @end table
14964 @noindent
14965 The structure of a dictionary file, and details on the conventions
14966 used in the default dictionary file, are defined in @ref{Name Casing}.
14968 The @option{^-D-^/SPECIFIC_CASING^} and
14969 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14970 compatible.
14972 @node Construct Layout Control
14973 @subsection Construct Layout Control
14974 @cindex Layout control in @command{gnatpp}
14976 @noindent
14977 This group of @command{gnatpp} switches controls the layout of comments and
14978 complex syntactic constructs.  See @ref{Formatting Comments} for details
14979 on their effect.
14981 @table @option
14982 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14983 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14984 All the comments remain unchanged
14986 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14987 GNAT-style comment line indentation (this is the default).
14989 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14990 Reference-manual comment line indentation.
14992 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14993 GNAT-style comment beginning
14995 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14996 Reformat comment blocks
14998 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14999 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
15000 GNAT-style layout (this is the default)
15002 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
15003 Compact layout
15005 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
15006 Uncompact layout
15008 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
15009 @item ^-N^/NOTABS^
15010 All the VT characters are removed from the comment text. All the HT characters
15011 are expanded with the sequences of space characters to get to the next tab
15012 stops.
15014 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
15015 @item ^--no-separate-is^/NO_SEPARATE_IS^
15016 Do not place the keyword @code{is} on a separate line in a subprogram body in
15017 case if the specification occupies more then one line.
15019 @end table
15021 @ifclear vms
15022 @noindent
15023 The @option{-c1} and @option{-c2} switches are incompatible.
15024 The @option{-c3} and @option{-c4} switches are compatible with each other and
15025 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
15026 the other comment formatting switches.
15028 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
15029 @end ifclear
15031 @ifset vms
15032 @noindent
15033 For the @option{/COMMENTS_LAYOUT} qualifier:
15034 @itemize @bullet
15035 @item
15036 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
15037 @item
15038 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
15039 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
15040 @end itemize
15042 @noindent
15043 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
15044 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
15045 @end ifset
15047 @node General Text Layout Control
15048 @subsection General Text Layout Control
15050 @noindent
15051 These switches allow control over line length and indentation.
15053 @table @option
15054 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
15055 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
15056 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
15058 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
15059 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
15060 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
15062 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
15063 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
15064 Indentation level for continuation lines (relative to the line being
15065 continued), @i{nnn} from 1 .. 9.
15066 The default
15067 value is one less then the (normal) indentation level, unless the
15068 indentation is set to 1 (in which case the default value for continuation
15069 line indentation is also 1)
15070 @end table
15072 @node Other Formatting Options
15073 @subsection Other Formatting Options
15075 @noindent
15076 These switches control the inclusion of missing end/exit labels, and
15077 the indentation level in @b{case} statements.
15079 @table @option
15080 @item ^-e^/NO_MISSED_LABELS^
15081 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
15082 Do not insert missing end/exit labels. An end label is the name of
15083 a construct that may optionally be repeated at the end of the
15084 construct's declaration;
15085 e.g., the names of packages, subprograms, and tasks.
15086 An exit label is the name of a loop that may appear as target
15087 of an exit statement within the loop.
15088 By default, @command{gnatpp} inserts these end/exit labels when
15089 they are absent from the original source. This option suppresses such
15090 insertion, so that the formatted source reflects the original.
15092 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
15093 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
15094 Insert a Form Feed character after a pragma Page.
15096 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
15097 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
15098 Do not use an additional indentation level for @b{case} alternatives
15099 and variants if there are @i{nnn} or more (the default
15100 value is 10).
15101 If @i{nnn} is 0, an additional indentation level is
15102 used for @b{case} alternatives and variants regardless of their number.
15103 @end table
15105 @node Setting the Source Search Path
15106 @subsection Setting the Source Search Path
15108 @noindent
15109 To define the search path for the input source file, @command{gnatpp}
15110 uses the same switches as the GNAT compiler, with the same effects.
15112 @table @option
15113 @item ^-I^/SEARCH=^@var{dir}
15114 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
15115 The same as the corresponding gcc switch
15117 @item ^-I-^/NOCURRENT_DIRECTORY^
15118 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
15119 The same as the corresponding gcc switch
15121 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
15122 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
15123 The same as the corresponding gcc switch
15125 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
15126 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
15127 The same as the corresponding gcc switch
15129 @end table
15131 @node Output File Control
15132 @subsection Output File Control
15134 @noindent
15135 By default the output is sent to the file whose name is obtained by appending
15136 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
15137 (if the file with this name already exists, it is unconditionally overwritten).
15138 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
15139 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
15140 as output file.
15141 The output may be redirected by the following switches:
15143 @table @option
15144 @item ^-pipe^/STANDARD_OUTPUT^
15145 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
15146 Send the output to @code{Standard_Output}
15148 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
15149 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
15150 Write the output into @var{output_file}.
15151 If @var{output_file} already exists, @command{gnatpp} terminates without
15152 reading or processing the input file.
15154 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
15155 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
15156 Write the output into @var{output_file}, overwriting the existing file
15157 (if one is present).
15159 @item ^-r^/REPLACE^
15160 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
15161 Replace the input source file with the reformatted output, and copy the
15162 original input source into the file whose name is obtained by appending the
15163 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
15164 If a file with this name already exists, @command{gnatpp} terminates without
15165 reading or processing the input file.
15167 @item ^-rf^/OVERRIDING_REPLACE^
15168 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
15169 Like @option{^-r^/REPLACE^} except that if the file with the specified name
15170 already exists, it is overwritten.
15172 @item ^-rnb^/NO_BACKUP^
15173 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
15174 Replace the input source file with the reformatted output without
15175 creating any backup copy of the input source.
15177 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
15178 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
15179 Specifies the format of the reformatted output file. The @var{xxx}
15180 ^string specified with the switch^option^ may be either
15181 @itemize @bullet
15182 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
15183 @item ``@option{^crlf^CRLF^}''
15184 the same as @option{^crlf^CRLF^}
15185 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
15186 @item ``@option{^lf^LF^}''
15187 the same as @option{^unix^UNIX^}
15188 @end itemize
15190 @end table
15192 @noindent
15193 Options @option{^-pipe^/STANDARD_OUTPUT^},
15194 @option{^-o^/OUTPUT^} and
15195 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
15196 contains only one file to reformat.
15197 Option
15198 @option{^--eol^/END_OF_LINE^}
15199 cannot be used together
15200 with @option{^-pipe^/STANDARD_OUTPUT^} option.
15202 @node Other gnatpp Switches
15203 @subsection Other @code{gnatpp} Switches
15205 @noindent
15206 The additional @command{gnatpp} switches are defined in this subsection.
15208 @table @option
15209 @item ^-files @var{filename}^/FILES=@var{output_file}^
15210 @cindex @option{^-files^/FILES^} (@code{gnatpp})
15211 Take the argument source files from the specified file. This file should be an
15212 ordinary textual file containing file names separated by spaces or
15213 line breaks. You can use this switch more then once in the same call to
15214 @command{gnatpp}. You also can combine this switch with explicit list of
15215 files.
15217 @item ^-v^/VERBOSE^
15218 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
15219 Verbose mode;
15220 @command{gnatpp} generates version information and then
15221 a trace of the actions it takes to produce or obtain the ASIS tree.
15223 @item ^-w^/WARNINGS^
15224 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
15225 Warning mode;
15226 @command{gnatpp} generates a warning whenever it cannot provide
15227 a required layout in the result source.
15228 @end table
15230 @node Formatting Rules
15231 @section Formatting Rules
15233 @noindent
15234 The following subsections show how @command{gnatpp} treats ``white space'',
15235 comments, program layout, and name casing.
15236 They provide the detailed descriptions of the switches shown above.
15238 @menu
15239 * White Space and Empty Lines::
15240 * Formatting Comments::
15241 * Construct Layout::
15242 * Name Casing::
15243 @end menu
15245 @node White Space and Empty Lines
15246 @subsection White Space and Empty Lines
15248 @noindent
15249 @command{gnatpp} does not have an option to control space characters.
15250 It will add or remove spaces according to the style illustrated by the
15251 examples in the @cite{Ada Reference Manual}.
15253 The only format effectors
15254 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15255 that will appear in the output file are platform-specific line breaks,
15256 and also format effectors within (but not at the end of) comments.
15257 In particular, each horizontal tab character that is not inside
15258 a comment will be treated as a space and thus will appear in the
15259 output file as zero or more spaces depending on
15260 the reformatting of the line in which it appears.
15261 The only exception is a Form Feed character, which is inserted after a
15262 pragma @code{Page} when @option{-ff} is set.
15264 The output file will contain no lines with trailing ``white space'' (spaces,
15265 format effectors).
15267 Empty lines in the original source are preserved
15268 only if they separate declarations or statements.
15269 In such contexts, a
15270 sequence of two or more empty lines is replaced by exactly one empty line.
15271 Note that a blank line will be removed if it separates two ``comment blocks''
15272 (a comment block is a sequence of whole-line comments).
15273 In order to preserve a visual separation between comment blocks, use an
15274 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15275 Likewise, if for some reason you wish to have a sequence of empty lines,
15276 use a sequence of empty comments instead.
15278 @node Formatting Comments
15279 @subsection Formatting Comments
15281 @noindent
15282 Comments in Ada code are of two kinds:
15283 @itemize @bullet
15284 @item
15285 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15286 ``white space'') on a line
15288 @item
15289 an @emph{end-of-line comment}, which follows some other Ada lexical element
15290 on the same line.
15291 @end itemize
15293 @noindent
15294 The indentation of a whole-line comment is that of either
15295 the preceding or following line in
15296 the formatted source, depending on switch settings as will be described below.
15298 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15299 between the end of the preceding Ada lexical element and the beginning
15300 of the comment as appear in the original source,
15301 unless either the comment has to be split to
15302 satisfy the line length limitation, or else the next line contains a
15303 whole line comment that is considered a continuation of this end-of-line
15304 comment (because it starts at the same position).
15305 In the latter two
15306 cases, the start of the end-of-line comment is moved right to the nearest
15307 multiple of the indentation level.
15308 This may result in a ``line overflow'' (the right-shifted comment extending
15309 beyond the maximum line length), in which case the comment is split as
15310 described below.
15312 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15313 (GNAT-style comment line indentation)
15314 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15315 (reference-manual comment line indentation).
15316 With reference-manual style, a whole-line comment is indented as if it
15317 were a declaration or statement at the same place
15318 (i.e., according to the indentation of the preceding line(s)).
15319 With GNAT style, a whole-line comment that is immediately followed by an
15320 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15321 word @b{begin}, is indented based on the construct that follows it.
15323 For example:
15324 @smallexample @c ada
15325 @cartouche
15326 if A then
15327     null;
15328        -- some comment
15329 else
15330    null;
15331 end if;
15332 @end cartouche
15333 @end smallexample
15335 @noindent
15336 Reference-manual indentation produces:
15338 @smallexample @c ada
15339 @cartouche
15340 if A then
15341    null;
15342    --  some comment
15343 else
15344    null;
15345 end if;
15346 @end cartouche
15347 @end smallexample
15349 @noindent
15350 while GNAT-style indentation produces:
15352 @smallexample @c ada
15353 @cartouche
15354 if A then
15355    null;
15356 --  some comment
15357 else
15358    null;
15359 end if;
15360 @end cartouche
15361 @end smallexample
15363 @noindent
15364 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15365 (GNAT style comment beginning) has the following
15366 effect:
15368 @itemize @bullet
15369 @item
15370 For each whole-line comment that does not end with two hyphens,
15371 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15372 to ensure that there are at least two spaces between these hyphens and the
15373 first non-blank character of the comment.
15374 @end itemize
15376 @noindent
15377 For an end-of-line comment, if in the original source the next line is a
15378 whole-line comment that starts at the same position
15379 as the end-of-line comment,
15380 then the whole-line comment (and all whole-line comments
15381 that follow it and that start at the same position)
15382 will start at this position in the output file.
15384 @noindent
15385 That is, if in the original source we have:
15387 @smallexample @c ada
15388 @cartouche
15389 begin
15390 A := B + C;            --  B must be in the range Low1..High1
15391                        --  C must be in the range Low2..High2
15392              --B+C will be in the range Low1+Low2..High1+High2
15393 X := X + 1;
15394 @end cartouche
15395 @end smallexample
15397 @noindent
15398 Then in the formatted source we get
15400 @smallexample @c ada
15401 @cartouche
15402 begin
15403    A := B + C;            --  B must be in the range Low1..High1
15404                           --  C must be in the range Low2..High2
15405    --  B+C will be in the range Low1+Low2..High1+High2
15406    X := X + 1;
15407 @end cartouche
15408 @end smallexample
15410 @noindent
15411 A comment that exceeds the line length limit will be split.
15412 Unless switch
15413 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15414 the line belongs to a reformattable block, splitting the line generates a
15415 @command{gnatpp} warning.
15416 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15417 comments may be reformatted in typical
15418 word processor style (that is, moving words between lines and putting as
15419 many words in a line as possible).
15421 @node Construct Layout
15422 @subsection Construct Layout
15424 @noindent
15425 In several cases the suggested layout in the Ada Reference Manual includes
15426 an extra level of indentation that many programmers prefer to avoid. The
15427 affected cases include:
15429 @itemize @bullet
15431 @item Record type declaration (RM 3.8)
15433 @item Record representation clause (RM 13.5.1)
15435 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
15437 @item Block statement in case if a block has a statement identifier (RM 5.6)
15438 @end itemize
15440 @noindent
15441 In compact mode (when GNAT style layout or compact layout is set),
15442 the pretty printer uses one level of indentation instead
15443 of two. This is achieved in the record definition and record representation
15444 clause cases by putting the @code{record} keyword on the same line as the
15445 start of the declaration or representation clause, and in the block and loop
15446 case by putting the block or loop header on the same line as the statement
15447 identifier.
15449 @noindent
15450 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15451 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15452 layout on the one hand, and uncompact layout
15453 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15454 can be illustrated by the following examples:
15456 @iftex
15457 @cartouche
15458 @multitable @columnfractions .5 .5
15459 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15461 @item
15462 @smallexample @c ada
15463 type q is record
15464    a : integer;
15465    b : integer;
15466 end record;
15467 @end smallexample
15468 @tab
15469 @smallexample @c ada
15470 type q is
15471    record
15472       a : integer;
15473       b : integer;
15474    end record;
15475 @end smallexample
15477 @item
15478 @smallexample @c ada
15479 for q use record
15480    a at 0 range  0 .. 31;
15481    b at 4 range  0 .. 31;
15482 end record;
15483 @end smallexample
15484 @tab
15485 @smallexample @c ada
15486 for q use
15487    record
15488       a at 0 range  0 .. 31;
15489       b at 4 range  0 .. 31;
15490    end record;
15491 @end smallexample
15493 @item
15494 @smallexample @c ada
15495 Block : declare
15496    A : Integer := 3;
15497 begin
15498    Proc (A, A);
15499 end Block;
15500 @end smallexample
15501 @tab
15502 @smallexample @c ada
15503 Block :
15504    declare
15505       A : Integer := 3;
15506    begin
15507       Proc (A, A);
15508    end Block;
15509 @end smallexample
15511 @item
15512 @smallexample @c ada
15513 Clear : for J in 1 .. 10 loop
15514    A (J) := 0;
15515 end loop Clear;
15516 @end smallexample
15517 @tab
15518 @smallexample @c ada
15519 Clear :
15520    for J in 1 .. 10 loop
15521       A (J) := 0;
15522    end loop Clear;
15523 @end smallexample
15524 @end multitable
15525 @end cartouche
15526 @end iftex
15528 @ifnottex
15529 @smallexample
15530 @cartouche
15531 GNAT style, compact layout              Uncompact layout
15533 type q is record                        type q is
15534    a : integer;                            record
15535    b : integer;                               a : integer;
15536 end record;                                   b : integer;
15537                                            end record;
15539 for q use record                        for q use
15540    a at 0 range  0 .. 31;                  record
15541    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
15542 end record;                                   b at 4 range  0 .. 31;
15543                                            end record;
15545 Block : declare                         Block :
15546    A : Integer := 3;                       declare
15547 begin                                         A : Integer := 3;
15548    Proc (A, A);                            begin
15549 end Block;                                    Proc (A, A);
15550                                            end Block;
15552 Clear : for J in 1 .. 10 loop           Clear :
15553    A (J) := 0;                             for J in 1 .. 10 loop
15554 end loop Clear;                               A (J) := 0;
15555                                            end loop Clear;
15556 @end cartouche
15557 @end smallexample
15558 @end ifnottex
15560 @noindent
15561 A further difference between GNAT style layout and compact layout is that
15562 GNAT style layout inserts empty lines as separation for
15563 compound statements, return statements and bodies.
15565 @node Name Casing
15566 @subsection Name Casing
15568 @noindent
15569 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15570 the same casing as the corresponding defining identifier.
15572 You control the casing for defining occurrences via the
15573 @option{^-n^/NAME_CASING^} switch.
15574 @ifclear vms
15575 With @option{-nD} (``as declared'', which is the default),
15576 @end ifclear
15577 @ifset vms
15578 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15579 @end ifset
15580 defining occurrences appear exactly as in the source file
15581 where they are declared.
15582 The other ^values for this switch^options for this qualifier^ ---
15583 @option{^-nU^UPPER_CASE^},
15584 @option{^-nL^LOWER_CASE^},
15585 @option{^-nM^MIXED_CASE^} ---
15586 result in
15587 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15588 If @command{gnatpp} changes the casing of a defining
15589 occurrence, it analogously changes the casing of all the
15590 usage occurrences of this name.
15592 If the defining occurrence of a name is not in the source compilation unit
15593 currently being processed by @command{gnatpp}, the casing of each reference to
15594 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15595 switch (subject to the dictionary file mechanism described below).
15596 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15597 had affected the
15598 casing for the defining occurrence of the name.
15600 Some names may need to be spelled with casing conventions that are not
15601 covered by the upper-, lower-, and mixed-case transformations.
15602 You can arrange correct casing by placing such names in a
15603 @emph{dictionary file},
15604 and then supplying a @option{^-D^/DICTIONARY^} switch.
15605 The casing of names from dictionary files overrides
15606 any @option{^-n^/NAME_CASING^} switch.
15608 To handle the casing of Ada predefined names and the names from GNAT libraries,
15609 @command{gnatpp} assumes a default dictionary file.
15610 The name of each predefined entity is spelled with the same casing as is used
15611 for the entity in the @cite{Ada Reference Manual}.
15612 The name of each entity in the GNAT libraries is spelled with the same casing
15613 as is used in the declaration of that entity.
15615 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15616 default dictionary file.
15617 Instead, the casing for predefined and GNAT-defined names will be established
15618 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15619 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15620 will appear as just shown,
15621 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15622 To ensure that even such names are rendered in uppercase,
15623 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15624 (or else, less conveniently, place these names in upper case in a dictionary
15625 file).
15627 A dictionary file is
15628 a plain text file; each line in this file can be either a blank line
15629 (containing only space characters and ASCII.HT characters), an Ada comment
15630 line, or the specification of exactly one @emph{casing schema}.
15632 A casing schema is a string that has the following syntax:
15634 @smallexample
15635 @cartouche
15636   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15638   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15639 @end cartouche
15640 @end smallexample
15642 @noindent
15643 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15644 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15646 The casing schema string can be followed by white space and/or an Ada-style
15647 comment; any amount of white space is allowed before the string.
15649 If a dictionary file is passed as
15650 @ifclear vms
15651 the value of a @option{-D@var{file}} switch
15652 @end ifclear
15653 @ifset vms
15654 an option to the @option{/DICTIONARY} qualifier
15655 @end ifset
15656 then for every
15657 simple name and every identifier, @command{gnatpp} checks if the dictionary
15658 defines the casing for the name or for some of its parts (the term ``subword''
15659 is used below to denote the part of a name which is delimited by ``_'' or by
15660 the beginning or end of the word and which does not contain any ``_'' inside):
15662 @itemize @bullet
15663 @item
15664 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15665 the casing defined by the dictionary; no subwords are checked for this word
15667 @item
15668 for every subword @command{gnatpp} checks if the dictionary contains the
15669 corresponding string of the form @code{*@var{simple_identifier}*},
15670 and if it does, the casing of this @var{simple_identifier} is used
15671 for this subword
15673 @item
15674 if the whole name does not contain any ``_'' inside, and if for this name
15675 the dictionary contains two entries - one of the form @var{identifier},
15676 and another - of the form *@var{simple_identifier}*, then the first one
15677 is applied to define the casing of this name
15679 @item
15680 if more than one dictionary file is passed as @command{gnatpp} switches, each
15681 dictionary adds new casing exceptions and overrides all the existing casing
15682 exceptions set by the previous dictionaries
15684 @item
15685 when @command{gnatpp} checks if the word or subword is in the dictionary,
15686 this check is not case sensitive
15687 @end itemize
15689 @noindent
15690 For example, suppose we have the following source to reformat:
15692 @smallexample @c ada
15693 @cartouche
15694 procedure test is
15695    name1 : integer := 1;
15696    name4_name3_name2 : integer := 2;
15697    name2_name3_name4 : Boolean;
15698    name1_var : Float;
15699 begin
15700    name2_name3_name4 := name4_name3_name2 > name1;
15701 end;
15702 @end cartouche
15703 @end smallexample
15705 @noindent
15706 And suppose we have two dictionaries:
15708 @smallexample
15709 @cartouche
15710 @i{dict1:}
15711    NAME1
15712    *NaMe3*
15713    *Name1*
15714 @end cartouche
15716 @cartouche
15717 @i{dict2:}
15718   *NAME3*
15719 @end cartouche
15720 @end smallexample
15722 @noindent
15723 If @command{gnatpp} is called with the following switches:
15725 @smallexample
15726 @ifclear vms
15727 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15728 @end ifclear
15729 @ifset vms
15730 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15731 @end ifset
15732 @end smallexample
15734 @noindent
15735 then we will get the following name casing in the @command{gnatpp} output:
15737 @smallexample @c ada
15738 @cartouche
15739 procedure Test is
15740    NAME1             : Integer := 1;
15741    Name4_NAME3_Name2 : Integer := 2;
15742    Name2_NAME3_Name4 : Boolean;
15743    Name1_Var         : Float;
15744 begin
15745    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15746 end Test;
15747 @end cartouche
15748 @end smallexample
15750 @c *********************************
15751 @node The GNAT Metric Tool gnatmetric
15752 @chapter The GNAT Metric Tool @command{gnatmetric}
15753 @findex gnatmetric
15754 @cindex Metric tool
15756 @noindent
15757 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15758 for computing various program metrics.
15759 It takes an Ada source file as input and generates a file containing the
15760 metrics data as output. Various switches control which
15761 metrics are computed and output.
15763 @command{gnatmetric} generates and uses the ASIS
15764 tree for the input source and thus requires the input to be syntactically and
15765 semantically legal.
15766 If this condition is not met, @command{gnatmetric} will generate
15767 an error message; no metric information for this file will be
15768 computed and reported.
15770 If the compilation unit contained in the input source depends semantically
15771 upon units in files located outside the current directory, you have to provide
15772 the source search path when invoking @command{gnatmetric}.
15773 If it depends semantically upon units that are contained
15774 in files with names that do not follow the GNAT file naming rules, you have to
15775 provide the configuration file describing the corresponding naming scheme (see
15776 the description of the @command{gnatmetric} switches below.)
15777 Alternatively, you may use a project file and invoke @command{gnatmetric}
15778 through the @command{gnat} driver.
15781 The @command{gnatmetric} command has the form
15783 @smallexample
15784 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
15785 @end smallexample
15787 @noindent
15788 where
15789 @itemize @bullet
15790 @item
15791 @i{switches} specify the metrics to compute and define the destination for
15792 the output
15794 @item
15795 Each @i{filename} is the name (including the extension) of a source
15796 file to process. ``Wildcards'' are allowed, and
15797 the file name may contain path information.
15798 If no @i{filename} is supplied, then the @i{switches} list must contain
15799 at least one
15800 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15801 Including both a @option{-files} switch and one or more
15802 @i{filename} arguments is permitted.
15804 @item
15805 @i{-cargs gcc_switches} is a list of switches for
15806 @command{gcc}. They will be passed on to all compiler invocations made by
15807 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15808 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15809 and use the @option{-gnatec} switch to set the configuration file.
15810 @end itemize
15812 @menu
15813 * Switches for gnatmetric::
15814 @end menu
15816 @node Switches for gnatmetric
15817 @section Switches for @command{gnatmetric}
15819 @noindent
15820 The following subsections describe the various switches accepted by
15821 @command{gnatmetric}, organized by category.
15823 @menu
15824 * Output Files Control::
15825 * Disable Metrics For Local Units::
15826 * Line Metrics Control::
15827 * Syntax Metrics Control::
15828 * Complexity Metrics Control::
15829 * Other gnatmetric Switches::
15830 @end menu
15832 @node Output Files Control
15833 @subsection Output File Control
15834 @cindex Output file control in @command{gnatmetric}
15836 @noindent
15837 @command{gnatmetric} has two output formats. It can generate a
15838 textual (human-readable) form, and also XML. By default only textual
15839 output is generated.
15841 When generating the output in textual form, @command{gnatmetric} creates
15842 for each Ada source file a corresponding text file
15843 containing the computed metrics. By default, this file
15844 is placed in the same directory as where the source file is located, and
15845 its name is obtained
15846 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15847 input file.
15849 All the output information generated in XML format is placed in a single
15850 file. By default this file is placed in the current directory and has the
15851 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15853 Some of the computed metrics are summed over the units passed to
15854 @command{gnatmetric}; for example, the total number of lines of code.
15855 By default this information is sent to @file{stdout}, but a file
15856 can be specified with the @option{-og} switch.
15858 The following switches control the @command{gnatmetric} output:
15860 @table @option
15861 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15862 @item ^-x^/XML^
15863 Generate the XML output
15865 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15866 @item ^-nt^/NO_TEXT^
15867 Do not generate the output in text form (implies @option{^-x^/XML^})
15869 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15870 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15871 Put textual files with detailed metrics into @var{output_dir}
15873 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15874 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15875 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15876 in the name of the output file.
15878 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15879 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15880 Put global metrics into @var{file_name}
15882 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15883 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15884 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15886 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15887 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15888 Use ``short'' source file names in the output.  (The @command{gnatmetric}
15889 output includes the name(s) of the Ada source file(s) from which the metrics
15890 are computed.  By default each name includes the absolute path. The
15891 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15892 to exclude all directory information from the file names that are output.)
15894 @end table
15896 @node Disable Metrics For Local Units
15897 @subsection Disable Metrics For Local Units
15898 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15900 @noindent
15901 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15902 one compilation
15903 unit per one source file. It computes line metrics for the whole source
15904 file, and it also computes syntax
15905 and complexity metrics for the file's outermost unit.
15907 By default, @command{gnatmetric} will also compute all metrics for certain
15908 kinds of locally declared program units:
15910 @itemize @bullet
15911 @item
15912 subprogram (and generic subprogram) bodies;
15914 @item
15915 package (and generic package) specifications and bodies;
15917 @item
15918 task object and type specifications and bodies;
15920 @item
15921 protected object and type specifications and bodies.
15922 @end itemize
15924 @noindent
15925 These kinds of entities will be referred to as
15926 @emph{eligible local program units}, or simply @emph{eligible local units},
15927 @cindex Eligible local unit (for @command{gnatmetric})
15928 in the discussion below.
15930 Note that a subprogram declaration, generic instantiation,
15931 or renaming declaration only receives metrics
15932 computation when it appear as the outermost entity
15933 in a source file.
15935 Suppression of metrics computation for eligible local units can be
15936 obtained via the following switch:
15938 @table @option
15939 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15940 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15941 Do not compute detailed metrics for eligible local program units
15943 @end table
15945 @node Line Metrics Control
15946 @subsection Line Metrics Control
15947 @cindex Line metrics control in @command{gnatmetric}
15949 @noindent
15950 For any (legal) source file, and for each of its
15951 eligible local program units, @command{gnatmetric} computes the following
15952 metrics:
15954 @itemize @bullet
15955 @item
15956 the total number of lines;
15958 @item
15959 the total number of code lines (i.e., non-blank lines that are not comments)
15961 @item
15962 the number of comment lines
15964 @item
15965 the number of code lines containing end-of-line comments;
15967 @item
15968 the number of empty lines and lines containing only space characters and/or
15969 format effectors (blank lines)
15971 @end itemize
15973 If @command{gnatmetric} is invoked on more than one source file, it sums the
15974 values of the line metrics for all the files being processed and then
15975 generates the cumulative results.
15977 By default, all the line metrics are computed and reported. You can use the
15978 following switches to select the specific line metrics to be computed and
15979 reported (if any of these parameters is set, only explicitly specified line
15980 metrics are computed).
15982 @table @option
15983 @cindex @option{^-la^/LINES_ALL^} (@command{gnatmetric})
15984 @item ^-la^/LINES_ALL^
15985 The number of all lines
15987 @cindex @option{^-lcode^/CODE_LINES^} (@command{gnatmetric})
15988 @item ^-lcode^/CODE_LINES^
15989 The number of code lines
15991 @cindex @option{^-lcomm^/COMMENT_LINES^} (@command{gnatmetric})
15992 @item ^-lcomm^/COMENT_LINES^
15993 The number of comment lines
15995 @cindex @option{^-leol^/MIXED_CODE_COMMENTS^} (@command{gnatmetric})
15996 @item ^-leol^/MIXED_CODE_COMMENTS^
15997 The number of code lines containing
15998 end-of-line comments
16000 @cindex @option{^-lb^/BLANK_LINES^} (@command{gnatmetric})
16001 @item ^-lb^/BLANK_LINES^
16002 The number of blank lines
16004 @end table
16007 @node Syntax Metrics Control
16008 @subsection Syntax Metrics Control
16009 @cindex Syntax metrics control in @command{gnatmetric}
16011 @noindent
16012 @command{gnatmetric} computes various syntactic metrics for the
16013 outermost unit and for each eligible local unit:
16015 @table @emph
16016 @item LSLOC (``Logical Source Lines Of Code'')
16017 The total number of declarations and the total number of statements
16019 @item Maximal static nesting level of inner program units
16020 According to
16021 @cite{Ada 95 Language Reference Manual}, 10.1(1), ``A program unit is either a
16022 package, a task unit, a protected unit, a
16023 protected entry, a generic unit, or an explicitly declared subprogram other
16024 than an enumeration literal.''
16026 @item Maximal nesting level of composite syntactic constructs
16027 This corresponds to the notion of the
16028 maximum nesting level in the GNAT built-in style checks
16029 (@pxref{Style Checking})
16030 @end table
16032 @noindent
16033 For the outermost unit in the file, @command{gnatmetric} additionally computes
16034 the following metrics:
16036 @table @emph
16037 @item Public subprograms
16038 This metric is computed for package specifications. It is the
16039 number of subprograms and generic subprograms declared in the visible
16040 part (including in nested packages, protected objects, and
16041 protected types).
16043 @item All subprograms
16044 This metric is computed for bodies and subunits. The
16045 metric is equal to a total number of subprogram bodies in the compilation
16046 unit.
16047 Neither generic instantiations nor renamings-as-a-body nor body stubs
16048 are counted. Any subprogram body is counted, independently of its nesting
16049 level and enclosing constructs. Generic bodies and bodies of protected
16050 subprograms are counted in the same way as ``usual'' subprogram bodies.
16052 @item Public types
16053 This metric is computed for package specifications and
16054 generic package declarations. It is the total number of types
16055 that can be referenced from outside this compilation unit, plus the
16056 number of types from all the visible parts of all the visible generic packages.
16057 Generic formal types are not counted.  Only types, not subtypes,
16058 are included.
16060 @noindent
16061 Along with the total number of public types, the following
16062 types are counted and reported separately:
16064 @itemize @bullet
16065 @item
16066 Abstract types
16068 @item
16069 Root tagged types (abstract, non-abstract, private, non-private). Type
16070 extensions are @emph{not} counted
16072 @item
16073 Private types (including private extensions)
16075 @item
16076 Task types
16078 @item
16079 Protected types
16081 @end itemize
16083 @item All types
16084 This metric is computed for any compilation unit. It is equal to the total
16085 number of the declarations of different types given in the compilation unit.
16086 The private and the corresponding full type declaration are counted as one
16087 type declaration. Incomplete type declarations and generic formal types
16088 are not counted.
16089 No distinction is made among different kinds of types (abstract,
16090 private etc.); the total number of types is computed and reported.
16092 @end table
16094 @noindent
16095 By default, all the syntax metrics are computed and reported. You can use the
16096 following switches to select specific syntax metrics;
16097 if any of these is set, only the explicitly specified metrics are computed.
16099 @table @option
16100 @cindex @option{^-ed^/DECLARATION_TOTAL^} (@command{gnatmetric})
16101 @item ^-ed^/DECLARATION_TOTAL^
16102 The total number of declarations
16104 @cindex @option{^-es^/STATEMENT_TOTAL^} (@command{gnatmetric})
16105 @item ^-es^/STATEMENT_TOTAL^
16106 The total number of statements
16108 @cindex @option{^-eps^/^} (@command{gnatmetric})
16109 @item ^-eps^/INT_SUBPROGRAMS^
16110 The number of public subprograms in a compilation unit
16112 @cindex @option{^-eas^/SUBPROGRAMS_ALL^} (@command{gnatmetric})
16113 @item ^-eas^/SUBPROGRAMS_ALL^
16114 The number of all the subprograms in a compilation unit
16116 @cindex @option{^-ept^/INT_TYPES^} (@command{gnatmetric})
16117 @item ^-ept^/INT_TYPES^
16118 The number of public types in a compilation unit
16120 @cindex @option{^-eat^/TYPES_ALL^} (@command{gnatmetric})
16121 @item ^-eat^/TYPES_ALL^
16122 The number of all the types in a compilation unit
16124 @cindex @option{^-enu^/PROGRAM_NESTING_MAX^} (@command{gnatmetric})
16125 @item ^-enu^/PROGRAM_NESTING_MAX^
16126 The maximal program unit nesting level
16128 @cindex @option{^-ec^/CONSTRUCT_NESTING_MAX^} (@command{gnatmetric})
16129 @item ^-ec^/CONSTRUCT_NESTING_MAX^
16130 The maximal construct nesting level
16132 @end table
16134 @node Complexity Metrics Control
16135 @subsection Complexity Metrics Control
16136 @cindex Complexity metrics control in @command{gnatmetric}
16138 @noindent
16139 For a program unit that is an executable body (a subprogram body (including
16140 generic bodies), task body, entry body or a package body containing
16141 its own statement sequence ) @command{gnatmetric} computes the following
16142 complexity metrics:
16144 @itemize @bullet
16145 @item
16146 McCabe cyclomatic complexity;
16148 @item
16149 McCabe essential complexity;
16151 @item
16152 maximal loop nesting level
16154 @end itemize
16156 @noindent
16157 The McCabe complexity metrics are defined
16158 in @url{www.mccabe.com/pdf/nist235r.pdf}
16160 According to McCabe, both control statements and short-circuit control forms
16161 should be taken into account when computing cyclomatic complexity. For each
16162 body, we compute three metric values:
16164 @itemize @bullet
16165 @item
16166 the complexity introduced by control
16167 statements only, without taking into account short-circuit forms,
16169 @item
16170 the complexity introduced by short-circuit control forms only, and
16172 @item
16173 the total
16174 cyclomatic complexity, which is the sum of these two values.
16175 @end itemize
16177 @noindent
16178 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16179 the code in the exception handlers and in all the nested program units.
16181 By default, all the complexity metrics are computed and reported.
16182 For more finely-grained control you can use
16183 the following switches:
16185 @table @option
16186 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
16188 @item ^-nocc^/SUPPRESS=CYCLOMATIC_COMPLEXITY^
16189 Do not compute the McCabe Cyclomatic Complexity
16191 @item ^-noec^/SUPPRESS=ESSENTIAL_COMPLEXITY^
16192 Do not compute the Essential Complexity
16194 @item ^-nonl^/SUPPRESS=MAXIMAL_LOOP_NESTING^
16195 Do not compute maximal loop nesting level
16197 @item ^-ne^/SUPPRESS=EXITS_AS_GOTOS^
16198 Do not consider @code{exit} statements as @code{goto}s when
16199 computing Essential Complexity
16201 @end table
16203 @node Other gnatmetric Switches
16204 @subsection Other @code{gnatmetric} Switches
16206 @noindent
16207 Additional @command{gnatmetric} switches are as follows:
16209 @table @option
16210 @item ^-files @var{filename}^/FILES=@var{filename}^
16211 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16212 Take the argument source files from the specified file. This file should be an
16213 ordinary textual file containing file names separated by spaces or
16214 line breaks. You can use this switch more then once in the same call to
16215 @command{gnatmetric}. You also can combine this switch with
16216 an explicit list of files.
16218 @item ^-v^/VERBOSE^
16219 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16220 Verbose mode;
16221 @command{gnatmetric} generates version information and then
16222 a trace of sources being processed.
16224 @item ^-dv^/DEBUG_OUTPUT^
16225 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
16226 Debug mode;
16227 @command{gnatmetric} generates various messages useful to understand what
16228 happens during the metrics computation
16230 @item ^-q^/QUIET^
16231 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16232 Quiet mode.
16233 @end table
16235 @c ***********************************
16236 @node File Name Krunching Using gnatkr
16237 @chapter File Name Krunching Using @code{gnatkr}
16238 @findex gnatkr
16240 @noindent
16241 This chapter discusses the method used by the compiler to shorten
16242 the default file names chosen for Ada units so that they do not
16243 exceed the maximum length permitted. It also describes the
16244 @code{gnatkr} utility that can be used to determine the result of
16245 applying this shortening.
16246 @menu
16247 * About gnatkr::
16248 * Using gnatkr::
16249 * Krunching Method::
16250 * Examples of gnatkr Usage::
16251 @end menu
16253 @node About gnatkr
16254 @section About @code{gnatkr}
16256 @noindent
16257 The default file naming rule in GNAT
16258 is that the file name must be derived from
16259 the unit name. The exact default rule is as follows:
16260 @itemize @bullet
16261 @item
16262 Take the unit name and replace all dots by hyphens.
16263 @item
16264 If such a replacement occurs in the
16265 second character position of a name, and the first character is
16266 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
16267 ^~ (tilde)^$ (dollar sign)^
16268 instead of a minus.
16269 @end itemize
16270 The reason for this exception is to avoid clashes
16271 with the standard names for children of System, Ada, Interfaces,
16272 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
16273 respectively.
16275 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16276 switch of the compiler activates a ``krunching''
16277 circuit that limits file names to nn characters (where nn is a decimal
16278 integer). For example, using OpenVMS,
16279 where the maximum file name length is
16280 39, the value of nn is usually set to 39, but if you want to generate
16281 a set of files that would be usable if ported to a system with some
16282 different maximum file length, then a different value can be specified.
16283 The default value of 39 for OpenVMS need not be specified.
16285 The @code{gnatkr} utility can be used to determine the krunched name for
16286 a given file, when krunched to a specified maximum length.
16288 @node Using gnatkr
16289 @section Using @code{gnatkr}
16291 @noindent
16292 The @code{gnatkr} command has the form
16294 @ifclear vms
16295 @smallexample
16296 $ gnatkr @var{name} [@var{length}]
16297 @end smallexample
16298 @end ifclear
16300 @ifset vms
16301 @smallexample
16302 $ gnatkr @var{name} /COUNT=nn
16303 @end smallexample
16304 @end ifset
16306 @noindent
16307 @var{name} is the uncrunched file name, derived from the name of the unit
16308 in the standard manner described in the previous section (i.e. in particular
16309 all dots are replaced by hyphens). The file name may or may not have an
16310 extension (defined as a suffix of the form period followed by arbitrary
16311 characters other than period). If an extension is present then it will
16312 be preserved in the output. For example, when krunching @file{hellofile.ads}
16313 to eight characters, the result will be hellofil.ads.
16315 Note: for compatibility with previous versions of @code{gnatkr} dots may
16316 appear in the name instead of hyphens, but the last dot will always be
16317 taken as the start of an extension. So if @code{gnatkr} is given an argument
16318 such as @file{Hello.World.adb} it will be treated exactly as if the first
16319 period had been a hyphen, and for example krunching to eight characters
16320 gives the result @file{hellworl.adb}.
16322 Note that the result is always all lower case (except on OpenVMS where it is
16323 all upper case). Characters of the other case are folded as required.
16325 @var{length} represents the length of the krunched name. The default
16326 when no argument is given is ^8^39^ characters. A length of zero stands for
16327 unlimited, in other words do not chop except for system files where the
16328 implied crunching length is always eight characters.
16330 @noindent
16331 The output is the krunched name. The output has an extension only if the
16332 original argument was a file name with an extension.
16334 @node Krunching Method
16335 @section Krunching Method
16337 @noindent
16338 The initial file name is determined by the name of the unit that the file
16339 contains. The name is formed by taking the full expanded name of the
16340 unit and replacing the separating dots with hyphens and
16341 using ^lowercase^uppercase^
16342 for all letters, except that a hyphen in the second character position is
16343 replaced by a ^tilde^dollar sign^ if the first character is
16344 ^a, i, g, or s^A, I, G, or S^.
16345 The extension is @code{.ads} for a
16346 specification and @code{.adb} for a body.
16347 Krunching does not affect the extension, but the file name is shortened to
16348 the specified length by following these rules:
16350 @itemize @bullet
16351 @item
16352 The name is divided into segments separated by hyphens, tildes or
16353 underscores and all hyphens, tildes, and underscores are
16354 eliminated. If this leaves the name short enough, we are done.
16356 @item
16357 If the name is too long, the longest segment is located (left-most
16358 if there are two of equal length), and shortened by dropping
16359 its last character. This is repeated until the name is short enough.
16361 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16362 to fit the name into 8 characters as required by some operating systems.
16364 @smallexample
16365 our-strings-wide_fixed 22
16366 our strings wide fixed 19
16367 our string  wide fixed 18
16368 our strin   wide fixed 17
16369 our stri    wide fixed 16
16370 our stri    wide fixe  15
16371 our str     wide fixe  14
16372 our str     wid  fixe  13
16373 our str     wid  fix   12
16374 ou  str     wid  fix   11
16375 ou  st      wid  fix   10
16376 ou  st      wi   fix   9
16377 ou  st      wi   fi    8
16378 Final file name: oustwifi.adb
16379 @end smallexample
16381 @item
16382 The file names for all predefined units are always krunched to eight
16383 characters. The krunching of these predefined units uses the following
16384 special prefix replacements:
16386 @table @file
16387 @item ada-
16388 replaced by @file{^a^A^-}
16390 @item gnat-
16391 replaced by @file{^g^G^-}
16393 @item interfaces-
16394 replaced by @file{^i^I^-}
16396 @item system-
16397 replaced by @file{^s^S^-}
16398 @end table
16400 These system files have a hyphen in the second character position. That
16401 is why normal user files replace such a character with a
16402 ^tilde^dollar sign^, to
16403 avoid confusion with system file names.
16405 As an example of this special rule, consider
16406 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16408 @smallexample
16409 ada-strings-wide_fixed 22
16410 a-  strings wide fixed 18
16411 a-  string  wide fixed 17
16412 a-  strin   wide fixed 16
16413 a-  stri    wide fixed 15
16414 a-  stri    wide fixe  14
16415 a-  str     wide fixe  13
16416 a-  str     wid  fixe  12
16417 a-  str     wid  fix   11
16418 a-  st      wid  fix   10
16419 a-  st      wi   fix   9
16420 a-  st      wi   fi    8
16421 Final file name: a-stwifi.adb
16422 @end smallexample
16423 @end itemize
16425 Of course no file shortening algorithm can guarantee uniqueness over all
16426 possible unit names, and if file name krunching is used then it is your
16427 responsibility to ensure that no name clashes occur. The utility
16428 program @code{gnatkr} is supplied for conveniently determining the
16429 krunched name of a file.
16431 @node Examples of gnatkr Usage
16432 @section Examples of @code{gnatkr} Usage
16434 @smallexample
16435 @iftex
16436 @leftskip=0cm
16437 @end iftex
16438 @ifclear vms
16439 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16440 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16441 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16442 $ gnatkr grandparent-parent-child     --> grparchi
16443 @end ifclear
16444 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16445 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16446 @end smallexample
16448 @node Preprocessing Using gnatprep
16449 @chapter Preprocessing Using @code{gnatprep}
16450 @findex gnatprep
16452 @noindent
16453 The @code{gnatprep} utility provides
16454 a simple preprocessing capability for Ada programs.
16455 It is designed for use with GNAT, but is not dependent on any special
16456 features of GNAT.
16458 @menu
16459 * Using gnatprep::
16460 * Switches for gnatprep::
16461 * Form of Definitions File::
16462 * Form of Input Text for gnatprep::
16463 @end menu
16465 @node Using gnatprep
16466 @section Using @code{gnatprep}
16468 @noindent
16469 To call @code{gnatprep} use
16471 @smallexample
16472 $ gnatprep [switches] infile outfile [deffile]
16473 @end smallexample
16475 @noindent
16476 where
16477 @table @code
16478 @item switches
16479 is an optional sequence of switches as described in the next section.
16481 @item infile
16482 is the full name of the input file, which is an Ada source
16483 file containing preprocessor directives.
16485 @item outfile
16486 is the full name of the output file, which is an Ada source
16487 in standard Ada form. When used with GNAT, this file name will
16488 normally have an ads or adb suffix.
16490 @item deffile
16491 is the full name of a text file containing definitions of
16492 symbols to be referenced by the preprocessor. This argument is
16493 optional, and can be replaced by the use of the @option{-D} switch.
16495 @end table
16497 @node Switches for gnatprep
16498 @section Switches for @code{gnatprep}
16500 @table @option
16501 @c !sort!
16503 @item ^-b^/BLANK_LINES^
16504 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16505 Causes both preprocessor lines and the lines deleted by
16506 preprocessing to be replaced by blank lines in the output source file,
16507 preserving line numbers in the output file.
16509 @item ^-c^/COMMENTS^
16510 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16511 Causes both preprocessor lines and the lines deleted
16512 by preprocessing to be retained in the output source as comments marked
16513 with the special string @code{"--! "}. This option will result in line numbers
16514 being preserved in the output file.
16516 @item ^-C^/REPLACE_IN_COMMENTS^
16517 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16518 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16519 If this option is specified, then comments are scanned and any $symbol
16520 substitutions performed as in program text. This is particularly useful
16521 when structured comments are used (e.g. when writing programs in the
16522 SPARK dialect of Ada). Note that this switch is not available when
16523 doing integrated preprocessing (it would be useless in this context
16524 since comments are ignored by the compiler in any case).
16526 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16527 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16528 Defines a new symbol, associated with value. If no value is given on the
16529 command line, then symbol is considered to be @code{True}. This switch
16530 can be used in place of a definition file.
16532 @ifset vms
16533 @item /REMOVE
16534 @cindex @option{/REMOVE} (@command{gnatprep})
16535 This is the default setting which causes lines deleted by preprocessing
16536 to be entirely removed from the output file.
16537 @end ifset
16539 @item ^-r^/REFERENCE^
16540 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16541 Causes a @code{Source_Reference} pragma to be generated that
16542 references the original input file, so that error messages will use
16543 the file name of this original file. The use of this switch implies
16544 that preprocessor lines are not to be removed from the file, so its
16545 use will force @option{^-b^/BLANK_LINES^} mode if
16546 @option{^-c^/COMMENTS^}
16547 has not been specified explicitly.
16549 Note that if the file to be preprocessed contains multiple units, then
16550 it will be necessary to @code{gnatchop} the output file from
16551 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16552 in the preprocessed file, it will be respected by
16553 @code{gnatchop ^-r^/REFERENCE^}
16554 so that the final chopped files will correctly refer to the original
16555 input source file for @code{gnatprep}.
16557 @item ^-s^/SYMBOLS^
16558 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16559 Causes a sorted list of symbol names and values to be
16560 listed on the standard output file.
16562 @item ^-u^/UNDEFINED^
16563 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16564 Causes undefined symbols to be treated as having the value FALSE in the context
16565 of a preprocessor test. In the absence of this option, an undefined symbol in
16566 a @code{#if} or @code{#elsif} test will be treated as an error.
16568 @end table
16570 @ifclear vms
16571 @noindent
16572 Note: if neither @option{-b} nor @option{-c} is present,
16573 then preprocessor lines and
16574 deleted lines are completely removed from the output, unless -r is
16575 specified, in which case -b is assumed.
16576 @end ifclear
16578 @node Form of Definitions File
16579 @section Form of Definitions File
16581 @noindent
16582 The definitions file contains lines of the form
16584 @smallexample
16585 symbol := value
16586 @end smallexample
16588 @noindent
16589 where symbol is an identifier, following normal Ada (case-insensitive)
16590 rules for its syntax, and value is one of the following:
16592 @itemize @bullet
16593 @item
16594 Empty, corresponding to a null substitution
16595 @item
16596 A string literal using normal Ada syntax
16597 @item
16598 Any sequence of characters from the set
16599 (letters, digits, period, underline).
16600 @end itemize
16602 @noindent
16603 Comment lines may also appear in the definitions file, starting with
16604 the usual @code{--},
16605 and comments may be added to the definitions lines.
16607 @node Form of Input Text for gnatprep
16608 @section Form of Input Text for @code{gnatprep}
16610 @noindent
16611 The input text may contain preprocessor conditional inclusion lines,
16612 as well as general symbol substitution sequences.
16614 The preprocessor conditional inclusion commands have the form
16616 @smallexample
16617 @group
16618 @cartouche
16619 #if @i{expression} [then]
16620    lines
16621 #elsif @i{expression} [then]
16622    lines
16623 #elsif @i{expression} [then]
16624    lines
16626 #else
16627    lines
16628 #end if;
16629 @end cartouche
16630 @end group
16631 @end smallexample
16633 @noindent
16634 In this example, @i{expression} is defined by the following grammar:
16635 @smallexample
16636 @i{expression} ::=  <symbol>
16637 @i{expression} ::=  <symbol> = "<value>"
16638 @i{expression} ::=  <symbol> = <symbol>
16639 @i{expression} ::=  <symbol> 'Defined
16640 @i{expression} ::=  not @i{expression}
16641 @i{expression} ::=  @i{expression} and @i{expression}
16642 @i{expression} ::=  @i{expression} or @i{expression}
16643 @i{expression} ::=  @i{expression} and then @i{expression}
16644 @i{expression} ::=  @i{expression} or else @i{expression}
16645 @i{expression} ::=  ( @i{expression} )
16646 @end smallexample
16648 @noindent
16649 For the first test (@i{expression} ::= <symbol>) the symbol must have
16650 either the value true or false, that is to say the right-hand of the
16651 symbol definition must be one of the (case-insensitive) literals
16652 @code{True} or @code{False}. If the value is true, then the
16653 corresponding lines are included, and if the value is false, they are
16654 excluded.
16656 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16657 the symbol has been defined in the definition file or by a @option{-D}
16658 switch on the command line. Otherwise, the test is false.
16660 The equality tests are case insensitive, as are all the preprocessor lines.
16662 If the symbol referenced is not defined in the symbol definitions file,
16663 then the effect depends on whether or not switch @option{-u}
16664 is specified. If so, then the symbol is treated as if it had the value
16665 false and the test fails. If this switch is not specified, then
16666 it is an error to reference an undefined symbol. It is also an error to
16667 reference a symbol that is defined with a value other than @code{True}
16668 or @code{False}.
16670 The use of the @code{not} operator inverts the sense of this logical test, so
16671 that the lines are included only if the symbol is not defined.
16672 The @code{then} keyword is optional as shown
16674 The @code{#} must be the first non-blank character on a line, but
16675 otherwise the format is free form. Spaces or tabs may appear between
16676 the @code{#} and the keyword. The keywords and the symbols are case
16677 insensitive as in normal Ada code. Comments may be used on a
16678 preprocessor line, but other than that, no other tokens may appear on a
16679 preprocessor line. Any number of @code{elsif} clauses can be present,
16680 including none at all. The @code{else} is optional, as in Ada.
16682 The @code{#} marking the start of a preprocessor line must be the first
16683 non-blank character on the line, i.e. it must be preceded only by
16684 spaces or horizontal tabs.
16686 Symbol substitution outside of preprocessor lines is obtained by using
16687 the sequence
16689 @smallexample
16690 $symbol
16691 @end smallexample
16693 @noindent
16694 anywhere within a source line, except in a comment or within a
16695 string literal. The identifier
16696 following the @code{$} must match one of the symbols defined in the symbol
16697 definition file, and the result is to substitute the value of the
16698 symbol in place of @code{$symbol} in the output file.
16700 Note that although the substitution of strings within a string literal
16701 is not possible, it is possible to have a symbol whose defined value is
16702 a string literal. So instead of setting XYZ to @code{hello} and writing:
16704 @smallexample
16705 Header : String := "$XYZ";
16706 @end smallexample
16708 @noindent
16709 you should set XYZ to @code{"hello"} and write:
16711 @smallexample
16712 Header : String := $XYZ;
16713 @end smallexample
16715 @noindent
16716 and then the substitution will occur as desired.
16718 @ifset vms
16719 @node The GNAT Run-Time Library Builder gnatlbr
16720 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
16721 @findex gnatlbr
16722 @cindex Library builder
16724 @noindent
16725 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
16726 supplied configuration pragmas.
16728 @menu
16729 * Running gnatlbr::
16730 * Switches for gnatlbr::
16731 * Examples of gnatlbr Usage::
16732 @end menu
16734 @node Running gnatlbr
16735 @section Running @code{gnatlbr}
16737 @noindent
16738 The @code{gnatlbr} command has the form
16740 @smallexample
16741 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
16742 @end smallexample
16744 @node Switches for gnatlbr
16745 @section Switches for @code{gnatlbr}
16747 @noindent
16748 @code{gnatlbr} recognizes the following switches:
16750 @table @option
16751 @c !sort!
16752 @item /CREATE=directory
16753 @cindex @code{/CREATE} (@code{gnatlbr})
16754      Create the new run-time library in the specified directory.
16756 @item /SET=directory
16757 @cindex @code{/SET} (@code{gnatlbr})
16758      Make the library in the specified directory the current run-time
16759      library.
16761 @item /DELETE=directory
16762 @cindex @code{/DELETE} (@code{gnatlbr})
16763      Delete the run-time library in the specified directory.
16765 @item /CONFIG=file
16766 @cindex @code{/CONFIG} (@code{gnatlbr})
16767      With /CREATE:
16768      Use the configuration pragmas in the specified file when building
16769      the library.
16771      With /SET:
16772      Use the configuration pragmas in the specified file when compiling.
16774 @end table
16776 @node Examples of gnatlbr Usage
16777 @section Example of @code{gnatlbr} Usage
16779 @smallexample
16780 Contents of VAXFLOAT.ADC:
16781 pragma Float_Representation (VAX_Float);
16783 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
16785 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
16787 @end smallexample
16788 @end ifset
16790 @node The GNAT Library Browser gnatls
16791 @chapter The GNAT Library Browser @code{gnatls}
16792 @findex gnatls
16793 @cindex Library browser
16795 @noindent
16796 @code{gnatls} is a tool that outputs information about compiled
16797 units. It gives the relationship between objects, unit names and source
16798 files. It can also be used to check the source dependencies of a unit
16799 as well as various characteristics.
16801 @menu
16802 * Running gnatls::
16803 * Switches for gnatls::
16804 * Examples of gnatls Usage::
16805 @end menu
16807 @node Running gnatls
16808 @section Running @code{gnatls}
16810 @noindent
16811 The @code{gnatls} command has the form
16813 @smallexample
16814 $ gnatls switches @var{object_or_ali_file}
16815 @end smallexample
16817 @noindent
16818 The main argument is the list of object or @file{ali} files
16819 (@pxref{The Ada Library Information Files})
16820 for which information is requested.
16822 In normal mode, without additional option, @code{gnatls} produces a
16823 four-column listing. Each line represents information for a specific
16824 object. The first column gives the full path of the object, the second
16825 column gives the name of the principal unit in this object, the third
16826 column gives the status of the source and the fourth column gives the
16827 full path of the source representing this unit.
16828 Here is a simple example of use:
16830 @smallexample
16831 $ gnatls *.o
16832 ^./^[]^demo1.o            demo1            DIF demo1.adb
16833 ^./^[]^demo2.o            demo2             OK demo2.adb
16834 ^./^[]^hello.o            h1                OK hello.adb
16835 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
16836 ^./^[]^instr.o            instr             OK instr.adb
16837 ^./^[]^tef.o              tef              DIF tef.adb
16838 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
16839 ^./^[]^tgef.o             tgef             DIF tgef.adb
16840 @end smallexample
16842 @noindent
16843 The first line can be interpreted as follows: the main unit which is
16844 contained in
16845 object file @file{demo1.o} is demo1, whose main source is in
16846 @file{demo1.adb}. Furthermore, the version of the source used for the
16847 compilation of demo1 has been modified (DIF). Each source file has a status
16848 qualifier which can be:
16850 @table @code
16851 @item OK (unchanged)
16852 The version of the source file used for the compilation of the
16853 specified unit corresponds exactly to the actual source file.
16855 @item MOK (slightly modified)
16856 The version of the source file used for the compilation of the
16857 specified unit differs from the actual source file but not enough to
16858 require recompilation. If you use gnatmake with the qualifier
16859 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16860 MOK will not be recompiled.
16862 @item DIF (modified)
16863 No version of the source found on the path corresponds to the source
16864 used to build this object.
16866 @item ??? (file not found)
16867 No source file was found for this unit.
16869 @item HID (hidden,  unchanged version not first on PATH)
16870 The version of the source that corresponds exactly to the source used
16871 for compilation has been found on the path but it is hidden by another
16872 version of the same source that has been modified.
16874 @end table
16876 @node Switches for gnatls
16877 @section Switches for @code{gnatls}
16879 @noindent
16880 @code{gnatls} recognizes the following switches:
16882 @table @option
16883 @c !sort!
16884 @item ^-a^/ALL_UNITS^
16885 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16886 Consider all units, including those of the predefined Ada library.
16887 Especially useful with @option{^-d^/DEPENDENCIES^}.
16889 @item ^-d^/DEPENDENCIES^
16890 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16891 List sources from which specified units depend on.
16893 @item ^-h^/OUTPUT=OPTIONS^
16894 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16895 Output the list of options.
16897 @item ^-o^/OUTPUT=OBJECTS^
16898 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16899 Only output information about object files.
16901 @item ^-s^/OUTPUT=SOURCES^
16902 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16903 Only output information about source files.
16905 @item ^-u^/OUTPUT=UNITS^
16906 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16907 Only output information about compilation units.
16909 @item ^-files^/FILES^=@var{file}
16910 @cindex @option{^-files^/FILES^} (@code{gnatls})
16911 Take as arguments the files listed in text file @var{file}.
16912 Text file @var{file} may contain empty lines that are ignored.
16913 Each non empty line should contain the name of an existing file.
16914 Several such switches may be specified simultaneously.
16916 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16917 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16918 @itemx ^-I^/SEARCH=^@var{dir}
16919 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
16920 @itemx -nostdinc
16921 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16922 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16923 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16924 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16925 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16926 flags (@pxref{Switches for gnatmake}).
16928 @item --RTS=@var{rts-path}
16929 @cindex @option{--RTS} (@code{gnatls})
16930 Specifies the default location of the runtime library. Same meaning as the
16931 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16933 @item ^-v^/OUTPUT=VERBOSE^
16934 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16935 Verbose mode. Output the complete source, object and project paths. Do not use
16936 the default column layout but instead use long format giving as much as
16937 information possible on each requested units, including special
16938 characteristics such as:
16940 @table @code
16941 @item  Preelaborable
16942 The unit is preelaborable in the Ada 95 sense.
16944 @item No_Elab_Code
16945 No elaboration code has been produced by the compiler for this unit.
16947 @item Pure
16948 The unit is pure in the Ada 95 sense.
16950 @item Elaborate_Body
16951 The unit contains a pragma Elaborate_Body.
16953 @item Remote_Types
16954 The unit contains a pragma Remote_Types.
16956 @item Shared_Passive
16957 The unit contains a pragma Shared_Passive.
16959 @item Predefined
16960 This unit is part of the predefined environment and cannot be modified
16961 by the user.
16963 @item Remote_Call_Interface
16964 The unit contains a pragma Remote_Call_Interface.
16966 @end table
16968 @end table
16970 @node Examples of gnatls Usage
16971 @section Example of @code{gnatls} Usage
16972 @ifclear vms
16974 @noindent
16975 Example of using the verbose switch. Note how the source and
16976 object paths are affected by the -I switch.
16978 @smallexample
16979 $ gnatls -v -I.. demo1.o
16981 GNATLS 5.03w (20041123-34)
16982 Copyright 1997-2004 Free Software Foundation, Inc.
16984 Source Search Path:
16985    <Current_Directory>
16986    ../
16987    /home/comar/local/adainclude/
16989 Object Search Path:
16990    <Current_Directory>
16991    ../
16992    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16994 Project Search Path:
16995    <Current_Directory>
16996    /home/comar/local/lib/gnat/
16998 ./demo1.o
16999    Unit =>
17000      Name   => demo1
17001      Kind   => subprogram body
17002      Flags  => No_Elab_Code
17003      Source => demo1.adb    modified
17004 @end smallexample
17006 @noindent
17007 The following is an example of use of the dependency list.
17008 Note the use of the -s switch
17009 which gives a straight list of source files. This can be useful for
17010 building specialized scripts.
17012 @smallexample
17013 $ gnatls -d demo2.o
17014 ./demo2.o   demo2        OK demo2.adb
17015                          OK gen_list.ads
17016                          OK gen_list.adb
17017                          OK instr.ads
17018                          OK instr-child.ads
17020 $ gnatls -d -s -a demo1.o
17021 demo1.adb
17022 /home/comar/local/adainclude/ada.ads
17023 /home/comar/local/adainclude/a-finali.ads
17024 /home/comar/local/adainclude/a-filico.ads
17025 /home/comar/local/adainclude/a-stream.ads
17026 /home/comar/local/adainclude/a-tags.ads
17027 gen_list.ads
17028 gen_list.adb
17029 /home/comar/local/adainclude/gnat.ads
17030 /home/comar/local/adainclude/g-io.ads
17031 instr.ads
17032 /home/comar/local/adainclude/system.ads
17033 /home/comar/local/adainclude/s-exctab.ads
17034 /home/comar/local/adainclude/s-finimp.ads
17035 /home/comar/local/adainclude/s-finroo.ads
17036 /home/comar/local/adainclude/s-secsta.ads
17037 /home/comar/local/adainclude/s-stalib.ads
17038 /home/comar/local/adainclude/s-stoele.ads
17039 /home/comar/local/adainclude/s-stratt.ads
17040 /home/comar/local/adainclude/s-tasoli.ads
17041 /home/comar/local/adainclude/s-unstyp.ads
17042 /home/comar/local/adainclude/unchconv.ads
17043 @end smallexample
17044 @end ifclear
17046 @ifset vms
17047 @smallexample
17048 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17050 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17051 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17052 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17053 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17054 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17055 demo1.adb
17056 gen_list.ads
17057 gen_list.adb
17058 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17059 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17060 instr.ads
17061 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17062 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17063 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17064 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17065 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17066 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17067 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17068 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17069 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17070 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17071 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17072 @end smallexample
17073 @end ifset
17075 @node Cleaning Up Using gnatclean
17076 @chapter Cleaning Up Using @code{gnatclean}
17077 @findex gnatclean
17078 @cindex Cleaning tool
17080 @noindent
17081 @code{gnatclean} is a tool that allows the deletion of files produced by the
17082 compiler, binder and linker, including ALI files, object files, tree files,
17083 expanded source files, library files, interface copy source files, binder
17084 generated files and executable files.
17086 @menu
17087 * Running gnatclean::
17088 * Switches for gnatclean::
17089 @c * Examples of gnatclean Usage::
17090 @end menu
17092 @node Running gnatclean
17093 @section Running @code{gnatclean}
17095 @noindent
17096 The @code{gnatclean} command has the form:
17098 @smallexample
17099 $ gnatclean switches @var{names}
17100 @end smallexample
17102 @noindent
17103 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17104 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17105 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17107 @noindent
17108 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17109 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17110 the linker. In informative-only mode, specified by switch
17111 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17112 normal mode is listed, but no file is actually deleted.
17114 @node Switches for gnatclean
17115 @section Switches for @code{gnatclean}
17117 @noindent
17118 @code{gnatclean} recognizes the following switches:
17120 @table @option
17121 @c !sort!
17122 @item ^-c^/COMPILER_FILES_ONLY^
17123 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17124 Only attempt to delete the files produced by the compiler, not those produced
17125 by the binder or the linker. The files that are not to be deleted are library
17126 files, interface copy files, binder generated files and executable files.
17128 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17129 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17130 Indicate that ALI and object files should normally be found in directory
17131 @var{dir}.
17133 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17134 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17135 When using project files, if some errors or warnings are detected during
17136 parsing and verbose mode is not in effect (no use of switch
17137 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17138 file, rather than its simple file name.
17140 @item ^-h^/HELP^
17141 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17142 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17144 @item ^-n^/NODELETE^
17145 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17146 Informative-only mode. Do not delete any files. Output the list of the files
17147 that would have been deleted if this switch was not specified.
17149 @item ^-P^/PROJECT_FILE=^@var{project}
17150 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17151 Use project file @var{project}. Only one such switch can be used.
17152 When cleaning a project file, the files produced by the compilation of the
17153 immediate sources or inherited sources of the project files are to be
17154 deleted. This is not depending on the presence or not of executable names
17155 on the command line.
17157 @item ^-q^/QUIET^
17158 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17159 Quiet output. If there are no errors, do not output anything, except in
17160 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17161 (switch ^-n^/NODELETE^).
17163 @item ^-r^/RECURSIVE^
17164 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17165 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17166 clean all imported and extended project files, recursively. If this switch
17167 is not specified, only the files related to the main project file are to be
17168 deleted. This switch has no effect if no project file is specified.
17170 @item ^-v^/VERBOSE^
17171 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17172 Verbose mode.
17174 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17175 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17176 Indicates the verbosity of the parsing of GNAT project files.
17177 @xref{Switches Related to Project Files}.
17179 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17180 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17181 Indicates that external variable @var{name} has the value @var{value}.
17182 The Project Manager will use this value for occurrences of
17183 @code{external(name)} when parsing the project file.
17184 @xref{Switches Related to Project Files}.
17186 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17187 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17188 When searching for ALI and object files, look in directory
17189 @var{dir}.
17191 @item ^-I^/SEARCH=^@var{dir}
17192 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17193 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17195 @item ^-I-^/NOCURRENT_DIRECTORY^
17196 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17197 @cindex Source files, suppressing search
17198 Do not look for ALI or object files in the directory
17199 where @code{gnatclean} was invoked.
17201 @end table
17203 @c @node Examples of gnatclean Usage
17204 @c @section Examples of @code{gnatclean} Usage
17206 @ifclear vms
17207 @node GNAT and Libraries
17208 @chapter GNAT and Libraries
17209 @cindex Library, building, installing, using
17211 @noindent
17212 This chapter describes how to build and use libraries with GNAT, and also shows
17213 how to recompile the GNAT run-time library. You should be familiar with the
17214 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17215 chapter.
17217 @menu
17218 * Introduction to Libraries in GNAT::
17219 * General Ada Libraries::
17220 * Stand-alone Ada Libraries::
17221 * Rebuilding the GNAT Run-Time Library::
17222 @end menu
17224 @node Introduction to Libraries in GNAT
17225 @section Introduction to Libraries in GNAT
17227 @noindent
17228 A library is, conceptually, a collection of objects which does not have its
17229 own main thread of execution, but rather provides certain services to the
17230 applications that use it. A library can be either statically linked with the
17231 application, in which case its code is directly included in the application,
17232 or, on platforms that support it, be dynamically linked, in which case
17233 its code is shared by all applications making use of this library.
17235 GNAT supports both types of libraries.
17236 In the static case, the compiled code can be provided in different ways. The
17237 simplest approach is to provide directly the set of objects resulting from
17238 compilation of the library source files. Alternatively, you can group the
17239 objects into an archive using whatever commands are provided by the operating
17240 system. For the latter case, the objects are grouped into a shared library.
17242 In the GNAT environment, a library has three types of components:
17243 @itemize @bullet
17244 @item
17245 Source files.
17246 @item
17247 @file{ALI} files.
17248 @xref{The Ada Library Information Files}.
17249 @item
17250 Object files, an archive or a shared library.
17251 @end itemize
17253 @noindent
17254 A GNAT library may expose all its source files, which is useful for
17255 documentation purposes. Alternatively, it may expose only the units needed by
17256 an external user to make use of the library. That is to say, the specs
17257 reflecting the library services along with all the units needed to compile
17258 those specs, which can include generic bodies or any body implementing an
17259 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17260 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17262 All compilation units comprising an application, including those in a library,
17263 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17264 computes the elaboration order from the @file{ALI} files and this is why they
17265 constitute a mandatory part of GNAT libraries. Except in the case of
17266 @emph{stand-alone libraries}, where a specific library elaboration routine is
17267 produced independently of the application(s) using the library.
17269 @node General Ada Libraries
17270 @section General Ada Libraries
17272 @menu
17273 * Building a library::
17274 * Installing a library::
17275 * Using a library::
17276 @end menu
17278 @node Building a library
17279 @subsection Building a library
17281 @noindent
17282 The easiest way to build a library is to use the Project Manager,
17283 which supports a special type of project called a @emph{Library Project}
17284 (@pxref{Library Projects}).
17286 A project is considered a library project, when two project-level attributes
17287 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17288 control different aspects of library configuration, additional optional
17289 project-level attributes can be specified:
17290 @table @code
17291 @item Library_Kind
17292 This attribute controls whether the library is to be static or dynamic
17294 @item Library_Version
17295 This attribute specifies the library version; this value is used
17296 during dynamic linking of shared libraries to determine if the currently
17297 installed versions of the binaries are compatible.
17299 @item Library_Options
17300 @item Library_GCC
17301 These attributes specify additional low-level options to be used during
17302 library generation, and redefine the actual application used to generate
17303 library.
17304 @end table
17306 @noindent
17307 The GNAT Project Manager takes full care of the library maintenance task,
17308 including recompilation of the source files for which objects do not exist
17309 or are not up to date, assembly of the library archive, and installation of
17310 the library (i.e., copying associated source, object and @file{ALI} files
17311 to the specified location).
17313 Here is a simple library project file:
17314 @smallexample @c ada
17315 project My_Lib is
17316    for Source_Dirs use ("src1", "src2");
17317    for Object_Dir use "obj";
17318    for Library_Name use "mylib";
17319    for Library_Dir use "lib";
17320    for Library_Kind use "dynamic";
17321 end My_lib;
17322 @end smallexample
17324 @noindent
17325 and the compilation command to build and install the library:
17327 @smallexample @c ada
17328   $ gnatmake -Pmy_lib
17329 @end smallexample
17331 @noindent
17332 It is not entirely trivial to perform manually all the steps required to
17333 produce a library. We recommend that you use the GNAT Project Manager
17334 for this task. In special cases where this is not desired, the necessary
17335 steps are discussed below.
17337 There are various possibilities for compiling the units that make up the
17338 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17339 with a conventional script. For simple libraries, it is also possible to create
17340 a dummy main program which depends upon all the packages that comprise the
17341 interface of the library. This dummy main program can then be given to
17342 @command{gnatmake}, which will ensure that all necessary objects are built.
17344 After this task is accomplished, you should follow the standard procedure
17345 of the underlying operating system to produce the static or shared library.
17347 Here is an example of such a dummy program:
17348 @smallexample @c ada
17349 @group
17350 with My_Lib.Service1;
17351 with My_Lib.Service2;
17352 with My_Lib.Service3;
17353 procedure My_Lib_Dummy is
17354 begin
17355    null;
17356 end;
17357 @end group
17358 @end smallexample
17360 @noindent
17361 Here are the generic commands that will build an archive or a shared library.
17363 @smallexample
17364 # compiling the library
17365 $ gnatmake -c my_lib_dummy.adb
17367 # we don't need the dummy object itself
17368 $ rm my_lib_dummy.o my_lib_dummy.ali
17370 # create an archive with the remaining objects
17371 $ ar rc libmy_lib.a *.o
17372 # some systems may require "ranlib" to be run as well
17374 # or create a shared library
17375 $ gcc -shared -o libmy_lib.so *.o
17376 # some systems may require the code to have been compiled with -fPIC
17378 # remove the object files that are now in the library
17379 $ rm *.o
17381 # Make the ALI files read-only so that gnatmake will not try to
17382 # regenerate the objects that are in the library
17383 $ chmod -w *.ali
17384 @end smallexample
17386 @noindent
17387 Please note that the library must have a name of the form @file{libxxx.a} or
17388 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
17389 the directive @option{-lxxx} at link time.
17391 @node Installing a library
17392 @subsection Installing a library
17393 @cindex @code{ADA_PROJECT_PATH}
17395 @noindent
17396 If you use project files, library installation is part of the library build
17397 process. Thus no further action is needed in order to make use of the
17398 libraries that are built as part of the general application build. A usable
17399 version of the library is installed in the directory specified by the
17400 @code{Library_Dir} attribute of the library project file.
17402 You may want to install a library in a context different from where the library
17403 is built. This situation arises with third party suppliers, who may want
17404 to distribute a library in binary form where the user is not expected to be
17405 able to recompile the library. The simplest option in this case is to provide
17406 a project file slightly different from the one used to build the library, by
17407 using the @code{externally_built} attribute. For instance, the project
17408 file used to build the library in the previous section can be changed into the
17409 following one when the library is installed:
17411 @smallexample @c projectfile
17412 project My_Lib is
17413    for Source_Dirs use ("src1", "src2");
17414    for Library_Name use "mylib";
17415    for Library_Dir use "lib";
17416    for Library_Kind use "dynamic";
17417    for Externally_Built use "true";
17418 end My_lib;
17419 @end smallexample
17421 @noindent
17422 This project file assumes that the directories @file{src1},
17423 @file{src2}, and @file{lib} exist in
17424 the directory containing the project file. The @code{externally_built}
17425 attribute makes it clear to the GNAT builder that it should not attempt to
17426 recompile any of the units from this library. It allows the library provider to
17427 restrict the source set to the minimum necessary for clients to make use of the
17428 library as described in the first section of this chapter. It is the
17429 responsibility of the library provider to install the necessary sources, ALI
17430 files and libraries in the directories mentioned in the project file. For
17431 convenience, the user's library project file should be installed in a location
17432 that will be searched automatically by the GNAT
17433 builder. These are the directories referenced in the @code{ADA_PROJECT_PATH}
17434 environment variable (@pxref{Importing Projects}), and also the default GNAT
17435 library location that can be queried with @command{gnatls -v} and is usually of
17436 the form $gnat_install_root/lib/gnat.
17438 When project files are not an option, it is also possible, but not recommended,
17439 to install the library so that the sources needed to use the library are on the
17440 Ada source path and the ALI files & libraries be on the Ada Object path (see
17441 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17442 administrator can place general-purpose libraries in the default compiler
17443 paths, by specifying the libraries' location in the configuration files
17444 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17445 must be located in the GNAT installation tree at the same place as the gcc spec
17446 file. The location of the gcc spec file can be determined as follows:
17447 @smallexample
17448 $ gcc -v
17449 @end smallexample
17451 @noindent
17452 The configuration files mentioned above have a simple format: each line
17453 must contain one unique directory name.
17454 Those names are added to the corresponding path
17455 in their order of appearance in the file. The names can be either absolute
17456 or relative; in the latter case, they are relative to where theses files
17457 are located.
17459 The files @file{ada_source_path} and @file{ada_object_path} might not be
17460 present in a
17461 GNAT installation, in which case, GNAT will look for its run-time library in
17462 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17463 objects and @file{ALI} files). When the files exist, the compiler does not
17464 look in @file{adainclude} and @file{adalib}, and thus the
17465 @file{ada_source_path} file
17466 must contain the location for the GNAT run-time sources (which can simply
17467 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17468 contain the location for the GNAT run-time objects (which can simply
17469 be @file{adalib}).
17471 You can also specify a new default path to the run-time library at compilation
17472 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17473 the run-time library you want your program to be compiled with. This switch is
17474 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17475 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17477 It is possible to install a library before or after the standard GNAT
17478 library, by reordering the lines in the configuration files. In general, a
17479 library must be installed before the GNAT library if it redefines
17480 any part of it.
17482 @node Using a library
17483 @subsection Using a library
17485 @noindent Once again, the project facility greatly simplifies the use of
17486 libraries. In this context, using a library is just a matter of adding a
17487 @code{with} clause in the user project. For instance, to make use of the
17488 library @code{My_Lib} shown in examples in earlier sections, you can
17489 write:
17491 @smallexample @c projectfile
17492 with "my_lib";
17493 project My_Proj is
17494   ...
17495 end My_Proj;
17496 @end smallexample
17498 Even if you have a third-party, non-Ada library, you can still use GNAT's
17499 Project Manager facility to provide a wrapper for it. For example, the
17500 following project, when @code{with}ed by your main project, will link with the
17501 third-party library @file{liba.a}:
17503 @smallexample @c projectfile
17504 @group
17505 project Liba is
17506    for Externally_Built use "true";
17507    for Library_Dir use "lib";
17508    for Library_Name use "a";
17509    for Library_Kind use "static";
17510 end Liba;
17511 @end group
17512 @end smallexample
17513 This is an alternative to the use of @code{pragma Linker_Options}. It is
17514 especially interesting in the context of systems with several interdependent
17515 static libraries where finding a proper linker order is not easy and best be
17516 left to the tools having visibility over project dependence information.
17518 @noindent
17519 In order to use an Ada library manually, you need to make sure that this
17520 library is on both your source and object path
17521 (see @ref{Search Paths and the Run-Time Library (RTL)}
17522 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17523 in an archive or a shared library, you need to specify the desired
17524 library at link time.
17526 For example, you can use the library @file{mylib} installed in
17527 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17529 @smallexample
17530 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17531   -largs -lmy_lib
17532 @end smallexample
17534 @noindent
17535 This can be expressed more simply:
17536 @smallexample
17537 $ gnatmake my_appl
17538 @end smallexample
17539 @noindent
17540 when the following conditions are met:
17541 @itemize @bullet
17542 @item
17543 @file{/dir/my_lib_src} has been added by the user to the environment
17544 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
17545 @file{ada_source_path}
17546 @item
17547 @file{/dir/my_lib_obj} has been added by the user to the environment
17548 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
17549 @file{ada_object_path}
17550 @item
17551 a pragma @code{Linker_Options} has been added to one of the sources.
17552 For example:
17554 @smallexample @c ada
17555 pragma Linker_Options ("-lmy_lib");
17556 @end smallexample
17557 @end itemize
17559 @node Stand-alone Ada Libraries
17560 @section Stand-alone Ada Libraries
17561 @cindex Stand-alone library, building, using
17563 @menu
17564 * Introduction to Stand-alone Libraries::
17565 * Building a Stand-alone Library::
17566 * Creating a Stand-alone Library to be used in a non-Ada context::
17567 * Restrictions in Stand-alone Libraries::
17568 @end menu
17570 @node Introduction to Stand-alone Libraries
17571 @subsection Introduction to Stand-alone Libraries
17573 @noindent
17574 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17575 necessary code to
17576 elaborate the Ada units that are included in the library. In contrast with
17577 an ordinary library, which consists of all sources, objects and @file{ALI}
17578 files of the
17579 library, a SAL may specify a restricted subset of compilation units
17580 to serve as a library interface. In this case, the fully
17581 self-sufficient set of files will normally consist of an objects
17582 archive, the sources of interface units' specs, and the @file{ALI}
17583 files of interface units.
17584 If an interface spec contains a generic unit or an inlined subprogram,
17585 the body's
17586 source must also be provided; if the units that must be provided in the source
17587 form depend on other units, the source and @file{ALI} files of those must
17588 also be provided.
17590 The main purpose of a SAL is to minimize the recompilation overhead of client
17591 applications when a new version of the library is installed. Specifically,
17592 if the interface sources have not changed, client applications do not need to
17593 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17594 version, controlled by @code{Library_Version} attribute, is not changed,
17595 then the clients do not need to be relinked.
17597 SALs also allow the library providers to minimize the amount of library source
17598 text exposed to the clients.  Such ``information hiding'' might be useful or
17599 necessary for various reasons.
17601 Stand-alone libraries are also well suited to be used in an executable whose
17602 main routine is not written in Ada.
17604 @node Building a Stand-alone Library
17605 @subsection Building a Stand-alone Library
17607 @noindent
17608 GNAT's Project facility provides a simple way of building and installing
17609 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17610 To be a Stand-alone Library Project, in addition to the two attributes
17611 that make a project a Library Project (@code{Library_Name} and
17612 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17613 @code{Library_Interface} must be defined.  For example:
17615 @smallexample @c projectfile
17616 @group
17617    for Library_Dir use "lib_dir";
17618    for Library_Name use "dummy";
17619    for Library_Interface use ("int1", "int1.child");
17620 @end group
17621 @end smallexample
17623 @noindent
17624 Attribute @code{Library_Interface} has a non-empty string list value,
17625 each string in the list designating a unit contained in an immediate source
17626 of the project file.
17628 When a Stand-alone Library is built, first the binder is invoked to build
17629 a package whose name depends on the library name
17630 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17631 This binder-generated package includes initialization and
17632 finalization procedures whose
17633 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17634 in the example
17635 above). The object corresponding to this package is included in the library.
17637 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17638 calling of these procedures if a static SAL is built, or if a shared SAL
17639 is built
17640 with the project-level attribute @code{Library_Auto_Init} set to
17641 @code{"false"}.
17643 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17644 (those that are listed in attribute @code{Library_Interface}) are copied to
17645 the Library Directory. As a consequence, only the Interface Units may be
17646 imported from Ada units outside of the library. If other units are imported,
17647 the binding phase will fail.
17649 The attribute @code{Library_Src_Dir} may be specified for a
17650 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17651 single string value. Its value must be the path (absolute or relative to the
17652 project directory) of an existing directory. This directory cannot be the
17653 object directory or one of the source directories, but it can be the same as
17654 the library directory. The sources of the Interface
17655 Units of the library that are needed by an Ada client of the library will be
17656 copied to the designated directory, called the Interface Copy directory.
17657 These sources include the specs of the Interface Units, but they may also
17658 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17659 are used, or when there is a generic unit in the spec. Before the sources
17660 are copied to the Interface Copy directory, an attempt is made to delete all
17661 files in the Interface Copy directory.
17663 Building stand-alone libraries by hand is somewhat tedious, but for those
17664 occasions when it is necessary here are the steps that you need to perform:
17665 @itemize @bullet
17666 @item
17667 Compile all library sources.
17669 @item
17670 Invoke the binder with the switch @option{-n} (No Ada main program),
17671 with all the @file{ALI} files of the interfaces, and
17672 with the switch @option{-L} to give specific names to the @code{init}
17673 and @code{final} procedures.  For example:
17674 @smallexample
17675   gnatbind -n int1.ali int2.ali -Lsal1
17676 @end smallexample
17678 @item
17679 Compile the binder generated file:
17680 @smallexample
17681   gcc -c b~int2.adb
17682 @end smallexample
17684 @item
17685 Link the dynamic library with all the necessary object files,
17686 indicating to the linker the names of the @code{init} (and possibly
17687 @code{final}) procedures for automatic initialization (and finalization).
17688 The built library should be placed in a directory different from
17689 the object directory.
17691 @item
17692 Copy the @code{ALI} files of the interface to the library directory,
17693 add in this copy an indication that it is an interface to a SAL
17694 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
17695 with letter ``P'') and make the modified copy of the @file{ALI} file
17696 read-only.
17697 @end itemize
17699 @noindent
17700 Using SALs is not different from using other libraries
17701 (see @ref{Using a library}).
17703 @node Creating a Stand-alone Library to be used in a non-Ada context
17704 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17706 @noindent
17707 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17708 a non-Ada context.
17710 The only extra step required is to ensure that library interface subprograms
17711 are compatible with the main program, by means of @code{pragma Export}
17712 or @code{pragma Convention}.
17714 Here is an example of simple library interface for use with C main program:
17716 @smallexample @c ada
17717 package Interface is
17719    procedure Do_Something;
17720    pragma Export (C, Do_Something, "do_something");
17722    procedure Do_Something_Else;
17723    pragma Export (C, Do_Something_Else, "do_something_else");
17725 end Interface;
17726 @end smallexample
17728 @noindent
17729 On the foreign language side, you must provide a ``foreign'' view of the
17730 library interface; remember that it should contain elaboration routines in
17731 addition to interface subprograms.
17733 The example below shows the content of @code{mylib_interface.h} (note
17734 that there is no rule for the naming of this file, any name can be used)
17735 @smallexample
17736 /* the library elaboration procedure */
17737 extern void mylibinit (void);
17739 /* the library finalization procedure */
17740 extern void mylibfinal (void);
17742 /* the interface exported by the library */
17743 extern void do_something (void);
17744 extern void do_something_else (void);
17745 @end smallexample
17747 @noindent
17748 Libraries built as explained above can be used from any program, provided
17749 that the elaboration procedures (named @code{mylibinit} in the previous
17750 example) are called before the library services are used. Any number of
17751 libraries can be used simultaneously, as long as the elaboration
17752 procedure of each library is called.
17754 Below is an example of a C program that uses the @code{mylib} library.
17756 @smallexample
17757 #include "mylib_interface.h"
17760 main (void)
17762    /* First, elaborate the library before using it */
17763    mylibinit ();
17765    /* Main program, using the library exported entities */
17766    do_something ();
17767    do_something_else ();
17769    /* Library finalization at the end of the program */
17770    mylibfinal ();
17771    return 0;
17773 @end smallexample
17775 @noindent
17776 Note that invoking any library finalization procedure generated by
17777 @code{gnatbind} shuts down the Ada run-time environment.
17778 Consequently, the
17779 finalization of all Ada libraries must be performed at the end of the program.
17780 No call to these libraries or to the Ada run-time library should be made
17781 after the finalization phase.
17783 @node Restrictions in Stand-alone Libraries
17784 @subsection Restrictions in Stand-alone Libraries
17786 @noindent
17787 The pragmas listed below should be used with caution inside libraries,
17788 as they can create incompatibilities with other Ada libraries:
17789 @itemize @bullet
17790 @item pragma @code{Locking_Policy}
17791 @item pragma @code{Queuing_Policy}
17792 @item pragma @code{Task_Dispatching_Policy}
17793 @item pragma @code{Unreserve_All_Interrupts}
17794 @end itemize
17796 @noindent
17797 When using a library that contains such pragmas, the user must make sure
17798 that all libraries use the same pragmas with the same values. Otherwise,
17799 @code{Program_Error} will
17800 be raised during the elaboration of the conflicting
17801 libraries. The usage of these pragmas and its consequences for the user
17802 should therefore be well documented.
17804 Similarly, the traceback in the exception occurrence mechanism should be
17805 enabled or disabled in a consistent manner across all libraries.
17806 Otherwise, Program_Error will be raised during the elaboration of the
17807 conflicting libraries.
17809 If the @code{Version} or @code{Body_Version}
17810 attributes are used inside a library, then you need to
17811 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17812 libraries, so that version identifiers can be properly computed.
17813 In practice these attributes are rarely used, so this is unlikely
17814 to be a consideration.
17816 @node  Rebuilding the GNAT Run-Time Library
17817 @section Rebuilding the GNAT Run-Time Library
17818 @cindex GNAT Run-Time Library, rebuilding
17819 @cindex Building the GNAT Run-Time Library
17820 @cindex Rebuilding the GNAT Run-Time Library
17821 @cindex Run-Time Library, rebuilding
17823 @noindent
17824 It may be useful to recompile the GNAT library in various contexts, the
17825 most important one being the use of partition-wide configuration pragmas
17826 such as @code{Normalize_Scalars}. A special Makefile called
17827 @code{Makefile.adalib} is provided to that effect and can be found in
17828 the directory containing the GNAT library. The location of this
17829 directory depends on the way the GNAT environment has been installed and can
17830 be determined by means of the command:
17832 @smallexample
17833 $ gnatls -v
17834 @end smallexample
17836 @noindent
17837 The last entry in the object search path usually contains the
17838 gnat library. This Makefile contains its own documentation and in
17839 particular the set of instructions needed to rebuild a new library and
17840 to use it.
17842 @node Using the GNU make Utility
17843 @chapter Using the GNU @code{make} Utility
17844 @findex make
17846 @noindent
17847 This chapter offers some examples of makefiles that solve specific
17848 problems. It does not explain how to write a makefile (see the GNU make
17849 documentation), nor does it try to replace the @command{gnatmake} utility
17850 (@pxref{The GNAT Make Program gnatmake}).
17852 All the examples in this section are specific to the GNU version of
17853 make. Although @code{make} is a standard utility, and the basic language
17854 is the same, these examples use some advanced features found only in
17855 @code{GNU make}.
17857 @menu
17858 * Using gnatmake in a Makefile::
17859 * Automatically Creating a List of Directories::
17860 * Generating the Command Line Switches::
17861 * Overcoming Command Line Length Limits::
17862 @end menu
17864 @node Using gnatmake in a Makefile
17865 @section Using gnatmake in a Makefile
17866 @findex makefile
17867 @cindex GNU make
17869 @noindent
17870 Complex project organizations can be handled in a very powerful way by
17871 using GNU make combined with gnatmake. For instance, here is a Makefile
17872 which allows you to build each subsystem of a big project into a separate
17873 shared library. Such a makefile allows you to significantly reduce the link
17874 time of very big applications while maintaining full coherence at
17875 each step of the build process.
17877 The list of dependencies are handled automatically by
17878 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17879 the appropriate directories.
17881 Note that you should also read the example on how to automatically
17882 create the list of directories
17883 (@pxref{Automatically Creating a List of Directories})
17884 which might help you in case your project has a lot of subdirectories.
17886 @smallexample
17887 @iftex
17888 @leftskip=0cm
17889 @font@heightrm=cmr8
17890 @heightrm
17891 @end iftex
17892 ## This Makefile is intended to be used with the following directory
17893 ## configuration:
17894 ##  - The sources are split into a series of csc (computer software components)
17895 ##    Each of these csc is put in its own directory.
17896 ##    Their name are referenced by the directory names.
17897 ##    They will be compiled into shared library (although this would also work
17898 ##    with static libraries
17899 ##  - The main program (and possibly other packages that do not belong to any
17900 ##    csc is put in the top level directory (where the Makefile is).
17901 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17902 ##                    \_ second_csc (sources) __ lib (will contain the library)
17903 ##                    \_ ...
17904 ## Although this Makefile is build for shared library, it is easy to modify
17905 ## to build partial link objects instead (modify the lines with -shared and
17906 ## gnatlink below)
17908 ## With this makefile, you can change any file in the system or add any new
17909 ## file, and everything will be recompiled correctly (only the relevant shared
17910 ## objects will be recompiled, and the main program will be re-linked).
17912 # The list of computer software component for your project. This might be
17913 # generated automatically.
17914 CSC_LIST=aa bb cc
17916 # Name of the main program (no extension)
17917 MAIN=main
17919 # If we need to build objects with -fPIC, uncomment the following line
17920 #NEED_FPIC=-fPIC
17922 # The following variable should give the directory containing libgnat.so
17923 # You can get this directory through 'gnatls -v'. This is usually the last
17924 # directory in the Object_Path.
17925 GLIB=...
17927 # The directories for the libraries
17928 # (This macro expands the list of CSC to the list of shared libraries, you
17929 # could simply use the expanded form :
17930 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17931 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17933 $@{MAIN@}: objects $@{LIB_DIR@}
17934     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17935     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17937 objects::
17938     # recompile the sources
17939     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17941 # Note: In a future version of GNAT, the following commands will be simplified
17942 # by a new tool, gnatmlib
17943 $@{LIB_DIR@}:
17944     mkdir -p $@{dir $@@ @}
17945     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17946     cd $@{dir $@@ @}; cp -f ../*.ali .
17948 # The dependencies for the modules
17949 # Note that we have to force the expansion of *.o, since in some cases
17950 # make won't be able to do it itself.
17951 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17952 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17953 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17955 # Make sure all of the shared libraries are in the path before starting the
17956 # program
17957 run::
17958     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17960 clean::
17961     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17962     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17963     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17964     $@{RM@} *.o *.ali $@{MAIN@}
17965 @end smallexample
17967 @node Automatically Creating a List of Directories
17968 @section Automatically Creating a List of Directories
17970 @noindent
17971 In most makefiles, you will have to specify a list of directories, and
17972 store it in a variable. For small projects, it is often easier to
17973 specify each of them by hand, since you then have full control over what
17974 is the proper order for these directories, which ones should be
17975 included...
17977 However, in larger projects, which might involve hundreds of
17978 subdirectories, it might be more convenient to generate this list
17979 automatically.
17981 The example below presents two methods. The first one, although less
17982 general, gives you more control over the list. It involves wildcard
17983 characters, that are automatically expanded by @code{make}. Its
17984 shortcoming is that you need to explicitly specify some of the
17985 organization of your project, such as for instance the directory tree
17986 depth, whether some directories are found in a separate tree,...
17988 The second method is the most general one. It requires an external
17989 program, called @code{find}, which is standard on all Unix systems. All
17990 the directories found under a given root directory will be added to the
17991 list.
17993 @smallexample
17994 @iftex
17995 @leftskip=0cm
17996 @font@heightrm=cmr8
17997 @heightrm
17998 @end iftex
17999 # The examples below are based on the following directory hierarchy:
18000 # All the directories can contain any number of files
18001 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
18002 #                       ->  ab
18003 #                       ->  ac
18004 #                ->  b  ->  ba  ->  baa
18005 #                       ->  bb
18006 #                       ->  bc
18007 # This Makefile creates a variable called DIRS, that can be reused any time
18008 # you need this list (see the other examples in this section)
18010 # The root of your project's directory hierarchy
18011 ROOT_DIRECTORY=.
18013 ####
18014 # First method: specify explicitly the list of directories
18015 # This allows you to specify any subset of all the directories you need.
18016 ####
18018 DIRS := a/aa/ a/ab/ b/ba/
18020 ####
18021 # Second method: use wildcards
18022 # Note that the argument(s) to wildcard below should end with a '/'.
18023 # Since wildcards also return file names, we have to filter them out
18024 # to avoid duplicate directory names.
18025 # We thus use make's @code{dir} and @code{sort} functions.
18026 # It sets DIRs to the following value (note that the directories aaa and baa
18027 # are not given, unless you change the arguments to wildcard).
18028 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18029 ####
18031 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18032                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18034 ####
18035 # Third method: use an external program
18036 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18037 # This is the most complete command: it sets DIRs to the following value:
18038 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18039 ####
18041 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18043 @end smallexample
18045 @node Generating the Command Line Switches
18046 @section Generating the Command Line Switches
18048 @noindent
18049 Once you have created the list of directories as explained in the
18050 previous section (@pxref{Automatically Creating a List of Directories}),
18051 you can easily generate the command line arguments to pass to gnatmake.
18053 For the sake of completeness, this example assumes that the source path
18054 is not the same as the object path, and that you have two separate lists
18055 of directories.
18057 @smallexample
18058 # see "Automatically creating a list of directories" to create
18059 # these variables
18060 SOURCE_DIRS=
18061 OBJECT_DIRS=
18063 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18064 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18066 all:
18067         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18068 @end smallexample
18070 @node Overcoming Command Line Length Limits
18071 @section Overcoming Command Line Length Limits
18073 @noindent
18074 One problem that might be encountered on big projects is that many
18075 operating systems limit the length of the command line. It is thus hard to give
18076 gnatmake the list of source and object directories.
18078 This example shows how you can set up environment variables, which will
18079 make @command{gnatmake} behave exactly as if the directories had been
18080 specified on the command line, but have a much higher length limit (or
18081 even none on most systems).
18083 It assumes that you have created a list of directories in your Makefile,
18084 using one of the methods presented in
18085 @ref{Automatically Creating a List of Directories}.
18086 For the sake of completeness, we assume that the object
18087 path (where the ALI files are found) is different from the sources patch.
18089 Note a small trick in the Makefile below: for efficiency reasons, we
18090 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18091 expanded immediately by @code{make}. This way we overcome the standard
18092 make behavior which is to expand the variables only when they are
18093 actually used.
18095 On Windows, if you are using the standard Windows command shell, you must
18096 replace colons with semicolons in the assignments to these variables.
18098 @smallexample
18099 @iftex
18100 @leftskip=0cm
18101 @font@heightrm=cmr8
18102 @heightrm
18103 @end iftex
18104 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
18105 # This is the same thing as putting the -I arguments on the command line.
18106 # (the equivalent of using -aI on the command line would be to define
18107 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
18108 # You can of course have different values for these variables.
18110 # Note also that we need to keep the previous values of these variables, since
18111 # they might have been set before running 'make' to specify where the GNAT
18112 # library is installed.
18114 # see "Automatically creating a list of directories" to create these
18115 # variables
18116 SOURCE_DIRS=
18117 OBJECT_DIRS=
18119 empty:=
18120 space:=$@{empty@} $@{empty@}
18121 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18122 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18123 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18124 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
18125 export ADA_INCLUDE_PATH
18126 export ADA_OBJECT_PATH
18128 all:
18129         gnatmake main_unit
18130 @end smallexample
18131 @end ifclear
18133 @node Memory Management Issues
18134 @chapter Memory Management Issues
18136 @noindent
18137 This chapter describes some useful memory pools provided in the GNAT library
18138 and in particular the GNAT Debug Pool facility, which can be used to detect
18139 incorrect uses of access values (including ``dangling references'').
18140 @ifclear vms
18141 It also describes the @command{gnatmem} tool, which can be used to track down
18142 ``memory leaks''.
18143 @end ifclear
18145 @menu
18146 * Some Useful Memory Pools::
18147 * The GNAT Debug Pool Facility::
18148 @ifclear vms
18149 * The gnatmem Tool::
18150 @end ifclear
18151 @end menu
18153 @node Some Useful Memory Pools
18154 @section Some Useful Memory Pools
18155 @findex Memory Pool
18156 @cindex storage, pool
18158 @noindent
18159 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18160 storage pool. Allocations use the standard system call @code{malloc} while
18161 deallocations use the standard system call @code{free}. No reclamation is
18162 performed when the pool goes out of scope. For performance reasons, the
18163 standard default Ada allocators/deallocators do not use any explicit storage
18164 pools but if they did, they could use this storage pool without any change in
18165 behavior. That is why this storage pool is used  when the user
18166 manages to make the default implicit allocator explicit as in this example:
18167 @smallexample @c ada
18168    type T1 is access Something;
18169     -- no Storage pool is defined for T2
18170    type T2 is access Something_Else;
18171    for T2'Storage_Pool use T1'Storage_Pool;
18172    -- the above is equivalent to
18173    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18174 @end smallexample
18176 @noindent
18177 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18178 pool. The allocation strategy is similar to @code{Pool_Local}'s
18179 except that the all
18180 storage allocated with this pool is reclaimed when the pool object goes out of
18181 scope. This pool provides a explicit mechanism similar to the implicit one
18182 provided by several Ada 83 compilers for allocations performed through a local
18183 access type and whose purpose was to reclaim memory when exiting the
18184 scope of a given local access. As an example, the following program does not
18185 leak memory even though it does not perform explicit deallocation:
18187 @smallexample @c ada
18188 with System.Pool_Local;
18189 procedure Pooloc1 is
18190    procedure Internal is
18191       type A is access Integer;
18192       X : System.Pool_Local.Unbounded_Reclaim_Pool;
18193       for A'Storage_Pool use X;
18194       v : A;
18195    begin
18196       for I in  1 .. 50 loop
18197          v := new Integer;
18198       end loop;
18199    end Internal;
18200 begin
18201    for I in  1 .. 100 loop
18202       Internal;
18203    end loop;
18204 end Pooloc1;
18205 @end smallexample
18207 @noindent
18208 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18209 @code{Storage_Size} is specified for an access type.
18210 The whole storage for the pool is
18211 allocated at once, usually on the stack at the point where the access type is
18212 elaborated. It is automatically reclaimed when exiting the scope where the
18213 access type is defined. This package is not intended to be used directly by the
18214 user and it is implicitly used for each such declaration:
18216 @smallexample @c ada
18217    type T1 is access Something;
18218    for T1'Storage_Size use 10_000;
18219 @end smallexample
18222 @node The GNAT Debug Pool Facility
18223 @section The GNAT Debug Pool Facility
18224 @findex Debug Pool
18225 @cindex storage, pool, memory corruption
18227 @noindent
18228 The use of unchecked deallocation and unchecked conversion can easily
18229 lead to incorrect memory references. The problems generated by such
18230 references are usually difficult to tackle because the symptoms can be
18231 very remote from the origin of the problem. In such cases, it is
18232 very helpful to detect the problem as early as possible. This is the
18233 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18235 In order to use the GNAT specific debugging pool, the user must
18236 associate a debug pool object with each of the access types that may be
18237 related to suspected memory problems. See Ada Reference Manual 13.11.
18238 @smallexample @c ada
18239 type Ptr is access Some_Type;
18240 Pool : GNAT.Debug_Pools.Debug_Pool;
18241 for Ptr'Storage_Pool use Pool;
18242 @end smallexample
18244 @noindent
18245 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18246 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18247 allow the user to redefine allocation and deallocation strategies. They
18248 also provide a checkpoint for each dereference, through the use of
18249 the primitive operation @code{Dereference} which is implicitly called at
18250 each dereference of an access value.
18252 Once an access type has been associated with a debug pool, operations on
18253 values of the type may raise four distinct exceptions,
18254 which correspond to four potential kinds of memory corruption:
18255 @itemize @bullet
18256 @item
18257 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18258 @item
18259 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18260 @item
18261 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18262 @item
18263 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18264 @end itemize
18266 @noindent
18267 For types associated with a Debug_Pool, dynamic allocation is performed using
18268 the standard GNAT allocation routine. References to all allocated chunks of
18269 memory are kept in an internal dictionary. Several deallocation strategies are
18270 provided, whereupon the user can choose to release the memory to the system,
18271 keep it allocated for further invalid access checks, or fill it with an easily
18272 recognizable pattern for debug sessions. The memory pattern is the old IBM
18273 hexadecimal convention: @code{16#DEADBEEF#}.
18275 See the documentation in the file g-debpoo.ads for more information on the
18276 various strategies.
18278 Upon each dereference, a check is made that the access value denotes a
18279 properly allocated memory location. Here is a complete example of use of
18280 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18281 @smallexample @c ada
18282 @iftex
18283 @leftskip=0cm
18284 @end iftex
18285 with Gnat.Io; use Gnat.Io;
18286 with Unchecked_Deallocation;
18287 with Unchecked_Conversion;
18288 with GNAT.Debug_Pools;
18289 with System.Storage_Elements;
18290 with Ada.Exceptions; use Ada.Exceptions;
18291 procedure Debug_Pool_Test is
18293    type T is access Integer;
18294    type U is access all T;
18296    P : GNAT.Debug_Pools.Debug_Pool;
18297    for T'Storage_Pool use P;
18299    procedure Free is new Unchecked_Deallocation (Integer, T);
18300    function UC is new Unchecked_Conversion (U, T);
18301    A, B : aliased T;
18303    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18305 begin
18306    Info (P);
18307    A := new Integer;
18308    B := new Integer;
18309    B := A;
18310    Info (P);
18311    Free (A);
18312    begin
18313       Put_Line (Integer'Image(B.all));
18314    exception
18315       when E : others => Put_Line ("raised: " & Exception_Name (E));
18316    end;
18317    begin
18318       Free (B);
18319    exception
18320       when E : others => Put_Line ("raised: " & Exception_Name (E));
18321    end;
18322    B := UC(A'Access);
18323    begin
18324       Put_Line (Integer'Image(B.all));
18325    exception
18326       when E : others => Put_Line ("raised: " & Exception_Name (E));
18327    end;
18328    begin
18329       Free (B);
18330    exception
18331       when E : others => Put_Line ("raised: " & Exception_Name (E));
18332    end;
18333    Info (P);
18334 end Debug_Pool_Test;
18335 @end smallexample
18337 @noindent
18338 The debug pool mechanism provides the following precise diagnostics on the
18339 execution of this erroneous program:
18340 @smallexample
18341 Debug Pool info:
18342   Total allocated bytes :  0
18343   Total deallocated bytes :  0
18344   Current Water Mark:  0
18345   High Water Mark:  0
18347 Debug Pool info:
18348   Total allocated bytes :  8
18349   Total deallocated bytes :  0
18350   Current Water Mark:  8
18351   High Water Mark:  8
18353 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18354 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18355 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18356 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18357 Debug Pool info:
18358   Total allocated bytes :  8
18359   Total deallocated bytes :  4
18360   Current Water Mark:  4
18361   High Water Mark:  8
18362 @end smallexample
18364 @ifclear vms
18365 @node The gnatmem Tool
18366 @section The @command{gnatmem} Tool
18367 @findex gnatmem
18369 @noindent
18370 The @code{gnatmem} utility monitors dynamic allocation and
18371 deallocation activity in a program, and displays information about
18372 incorrect deallocations and possible sources of memory leaks.
18373 It provides three type of information:
18374 @itemize @bullet
18375 @item
18376 General information concerning memory management, such as the total
18377 number of allocations and deallocations, the amount of allocated
18378 memory and the high water mark, i.e. the largest amount of allocated
18379 memory in the course of program execution.
18381 @item
18382 Backtraces for all incorrect deallocations, that is to say deallocations
18383 which do not correspond to a valid allocation.
18385 @item
18386 Information on each allocation that is potentially the origin of a memory
18387 leak.
18388 @end itemize
18390 @menu
18391 * Running gnatmem::
18392 * Switches for gnatmem::
18393 * Example of gnatmem Usage::
18394 @end menu
18396 @node Running gnatmem
18397 @subsection Running @code{gnatmem}
18399 @noindent
18400 @code{gnatmem} makes use of the output created by the special version of
18401 allocation and deallocation routines that record call information. This
18402 allows to obtain accurate dynamic memory usage history at a minimal cost to
18403 the execution speed. Note however, that @code{gnatmem} is not supported on
18404 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
18405 32-bit Solaris (sparc and x86) and Windows NT/2000/XP (x86).
18407 @noindent
18408 The @code{gnatmem} command has the form
18410 @smallexample
18411    $ gnatmem [switches] user_program
18412 @end smallexample
18414 @noindent
18415 The program must have been linked with the instrumented version of the
18416 allocation and deallocation routines. This is done by linking with the
18417 @file{libgmem.a} library. For correct symbolic backtrace information,
18418 the user program should be compiled with debugging options
18419 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18421 @smallexample
18422 $ gnatmake -g my_program -largs -lgmem
18423 @end smallexample
18425 @noindent
18426 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18427 This file contains information about all allocations and deallocations
18428 performed by the program. It is produced by the instrumented allocations and
18429 deallocations routines and will be used by @code{gnatmem}.
18431 In order to produce symbolic backtrace information for allocations and
18432 deallocations performed by the GNAT run-time library, you need to use a
18433 version of that library that has been compiled with the @option{-g} switch
18434 (see @ref{Rebuilding the GNAT Run-Time Library}).
18436 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18437 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18438 @code{-i} switch, gnatmem will assume that this file can be found in the
18439 current directory. For example, after you have executed @file{my_program},
18440 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18442 @smallexample
18443 $ gnatmem my_program
18444 @end smallexample
18446 @noindent
18447 This will produce the output with the following format:
18449 *************** debut cc
18450 @smallexample
18451 $ gnatmem my_program
18453 Global information
18454 ------------------
18455    Total number of allocations        :  45
18456    Total number of deallocations      :   6
18457    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18458    High Water Mark                    :  11.40 Kilobytes
18463 Allocation Root # 2
18464 -------------------
18465  Number of non freed allocations    :  11
18466  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18467  High Water Mark                    :   1.27 Kilobytes
18468  Backtrace                          :
18469    my_program.adb:23 my_program.alloc
18473 @end smallexample
18475 The first block of output gives general information. In this case, the
18476 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18477 Unchecked_Deallocation routine occurred.
18479 @noindent
18480 Subsequent paragraphs display  information on all allocation roots.
18481 An allocation root is a specific point in the execution of the program
18482 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18483 construct. This root is represented by an execution backtrace (or subprogram
18484 call stack). By default the backtrace depth for allocations roots is 1, so
18485 that a root corresponds exactly to a source location. The backtrace can
18486 be made deeper, to make the root more specific.
18488 @node Switches for gnatmem
18489 @subsection Switches for @code{gnatmem}
18491 @noindent
18492 @code{gnatmem} recognizes the following switches:
18494 @table @option
18496 @item -q
18497 @cindex @option{-q} (@code{gnatmem})
18498 Quiet. Gives the minimum output needed to identify the origin of the
18499 memory leaks. Omits statistical information.
18501 @item @var{N}
18502 @cindex @var{N} (@code{gnatmem})
18503 N is an integer literal (usually between 1 and 10) which controls the
18504 depth of the backtraces defining allocation root. The default value for
18505 N is 1. The deeper the backtrace, the more precise the localization of
18506 the root. Note that the total number of roots can depend on this
18507 parameter. This parameter must be specified @emph{before} the name of the
18508 executable to be analyzed, to avoid ambiguity.
18510 @item -b n
18511 @cindex @option{-b} (@code{gnatmem})
18512 This switch has the same effect as just depth parameter.
18514 @item -i @var{file}
18515 @cindex @option{-i} (@code{gnatmem})
18516 Do the @code{gnatmem} processing starting from @file{file}, rather than
18517 @file{gmem.out} in the current directory.
18519 @item -m n
18520 @cindex @option{-m} (@code{gnatmem})
18521 This switch causes @code{gnatmem} to mask the allocation roots that have less
18522 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18523 examine even the roots that didn't result in leaks.
18525 @item -s order
18526 @cindex @option{-s} (@code{gnatmem})
18527 This switch causes @code{gnatmem} to sort the allocation roots according to the
18528 specified order of sort criteria, each identified by a single letter. The
18529 currently supported criteria are @code{n, h, w} standing respectively for
18530 number of unfreed allocations, high watermark, and final watermark
18531 corresponding to a specific root. The default order is @code{nwh}.
18533 @end table
18535 @node Example of gnatmem Usage
18536 @subsection Example of @code{gnatmem} Usage
18538 @noindent
18539 The following example shows the use of @code{gnatmem}
18540 on a simple memory-leaking program.
18541 Suppose that we have the following Ada program:
18543 @smallexample @c ada
18544 @group
18545 @cartouche
18546 with Unchecked_Deallocation;
18547 procedure Test_Gm is
18549    type T is array (1..1000) of Integer;
18550    type Ptr is access T;
18551    procedure Free is new Unchecked_Deallocation (T, Ptr);
18552    A : Ptr;
18554    procedure My_Alloc is
18555    begin
18556       A := new T;
18557    end My_Alloc;
18559    procedure My_DeAlloc is
18560       B : Ptr := A;
18561    begin
18562       Free (B);
18563    end My_DeAlloc;
18565 begin
18566    My_Alloc;
18567    for I in 1 .. 5 loop
18568       for J in I .. 5 loop
18569          My_Alloc;
18570       end loop;
18571       My_Dealloc;
18572    end loop;
18573 end;
18574 @end cartouche
18575 @end group
18576 @end smallexample
18578 @noindent
18579 The program needs to be compiled with debugging option and linked with
18580 @code{gmem} library:
18582 @smallexample
18583 $ gnatmake -g test_gm -largs -lgmem
18584 @end smallexample
18586 @noindent
18587 Then we execute the program as usual:
18589 @smallexample
18590 $ test_gm
18591 @end smallexample
18593 @noindent
18594 Then @code{gnatmem} is invoked simply with
18595 @smallexample
18596 $ gnatmem test_gm
18597 @end smallexample
18599 @noindent
18600 which produces the following output (result may vary on different platforms):
18602 @smallexample
18603 Global information
18604 ------------------
18605    Total number of allocations        :  18
18606    Total number of deallocations      :   5
18607    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18608    High Water Mark                    :  56.90 Kilobytes
18610 Allocation Root # 1
18611 -------------------
18612  Number of non freed allocations    :  11
18613  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18614  High Water Mark                    :  46.88 Kilobytes
18615  Backtrace                          :
18616    test_gm.adb:11 test_gm.my_alloc
18618 Allocation Root # 2
18619 -------------------
18620  Number of non freed allocations    :   1
18621  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18622  High Water Mark                    :  10.02 Kilobytes
18623  Backtrace                          :
18624    s-secsta.adb:81 system.secondary_stack.ss_init
18626 Allocation Root # 3
18627 -------------------
18628  Number of non freed allocations    :   1
18629  Final Water Mark (non freed mem)   :  12 Bytes
18630  High Water Mark                    :  12 Bytes
18631  Backtrace                          :
18632    s-secsta.adb:181 system.secondary_stack.ss_init
18633 @end smallexample
18635 @noindent
18636 Note that the GNAT run time contains itself a certain number of
18637 allocations that have no  corresponding deallocation,
18638 as shown here for root #2 and root
18639 #3. This is a normal behavior when the number of non freed allocations
18640 is one, it allocates dynamic data structures that the run time needs for
18641 the complete lifetime of the program. Note also that there is only one
18642 allocation root in the user program with a single line back trace:
18643 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18644 program shows that 'My_Alloc' is called at 2 different points in the
18645 source (line 21 and line 24). If those two allocation roots need to be
18646 distinguished, the backtrace depth parameter can be used:
18648 @smallexample
18649 $ gnatmem 3 test_gm
18650 @end smallexample
18652 @noindent
18653 which will give the following output:
18655 @smallexample
18656 Global information
18657 ------------------
18658    Total number of allocations        :  18
18659    Total number of deallocations      :   5
18660    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18661    High Water Mark                    :  56.90 Kilobytes
18663 Allocation Root # 1
18664 -------------------
18665  Number of non freed allocations    :  10
18666  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18667  High Water Mark                    :  42.97 Kilobytes
18668  Backtrace                          :
18669    test_gm.adb:11 test_gm.my_alloc
18670    test_gm.adb:24 test_gm
18671    b_test_gm.c:52 main
18673 Allocation Root # 2
18674 -------------------
18675  Number of non freed allocations    :   1
18676  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18677  High Water Mark                    :  10.02 Kilobytes
18678  Backtrace                          :
18679    s-secsta.adb:81  system.secondary_stack.ss_init
18680    s-secsta.adb:283 <system__secondary_stack___elabb>
18681    b_test_gm.c:33   adainit
18683 Allocation Root # 3
18684 -------------------
18685  Number of non freed allocations    :   1
18686  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18687  High Water Mark                    :   3.91 Kilobytes
18688  Backtrace                          :
18689    test_gm.adb:11 test_gm.my_alloc
18690    test_gm.adb:21 test_gm
18691    b_test_gm.c:52 main
18693 Allocation Root # 4
18694 -------------------
18695  Number of non freed allocations    :   1
18696  Final Water Mark (non freed mem)   :  12 Bytes
18697  High Water Mark                    :  12 Bytes
18698  Backtrace                          :
18699    s-secsta.adb:181 system.secondary_stack.ss_init
18700    s-secsta.adb:283 <system__secondary_stack___elabb>
18701    b_test_gm.c:33   adainit
18702 @end smallexample
18704 @noindent
18705 The allocation root #1 of the first example has been split in 2 roots #1
18706 and #3 thanks to the more precise associated backtrace.
18708 @end ifclear
18710 @node Stack Related Facilities
18711 @chapter Stack Related Facilities
18713 @noindent
18714 This chapter describes some useful tools associated with stack
18715 checking and analysis. In
18716 particular, it deals with dynamic and static stack usage measurements.
18718 @menu
18719 * Stack Overflow Checking::
18720 * Static Stack Usage Analysis::
18721 * Dynamic Stack Usage Analysis::
18722 @end menu
18724 @node Stack Overflow Checking
18725 @section Stack Overflow Checking
18726 @cindex Stack Overflow Checking
18727 @cindex -fstack-check
18729 @noindent
18730 For most operating systems, @command{gcc} does not perform stack overflow
18731 checking by default. This means that if the main environment task or
18732 some other task exceeds the available stack space, then unpredictable
18733 behavior will occur. Most native systems offer some level of protection by
18734 adding a guard page at the end of each task stack. This mechanism is usually
18735 not enough for dealing properly with stack overflow situations because
18736 a large local variable could ``jump'' above the guard page.
18737 Furthermore, when the
18738 guard page is hit, there may not be any space left on the stack for executing
18739 the exception propagation code. Enabling stack checking avoids
18740 such situations.
18742 To activate stack checking, compile all units with the gcc option
18743 @option{-fstack-check}. For example:
18745 @smallexample
18746 gcc -c -fstack-check package1.adb
18747 @end smallexample
18749 @noindent
18750 Units compiled with this option will generate extra instructions to check
18751 that any use of the stack (for procedure calls or for declaring local
18752 variables in declare blocks) does not exceed the available stack space.
18753 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18755 For declared tasks, the stack size is controlled by the size
18756 given in an applicable @code{Storage_Size} pragma or by the value specified
18757 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18758 the default size as defined in the GNAT runtime otherwise.
18760 For the environment task, the stack size depends on
18761 system defaults and is unknown to the compiler. Stack checking
18762 may still work correctly if a fixed
18763 size stack is allocated, but this cannot be guaranteed.
18764 To ensure that a clean exception is signalled for stack
18765 overflow, set the environment variable
18766 @code{GNAT_STACK_LIMIT} to indicate the maximum
18767 stack area that can be used, as in:
18768 @cindex GNAT_STACK_LIMIT
18770 @smallexample
18771 SET GNAT_STACK_LIMIT 1600
18772 @end smallexample
18774 @noindent
18775 The limit is given in kilobytes, so the above declaration would
18776 set the stack limit of the environment task to 1.6 megabytes.
18777 Note that the only purpose of this usage is to limit the amount
18778 of stack used by the environment task. If it is necessary to
18779 increase the amount of stack for the environment task, then this
18780 is an operating systems issue, and must be addressed with the
18781 appropriate operating systems commands.
18783 @node Static Stack Usage Analysis
18784 @section Static Stack Usage Analysis
18785 @cindex Static Stack Usage Analysis
18786 @cindex -fstack-usage
18788 @noindent
18789 A unit compiled with @option{-fstack-usage} will generate an extra file
18790 that specifies
18791 the maximum amount of stack used, on a per-function basis.
18792 The file has the same
18793 basename as the target object file with a @file{.su} extension.
18794 Each line of this file is made up of three fields:
18796 @itemize
18797 @item
18798 The name of the function.
18799 @item
18800 A number of bytes.
18801 @item
18802 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
18803 @end itemize
18805 The second field corresponds to the size of the known part of the function
18806 frame.
18808 The qualifier @code{static} means that the function frame size
18809 is purely static.
18810 It usually means that all local variables have a static size.
18811 In this case, the second field is a reliable measure of the function stack
18812 utilization.
18814 The qualifier @code{dynamic} means that the function frame size is not static.
18815 It happens mainly when some local variables have a dynamic size. When this
18816 qualifier appears alone, the second field is not a reliable measure
18817 of the function stack analysis. When it is qualified with  @code{bounded}, it
18818 means that the second field is a reliable maximum of the function stack
18819 utilization.
18821 @node Dynamic Stack Usage Analysis
18822 @section Dynamic Stack Usage Analysis
18824 @noindent
18825 It is possible to measure the maximum amount of stack used by a task, by
18826 adding a switch to @command{gnatbind}, as:
18828 @smallexample
18829 $ gnatbind -u0 file
18830 @end smallexample
18832 @noindent
18833 With this option, at each task termination, its stack usage is  output on
18834 @file{stderr}.
18835 It is not always convenient to output the stack usage when the program
18836 is still running. Hence, it is possible to delay this output until program
18837 termination. for a given number of tasks specified as the argument of the
18838 @code{-u} option. For instance:
18840 @smallexample
18841 $ gnatbind -u100 file
18842 @end smallexample
18844 @noindent
18845 will buffer the stack usage information of the first 100 tasks to terminate and
18846 output this info at program termination. Results are displayed in four
18847 columns:
18849 @noindent
18850 Index | Task Name | Stack Size | Actual Use
18852 @noindent
18853 where:
18855 @table @emph
18856 @item Index
18857 is a number associated with each task.
18859 @item Task Name
18860 is the name of the task analyzed.
18862 @item Stack Size
18863 is the maximum size for the stack. In order to prevent overflow,
18864 the real stack limit  is slightly larger than the Stack Size in order to allow
18865 proper recovery.
18867 @item Actual Use
18868 is the measure done by the stack analyzer.
18870 @end table
18872 @noindent
18873 The environment task stack, e.g. the stack that contains the main unit, is
18874 only processed when the environment variable GNAT_STACK_LIMIT is set.
18876 @c *********************************
18877 @node Verifying properties using gnatcheck
18878 @chapter Verifying properties using @command{gnatcheck}
18879 @findex gnatcheck
18881 @noindent
18882 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18883 of Ada source files according to a given set of semantic rules.
18885 In order to check compliance with a given rule, @command{gnatcheck} has to
18886 semantically analyze the Ada sources.
18887 Therefore, checks can only be performed on
18888 legal Ada units. Moreover, when a unit depends semantically upon units located
18889 outside the current directory, the source search path has to be provided when
18890 calling @command{gnatcheck}, either through a specified project file or
18891 through @command{gnatcheck} switches as described below.
18893 The project support for @command{gnatcheck} is provided by the @command{gnat}
18894 driver.
18896 Several rules are already implemented in @command{gnatcheck}. The list of such
18897 rules can be obtained with option @option{^-h^/HELP^} as described in the next
18898 section. A user can add new rules by modifying the @command{gnatcheck} code and
18899 rebuilding the tool. For adding a simple rule making some local checks, a small
18900 amount of straightforward ASIS-based programming is usually needed.
18902 @noindent
18903 @command{gnatcheck} has the command-line interface of the form
18905 @smallexample
18906 $ gnatcheck [@i{switches}]  @{@i{filename}@}  [@i{^-files^/FILES^=@{arg_list_filename@}}]
18907       [@i{-cargs gcc_switches}] [@i{-rules rule_options}]
18908 @end smallexample
18911 @noindent
18912 where
18913 @itemize @bullet
18914 @item
18915 @i{switches} specify the general tool options
18917 @item
18918 Each @i{filename} is the name (including the extension) of a source
18919 file to process. ``Wildcards'' are allowed, and
18920 the file name may contain path information.
18922 @item
18923 Each @i{arg_list_filename} is the name (including the extension) of a text
18924 file containing the names of the source files to process, separated by spaces
18925 or line breaks.
18927 @item
18928 @i{-cargs gcc_switches} is a list of switches for
18929 @command{gcc}. They will be passed on to all compiler invocations made by
18930 @command{gnatcheck} to generate the ASIS trees. Here you can provide
18931 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
18932 and use the @option{-gnatec} switch to set the configuration file.
18934 @item
18935 @i{-rules rule_options} is a list of options for controlling a set of
18936 rules to be checked by @command{gnatcheck} (@pxref{gnatcheck Rule Options})
18937 @end itemize
18939 @noindent
18940 Either a @i{filename} or an @i{arg_list_filename} needs to be supplied.
18942 @menu
18943 * Format of the Report File::
18944 * General gnatcheck Switches::
18945 * gnatcheck Rule Options::
18946 * Add the Results of Compiler Checks to gnatcheck Output::
18947 @end menu
18949 @node Format of the Report File
18950 @section Format of the Report File
18952 @noindent
18953 The @command{gnatcheck} tool outputs on @file{stdout} all messages concerning
18954 rule violations.
18955 It also creates, in the current
18956 directory, a text file named @file{^gnatcheck.out^GNATCHECK.OUT^} that
18957 contains the complete report of the last gnatcheck run. This report contains:
18958 @itemize @bullet
18959 @item a list of the Ada source files being checked,
18960 @item a list of enabled and disabled rules,
18961 @item a list of the diagnostic messages, ordered in three different ways
18962 and collected in three separate
18963 sections. Section 1 contains the raw list of diagnostic messages. It
18964 corresponds to the output going to @file{stdout}. Section 2 contains
18965 messages ordered by rules.
18966 Section 3 contains messages ordered by source files.
18967 @end itemize
18970 @node General gnatcheck Switches
18971 @section General @command{gnatcheck} Switches
18973 @noindent
18974 The following switches control the general @command{gnatcheck} behavior
18976 @table @option
18977 @cindex @option{^-a^/ALL^} (@command{gnatcheck})
18978 @item ^-a^/ALL^
18979 Process all units including those with read-only ALI files such as
18980 those from GNAT Run-Time library.
18982 @cindex @option{^-h^/HELP^} (@command{gnatcheck})
18983 @item ^-h^/HELP^
18984 Print out the list of the currently implemented rules. For more details see
18985 the README file in the @command{gnatcheck} sources.
18987 @cindex @option{^-l^/LOCS^} (@command{gnatcheck})
18988 @item ^-l^/LOCS^
18989 Use full source locations references in the report file. For a construct from
18990 a generic instantiation a full source location is a chain from the location
18991 of this construct in the generic unit to the place where this unit is
18992 instantiated.
18994 @cindex @option{^-q^/QUIET^} (@command{gnatcheck})
18995 @item ^-q^/QUIET^
18996 Quiet mode. All the diagnoses about rule violations are placed in the
18997 @command{gnatcheck} report file only, without duplicating in @file{stdout}.
18999 @cindex @option{^-s^/SHORT^} (@command{gnatcheck})
19000 @item ^-s^/SHORT^
19001 Short format of the report file (no version information, no list of applied
19002 rules, no list of checked sources is included)
19004 @cindex @option{^-s1^/COMPILER_STYLE^} (@command{gnatcheck})
19005 @item ^-s1^/COMPILER_STYLE^
19006 Include the compiler-style section in the report file
19008 @cindex @option{^-s2^/BY_RULES^} (@command{gnatcheck})
19009 @item ^-s2^/BY_RULES^
19010 Include the section containing diagnoses ordered by rules in the report file
19012 @cindex @option{^-s3^/BY_FILES_BY_RULES^} (@command{gnatcheck})
19013 @item ^-s3^/BY_FILES_BY_RULES^
19014 Include the section containing diagnoses ordered by files and then by rules
19015 in the report file
19017 @cindex @option{^-v^/VERBOSE^} (@command{gnatcheck})
19018 @item ^-v^/VERBOSE^
19019 Verbose mode; @command{gnatcheck} generates version information and then
19020 a trace of sources being processed.
19022 @end table
19024 @noindent
19025 Note, that if either of the options @option{^-s1^/COMPILER_STYLE^},
19026 @option{^-s2^/BY_RULES^} or
19027 @option{^-s3^/BY_FILES_BY_RULES^} is specified,
19028 then the  @command{gnatcheck} report file will contain only sections
19029 explicitly stated by these options.
19031 @node gnatcheck Rule Options
19032 @section @command{gnatcheck} Rule Options
19034 @noindent
19035 The following options control the processing performed by
19036 @command{gnatcheck}.
19038 @table @option
19039 @cindex @option{+ALL} (@command{gnatcheck})
19040 @item +ALL
19041 Turn all the rule checks ON
19043 @cindex @option{-ALL} (@command{gnatcheck})
19044 @item -ALL
19045 Turn all the rule checks OFF
19047 @cindex @option{+R} (@command{gnatcheck})
19048 @item +R@i{rule_id[:param]}
19049 Turn on the check for a specified rule with the specified parameter, if any.
19050 @i{rule_id} should be the identifier of one of the currently implemented rules
19051 (use @option{^-h^/HELP^} for the list of implemented rules). Rule identifiers
19052 are not case-sensitive. The @i{:param} item should
19053 be a string representing a valid parameter(s) for the specified rule.
19054 If it contains any space characters then this string must be enclosed in
19055 quotation marks.
19057 @cindex @option{-R} (@command{gnatcheck})
19058 @item -R@i{rule_id}
19059 Turn off the check for a specified rule
19061 @end table
19063 @node Add the Results of Compiler Checks to gnatcheck Output
19064 @section Add the Results of Compiler Checks to @command{gnatcheck} Output
19066 @noindent
19067 The @command{gnatcheck} tool can include in the generated diagnostic messages
19068 and in
19069 the report file the results of the checks performed by the compiler. Though
19070 disabled by default, this effect may be obtained by using @option{+R} with
19071 the following rule identifiers and parameters:
19073 @table @option
19074 @item Restrictions
19075 To record restrictions violations (that are performed by the compiler if the
19076 pragma @code{Restrictions} or @code{Restriction_Warnings} are given),
19077 use the rule named
19078 @i{Restrictions} with the same parameters as pragma
19079 @code{Restrictions} or @code{Restriction_Warnings}
19081 @item Style_Checks
19082 To record compiler style checks, use the rule named
19083 @i{Style_Checks}. A parameter of this rule can be either @i{All_Checks}, that
19084 turns ON all the style checks, or a string that has exactly the same structure
19085 and semantics as @code{string_LITERAL} parameter of GNAT pragma
19086 @code{Style_Checks}.
19088 @item Warnings
19089 To record compiler warnings (@pxref{Warning Message Control}), use the rule
19090 named @i{Warnings} with a parameter that is a valid
19091 @code{static_string_expression} argument of GNAT pragma @code{Warnings}.
19093 @end table
19095 @c *********************************
19096 @node Creating Sample Bodies Using gnatstub
19097 @chapter Creating Sample Bodies Using @command{gnatstub}
19098 @findex gnatstub
19100 @noindent
19101 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
19102 for library unit declarations.
19104 To create a body stub, @command{gnatstub} has to compile the library
19105 unit declaration. Therefore, bodies can be created only for legal
19106 library units. Moreover, if a library unit depends semantically upon
19107 units located outside the current directory, you have to provide
19108 the source search path when calling @command{gnatstub}, see the description
19109 of @command{gnatstub} switches below.
19111 @menu
19112 * Running gnatstub::
19113 * Switches for gnatstub::
19114 @end menu
19116 @node Running gnatstub
19117 @section Running @command{gnatstub}
19119 @noindent
19120 @command{gnatstub} has the command-line interface of the form
19122 @smallexample
19123 $ gnatstub [switches] filename [directory]
19124 @end smallexample
19126 @noindent
19127 where
19128 @table @emph
19129 @item filename
19130 is the name of the source file that contains a library unit declaration
19131 for which a body must be created. The file name may contain the path
19132 information.
19133 The file name does not have to follow the GNAT file name conventions. If the
19134 name
19135 does not follow GNAT file naming conventions, the name of the body file must
19136 be provided
19137 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19138 If the file name follows the GNAT file naming
19139 conventions and the name of the body file is not provided,
19140 @command{gnatstub}
19141 creates the name
19142 of the body file from the argument file name by replacing the @file{.ads}
19143 suffix
19144 with the @file{.adb} suffix.
19146 @item directory
19147 indicates the directory in which the body stub is to be placed (the default
19148 is the
19149 current directory)
19151 @item switches
19152 is an optional sequence of switches as described in the next section
19153 @end table
19155 @node Switches for gnatstub
19156 @section Switches for @command{gnatstub}
19158 @table @option
19159 @c !sort!
19161 @item ^-f^/FULL^
19162 @cindex @option{^-f^/FULL^} (@command{gnatstub})
19163 If the destination directory already contains a file with the name of the
19164 body file
19165 for the argument spec file, replace it with the generated body stub.
19167 @item ^-hs^/HEADER=SPEC^
19168 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19169 Put the comment header (i.e., all the comments preceding the
19170 compilation unit) from the source of the library unit declaration
19171 into the body stub.
19173 @item ^-hg^/HEADER=GENERAL^
19174 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19175 Put a sample comment header into the body stub.
19177 @ifclear vms
19178 @item -IDIR
19179 @cindex @option{-IDIR} (@command{gnatstub})
19180 @itemx -I-
19181 @cindex @option{-I-} (@command{gnatstub})
19182 @end ifclear
19183 @ifset vms
19184 @item /NOCURRENT_DIRECTORY
19185 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19186 @end ifset
19187 ^These switches have ^This switch has^ the same meaning as in calls to
19188 @command{gcc}.
19189 ^They define ^It defines ^ the source search path in the call to
19190 @command{gcc} issued
19191 by @command{gnatstub} to compile an argument source file.
19193 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19194 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19195 This switch has the same meaning as in calls to @command{gcc}.
19196 It defines the additional configuration file to be passed to the call to
19197 @command{gcc} issued
19198 by @command{gnatstub} to compile an argument source file.
19200 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19201 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19202 (@var{n} is a non-negative integer). Set the maximum line length in the
19203 body stub to @var{n}; the default is 79. The maximum value that can be
19204 specified is 32767. Note that in the special case of configuration
19205 pragma files, the maximum is always 32767 regardless of whether or
19206 not this switch appears.
19208 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
19209 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19210 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19211 the generated body sample to @var{n}.
19212 The default indentation is 3.
19214 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19215 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19216 Order local bodies alphabetically. (By default local bodies are ordered
19217 in the same way as the corresponding local specs in the argument spec file.)
19219 @item ^-i^/INDENTATION=^@var{n}
19220 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19221 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19223 @item ^-k^/TREE_FILE=SAVE^
19224 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19225 Do not remove the tree file (i.e., the snapshot of the compiler internal
19226 structures used by @command{gnatstub}) after creating the body stub.
19228 @item ^-l^/LINE_LENGTH=^@var{n}
19229 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19230 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19232 @item ^-o^/BODY=^@var{body-name}
19233 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19234 Body file name.  This should be set if the argument file name does not
19235 follow
19236 the GNAT file naming
19237 conventions. If this switch is omitted the default name for the body will be
19238 obtained
19239 from the argument file name according to the GNAT file naming conventions.
19241 @item ^-q^/QUIET^
19242 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19243 Quiet mode: do not generate a confirmation when a body is
19244 successfully created, and do not generate a message when a body is not
19245 required for an
19246 argument unit.
19248 @item ^-r^/TREE_FILE=REUSE^
19249 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19250 Reuse the tree file (if it exists) instead of creating it.  Instead of
19251 creating the tree file for the library unit declaration, @command{gnatstub}
19252 tries to find it in the current directory and use it for creating
19253 a body. If the tree file is not found, no body is created. This option
19254 also implies @option{^-k^/SAVE^}, whether or not
19255 the latter is set explicitly.
19257 @item ^-t^/TREE_FILE=OVERWRITE^
19258 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19259 Overwrite the existing tree file.  If the current directory already
19260 contains the file which, according to the GNAT file naming rules should
19261 be considered as a tree file for the argument source file,
19262 @command{gnatstub}
19263 will refuse to create the tree file needed to create a sample body
19264 unless this option is set.
19266 @item ^-v^/VERBOSE^
19267 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19268 Verbose mode: generate version information.
19270 @end table
19272 @node Other Utility Programs
19273 @chapter Other Utility Programs
19275 @noindent
19276 This chapter discusses some other utility programs available in the Ada
19277 environment.
19279 @menu
19280 * Using Other Utility Programs with GNAT::
19281 * The External Symbol Naming Scheme of GNAT::
19282 @ifclear vms
19283 * Ada Mode for Glide::
19284 @end ifclear
19285 * Converting Ada Files to html with gnathtml::
19286 * Installing gnathtml::
19287 @ifset vms
19288 * LSE::
19289 * Profiling::
19290 @end ifset
19291 @end menu
19293 @node Using Other Utility Programs with GNAT
19294 @section Using Other Utility Programs with GNAT
19296 @noindent
19297 The object files generated by GNAT are in standard system format and in
19298 particular the debugging information uses this format. This means
19299 programs generated by GNAT can be used with existing utilities that
19300 depend on these formats.
19302 @ifclear vms
19303 In general, any utility program that works with C will also often work with
19304 Ada programs generated by GNAT. This includes software utilities such as
19305 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
19306 as Purify.
19307 @end ifclear
19309 @node The External Symbol Naming Scheme of GNAT
19310 @section The External Symbol Naming Scheme of GNAT
19312 @noindent
19313 In order to interpret the output from GNAT, when using tools that are
19314 originally intended for use with other languages, it is useful to
19315 understand the conventions used to generate link names from the Ada
19316 entity names.
19318 All link names are in all lowercase letters. With the exception of library
19319 procedure names, the mechanism used is simply to use the full expanded
19320 Ada name with dots replaced by double underscores. For example, suppose
19321 we have the following package spec:
19323 @smallexample @c ada
19324 @group
19325 @cartouche
19326 package QRS is
19327    MN : Integer;
19328 end QRS;
19329 @end cartouche
19330 @end group
19331 @end smallexample
19333 @noindent
19334 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
19335 the corresponding link name is @code{qrs__mn}.
19336 @findex Export
19337 Of course if a @code{pragma Export} is used this may be overridden:
19339 @smallexample @c ada
19340 @group
19341 @cartouche
19342 package Exports is
19343    Var1 : Integer;
19344    pragma Export (Var1, C, External_Name => "var1_name");
19345    Var2 : Integer;
19346    pragma Export (Var2, C, Link_Name => "var2_link_name");
19347 end Exports;
19348 @end cartouche
19349 @end group
19350 @end smallexample
19352 @noindent
19353 In this case, the link name for @var{Var1} is whatever link name the
19354 C compiler would assign for the C function @var{var1_name}. This typically
19355 would be either @var{var1_name} or @var{_var1_name}, depending on operating
19356 system conventions, but other possibilities exist. The link name for
19357 @var{Var2} is @var{var2_link_name}, and this is not operating system
19358 dependent.
19360 @findex _main
19361 One exception occurs for library level procedures. A potential ambiguity
19362 arises between the required name @code{_main} for the C main program,
19363 and the name we would otherwise assign to an Ada library level procedure
19364 called @code{Main} (which might well not be the main program).
19366 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
19367 names. So if we have a library level procedure such as
19369 @smallexample @c ada
19370 @group
19371 @cartouche
19372 procedure Hello (S : String);
19373 @end cartouche
19374 @end group
19375 @end smallexample
19377 @noindent
19378 the external name of this procedure will be @var{_ada_hello}.
19380 @ifclear vms
19381 @node Ada Mode for Glide
19382 @section Ada Mode for @code{Glide}
19383 @cindex Ada mode (for Glide)
19385 @noindent
19386 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
19387 user to understand and navigate existing code, and facilitates writing
19388 new code. It furthermore provides some utility functions for easier
19389 integration of standard Emacs features when programming in Ada.
19391 Its general features include:
19393 @itemize @bullet
19394 @item
19395 An Integrated Development Environment with functionality such as the
19396 following
19398 @itemize @bullet
19399 @item
19400 ``Project files'' for configuration-specific aspects
19401 (e.g. directories and compilation options)
19403 @item
19404 Compiling and stepping through error messages.
19406 @item
19407 Running and debugging an applications within Glide.
19408 @end itemize
19410 @item
19411 Pull-down menus
19413 @item
19414 User configurability
19415 @end itemize
19417 Some of the specific Ada mode features are:
19419 @itemize @bullet
19420 @item
19421 Functions for easy and quick stepping through Ada code
19423 @item
19424 Getting cross reference information for identifiers (e.g., finding a
19425 defining occurrence)
19427 @item
19428 Displaying an index menu of types and subprograms, allowing
19429 direct selection for browsing
19431 @item
19432 Automatic color highlighting of the various Ada entities
19433 @end itemize
19435 Glide directly supports writing Ada code, via several facilities:
19437 @itemize @bullet
19438 @item
19439 Switching between spec and body files with possible
19440 autogeneration of body files
19442 @item
19443 Automatic formating of subprogram parameter lists
19445 @item
19446 Automatic indentation according to Ada syntax
19448 @item
19449 Automatic completion of identifiers
19451 @item
19452 Automatic (and configurable) casing of identifiers, keywords, and attributes
19454 @item
19455 Insertion of syntactic templates
19457 @item
19458 Block commenting / uncommenting
19459 @end itemize
19461 @noindent
19462 For more information, please refer to the online documentation
19463 available in the @code{Glide} @result{} @code{Help} menu.
19464 @end ifclear
19466 @node Converting Ada Files to html with gnathtml
19467 @section Converting Ada Files to HTML with @code{gnathtml}
19469 @noindent
19470 This @code{Perl} script allows Ada source files to be browsed using
19471 standard Web browsers. For installation procedure, see the section
19472 @xref{Installing gnathtml}.
19474 Ada reserved keywords are highlighted in a bold font and Ada comments in
19475 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
19476 switch to suppress the generation of cross-referencing information, user
19477 defined variables and types will appear in a different color; you will
19478 be able to click on any identifier and go to its declaration.
19480 The command line is as follow:
19481 @smallexample
19482 $ perl gnathtml.pl [^switches^options^] ada-files
19483 @end smallexample
19485 @noindent
19486 You can pass it as many Ada files as you want. @code{gnathtml} will generate
19487 an html file for every ada file, and a global file called @file{index.htm}.
19488 This file is an index of every identifier defined in the files.
19490 The available ^switches^options^ are the following ones :
19492 @table @option
19493 @item -83
19494 @cindex @option{-83} (@code{gnathtml})
19495 Only the subset on the Ada 83 keywords will be highlighted, not the full
19496 Ada 95 keywords set.
19498 @item -cc @var{color}
19499 @cindex @option{-cc} (@code{gnathtml})
19500 This option allows you to change the color used for comments. The default
19501 value is green. The color argument can be any name accepted by html.
19503 @item -d
19504 @cindex @option{-d} (@code{gnathtml})
19505 If the Ada files depend on some other files (for instance through
19506 @code{with} clauses, the latter files will also be converted to html.
19507 Only the files in the user project will be converted to html, not the files
19508 in the run-time library itself.
19510 @item -D
19511 @cindex @option{-D} (@code{gnathtml})
19512 This command is the same as @option{-d} above, but @command{gnathtml} will
19513 also look for files in the run-time library, and generate html files for them.
19515 @item -ext @var{extension}
19516 @cindex @option{-ext} (@code{gnathtml})
19517 This option allows you to change the extension of the generated HTML files.
19518 If you do not specify an extension, it will default to @file{htm}.
19520 @item -f
19521 @cindex @option{-f} (@code{gnathtml})
19522 By default, gnathtml will generate html links only for global entities
19523 ('with'ed units, global variables and types,...). If you specify
19524 @option{-f} on the command line, then links will be generated for local
19525 entities too.
19527 @item -l @var{number}
19528 @cindex @option{-l} (@code{gnathtml})
19529 If this ^switch^option^ is provided and @var{number} is not 0, then
19530 @code{gnathtml} will number the html files every @var{number} line.
19532 @item -I @var{dir}
19533 @cindex @option{-I} (@code{gnathtml})
19534 Specify a directory to search for library files (@file{.ALI} files) and
19535 source files. You can provide several -I switches on the command line,
19536 and the directories will be parsed in the order of the command line.
19538 @item -o @var{dir}
19539 @cindex @option{-o} (@code{gnathtml})
19540 Specify the output directory for html files. By default, gnathtml will
19541 saved the generated html files in a subdirectory named @file{html/}.
19543 @item -p @var{file}
19544 @cindex @option{-p} (@code{gnathtml})
19545 If you are using Emacs and the most recent Emacs Ada mode, which provides
19546 a full Integrated Development Environment for compiling, checking,
19547 running and debugging applications, you may use @file{.gpr} files
19548 to give the directories where Emacs can find sources and object files.
19550 Using this ^switch^option^, you can tell gnathtml to use these files.
19551 This allows you to get an html version of your application, even if it
19552 is spread over multiple directories.
19554 @item -sc @var{color}
19555 @cindex @option{-sc} (@code{gnathtml})
19556 This ^switch^option^ allows you to change the color used for symbol
19557 definitions.
19558 The default value is red. The color argument can be any name accepted by html.
19560 @item -t @var{file}
19561 @cindex @option{-t} (@code{gnathtml})
19562 This ^switch^option^ provides the name of a file. This file contains a list of
19563 file names to be converted, and the effect is exactly as though they had
19564 appeared explicitly on the command line. This
19565 is the recommended way to work around the command line length limit on some
19566 systems.
19568 @end table
19570 @node Installing gnathtml
19571 @section Installing @code{gnathtml}
19573 @noindent
19574 @code{Perl} needs to be installed on your machine to run this script.
19575 @code{Perl} is freely available for almost every architecture and
19576 Operating System via the Internet.
19578 On Unix systems, you  may want to modify  the  first line of  the script
19579 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
19580 is. The syntax of this line is :
19581 @smallexample
19582 #!full_path_name_to_perl
19583 @end smallexample
19585 @noindent
19586 Alternatively, you may run the script using the following command line:
19588 @smallexample
19589 $ perl gnathtml.pl [switches] files
19590 @end smallexample
19592 @ifset vms
19593 @node LSE
19594 @section LSE
19595 @findex LSE
19597 @noindent
19598 The GNAT distribution provides an Ada 95 template for the HP Language
19599 Sensitive Editor (LSE), a component of DECset. In order to
19600 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
19602 @node Profiling
19603 @section Profiling
19604 @findex PCA
19606 @noindent
19607 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
19608 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
19609 the collection phase with the /DEBUG qualifier.
19611 @smallexample
19612 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
19613 $ DEFINE LIB$DEBUG PCA$COLLECTOR
19614 $ RUN/DEBUG <PROGRAM_NAME>
19615 @end smallexample
19616 @noindent
19617 @end ifset
19619 @node Running and Debugging Ada Programs
19620 @chapter Running and Debugging Ada Programs
19621 @cindex Debugging
19623 @noindent
19624 This chapter discusses how to debug Ada programs.
19625 @ifset vms
19626 It applies to the Alpha OpenVMS platform;
19627 the debugger for I64 OpenVMS is scheduled for a subsequent release.
19628 @end ifset
19630 An incorrect Ada program may be handled in three ways by the GNAT compiler:
19632 @enumerate
19633 @item
19634 The illegality may be a violation of the static semantics of Ada. In
19635 that case GNAT diagnoses the constructs in the program that are illegal.
19636 It is then a straightforward matter for the user to modify those parts of
19637 the program.
19639 @item
19640 The illegality may be a violation of the dynamic semantics of Ada. In
19641 that case the program compiles and executes, but may generate incorrect
19642 results, or may terminate abnormally with some exception.
19644 @item
19645 When presented with a program that contains convoluted errors, GNAT
19646 itself may terminate abnormally without providing full diagnostics on
19647 the incorrect user program.
19648 @end enumerate
19650 @menu
19651 * The GNAT Debugger GDB::
19652 * Running GDB::
19653 * Introduction to GDB Commands::
19654 * Using Ada Expressions::
19655 * Calling User-Defined Subprograms::
19656 * Using the Next Command in a Function::
19657 * Ada Exceptions::
19658 * Ada Tasks::
19659 * Debugging Generic Units::
19660 * GNAT Abnormal Termination or Failure to Terminate::
19661 * Naming Conventions for GNAT Source Files::
19662 * Getting Internal Debugging Information::
19663 * Stack Traceback::
19664 @end menu
19666 @cindex Debugger
19667 @findex gdb
19669 @node The GNAT Debugger GDB
19670 @section The GNAT Debugger GDB
19672 @noindent
19673 @code{GDB} is a general purpose, platform-independent debugger that
19674 can be used to debug mixed-language programs compiled with @command{gcc},
19675 and in particular is capable of debugging Ada programs compiled with
19676 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19677 complex Ada data structures.
19679 The manual @cite{Debugging with GDB}
19680 @ifset vms
19681 , located in the GNU:[DOCS] directory,
19682 @end ifset
19683 contains full details on the usage of @code{GDB}, including a section on
19684 its usage on programs. This manual should be consulted for full
19685 details. The section that follows is a brief introduction to the
19686 philosophy and use of @code{GDB}.
19688 When GNAT programs are compiled, the compiler optionally writes debugging
19689 information into the generated object file, including information on
19690 line numbers, and on declared types and variables. This information is
19691 separate from the generated code. It makes the object files considerably
19692 larger, but it does not add to the size of the actual executable that
19693 will be loaded into memory, and has no impact on run-time performance. The
19694 generation of debug information is triggered by the use of the
19695 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
19696 the compilations. It is important to emphasize that the use of these
19697 options does not change the generated code.
19699 The debugging information is written in standard system formats that
19700 are used by many tools, including debuggers and profilers. The format
19701 of the information is typically designed to describe C types and
19702 semantics, but GNAT implements a translation scheme which allows full
19703 details about Ada types and variables to be encoded into these
19704 standard C formats. Details of this encoding scheme may be found in
19705 the file exp_dbug.ads in the GNAT source distribution. However, the
19706 details of this encoding are, in general, of no interest to a user,
19707 since @code{GDB} automatically performs the necessary decoding.
19709 When a program is bound and linked, the debugging information is
19710 collected from the object files, and stored in the executable image of
19711 the program. Again, this process significantly increases the size of
19712 the generated executable file, but it does not increase the size of
19713 the executable program itself. Furthermore, if this program is run in
19714 the normal manner, it runs exactly as if the debug information were
19715 not present, and takes no more actual memory.
19717 However, if the program is run under control of @code{GDB}, the
19718 debugger is activated.  The image of the program is loaded, at which
19719 point it is ready to run.  If a run command is given, then the program
19720 will run exactly as it would have if @code{GDB} were not present. This
19721 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19722 entirely non-intrusive until a breakpoint is encountered.  If no
19723 breakpoint is ever hit, the program will run exactly as it would if no
19724 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19725 the debugging information and can respond to user commands to inspect
19726 variables, and more generally to report on the state of execution.
19728 @c **************
19729 @node Running GDB
19730 @section Running GDB
19732 @noindent
19733 The debugger can be launched directly and simply from @code{glide} or
19734 through its graphical interface: @code{gvd}. It can also be used
19735 directly in text mode. Here is described the basic use of @code{GDB}
19736 in text mode. All the commands described below can be used in the
19737 @code{gvd} console window even though there is usually other more
19738 graphical ways to achieve the same goals.
19740 @ifclear vms
19741 @noindent
19742 The command to run the graphical interface of the debugger is
19743 @smallexample
19744 $ gvd program
19745 @end smallexample
19746 @end ifclear
19748 @noindent
19749 The command to run @code{GDB} in text mode is
19751 @smallexample
19752 $ ^gdb program^$ GDB PROGRAM^
19753 @end smallexample
19755 @noindent
19756 where @code{^program^PROGRAM^} is the name of the executable file. This
19757 activates the debugger and results in a prompt for debugger commands.
19758 The simplest command is simply @code{run}, which causes the program to run
19759 exactly as if the debugger were not present. The following section
19760 describes some of the additional commands that can be given to @code{GDB}.
19762 @c *******************************
19763 @node Introduction to GDB Commands
19764 @section Introduction to GDB Commands
19766 @noindent
19767 @code{GDB} contains a large repertoire of commands. The manual
19768 @cite{Debugging with GDB}
19769 @ifset vms
19770 , located in the GNU:[DOCS] directory,
19771 @end ifset
19772 includes extensive documentation on the use
19773 of these commands, together with examples of their use. Furthermore,
19774 the command @var{help} invoked from within @code{GDB} activates a simple help
19775 facility which summarizes the available commands and their options.
19776 In this section we summarize a few of the most commonly
19777 used commands to give an idea of what @code{GDB} is about. You should create
19778 a simple program with debugging information and experiment with the use of
19779 these @code{GDB} commands on the program as you read through the
19780 following section.
19782 @table @code
19783 @item set args @var{arguments}
19784 The @var{arguments} list above is a list of arguments to be passed to
19785 the program on a subsequent run command, just as though the arguments
19786 had been entered on a normal invocation of the program. The @code{set args}
19787 command is not needed if the program does not require arguments.
19789 @item run
19790 The @code{run} command causes execution of the program to start from
19791 the beginning. If the program is already running, that is to say if
19792 you are currently positioned at a breakpoint, then a prompt will ask
19793 for confirmation that you want to abandon the current execution and
19794 restart.
19796 @item breakpoint @var{location}
19797 The breakpoint command sets a breakpoint, that is to say a point at which
19798 execution will halt and @code{GDB} will await further
19799 commands. @var{location} is
19800 either a line number within a file, given in the format @code{file:linenumber},
19801 or it is the name of a subprogram. If you request that a breakpoint be set on
19802 a subprogram that is overloaded, a prompt will ask you to specify on which of
19803 those subprograms you want to breakpoint. You can also
19804 specify that all of them should be breakpointed. If the program is run
19805 and execution encounters the breakpoint, then the program
19806 stops and @code{GDB} signals that the breakpoint was encountered by
19807 printing the line of code before which the program is halted.
19809 @item breakpoint exception @var{name}
19810 A special form of the breakpoint command which breakpoints whenever
19811 exception @var{name} is raised.
19812 If @var{name} is omitted,
19813 then a breakpoint will occur when any exception is raised.
19815 @item print @var{expression}
19816 This will print the value of the given expression. Most simple
19817 Ada expression formats are properly handled by @code{GDB}, so the expression
19818 can contain function calls, variables, operators, and attribute references.
19820 @item continue
19821 Continues execution following a breakpoint, until the next breakpoint or the
19822 termination of the program.
19824 @item step
19825 Executes a single line after a breakpoint. If the next statement
19826 is a subprogram call, execution continues into (the first statement of)
19827 the called subprogram.
19829 @item next
19830 Executes a single line. If this line is a subprogram call, executes and
19831 returns from the call.
19833 @item list
19834 Lists a few lines around the current source location. In practice, it
19835 is usually more convenient to have a separate edit window open with the
19836 relevant source file displayed. Successive applications of this command
19837 print subsequent lines. The command can be given an argument which is a
19838 line number, in which case it displays a few lines around the specified one.
19840 @item backtrace
19841 Displays a backtrace of the call chain. This command is typically
19842 used after a breakpoint has occurred, to examine the sequence of calls that
19843 leads to the current breakpoint. The display includes one line for each
19844 activation record (frame) corresponding to an active subprogram.
19846 @item up
19847 At a breakpoint, @code{GDB} can display the values of variables local
19848 to the current frame. The command @code{up} can be used to
19849 examine the contents of other active frames, by moving the focus up
19850 the stack, that is to say from callee to caller, one frame at a time.
19852 @item down
19853 Moves the focus of @code{GDB} down from the frame currently being
19854 examined to the frame of its callee (the reverse of the previous command),
19856 @item frame @var{n}
19857 Inspect the frame with the given number. The value 0 denotes the frame
19858 of the current breakpoint, that is to say the top of the call stack.
19860 @end table
19862 The above list is a very short introduction to the commands that
19863 @code{GDB} provides. Important additional capabilities, including conditional
19864 breakpoints, the ability to execute command sequences on a breakpoint,
19865 the ability to debug at the machine instruction level and many other
19866 features are described in detail in @cite{Debugging with GDB}.
19867 Note that most commands can be abbreviated
19868 (for example, c for continue, bt for backtrace).
19870 @node Using Ada Expressions
19871 @section Using Ada Expressions
19872 @cindex Ada expressions
19874 @noindent
19875 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19876 extensions. The philosophy behind the design of this subset is
19878 @itemize @bullet
19879 @item
19880 That @code{GDB} should provide basic literals and access to operations for
19881 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19882 leaving more sophisticated computations to subprograms written into the
19883 program (which therefore may be called from @code{GDB}).
19885 @item
19886 That type safety and strict adherence to Ada language restrictions
19887 are not particularly important to the @code{GDB} user.
19889 @item
19890 That brevity is important to the @code{GDB} user.
19891 @end itemize
19893 Thus, for brevity, the debugger acts as if there were
19894 implicit @code{with} and @code{use} clauses in effect for all user-written
19895 packages, thus making it unnecessary to fully qualify most names with
19896 their packages, regardless of context. Where this causes ambiguity,
19897 @code{GDB} asks the user's intent.
19899 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19901 @node Calling User-Defined Subprograms
19902 @section Calling User-Defined Subprograms
19904 @noindent
19905 An important capability of @code{GDB} is the ability to call user-defined
19906 subprograms while debugging. This is achieved simply by entering
19907 a subprogram call statement in the form:
19909 @smallexample
19910 call subprogram-name (parameters)
19911 @end smallexample
19913 @noindent
19914 The keyword @code{call} can be omitted in the normal case where the
19915 @code{subprogram-name} does not coincide with any of the predefined
19916 @code{GDB} commands.
19918 The effect is to invoke the given subprogram, passing it the
19919 list of parameters that is supplied. The parameters can be expressions and
19920 can include variables from the program being debugged. The
19921 subprogram must be defined
19922 at the library level within your program, and @code{GDB} will call the
19923 subprogram within the environment of your program execution (which
19924 means that the subprogram is free to access or even modify variables
19925 within your program).
19927 The most important use of this facility is in allowing the inclusion of
19928 debugging routines that are tailored to particular data structures
19929 in your program. Such debugging routines can be written to provide a suitably
19930 high-level description of an abstract type, rather than a low-level dump
19931 of its physical layout. After all, the standard
19932 @code{GDB print} command only knows the physical layout of your
19933 types, not their abstract meaning. Debugging routines can provide information
19934 at the desired semantic level and are thus enormously useful.
19936 For example, when debugging GNAT itself, it is crucial to have access to
19937 the contents of the tree nodes used to represent the program internally.
19938 But tree nodes are represented simply by an integer value (which in turn
19939 is an index into a table of nodes).
19940 Using the @code{print} command on a tree node would simply print this integer
19941 value, which is not very useful. But the PN routine (defined in file
19942 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19943 a useful high level representation of the tree node, which includes the
19944 syntactic category of the node, its position in the source, the integers
19945 that denote descendant nodes and parent node, as well as varied
19946 semantic information. To study this example in more detail, you might want to
19947 look at the body of the PN procedure in the stated file.
19949 @node Using the Next Command in a Function
19950 @section Using the Next Command in a Function
19952 @noindent
19953 When you use the @code{next} command in a function, the current source
19954 location will advance to the next statement as usual. A special case
19955 arises in the case of a @code{return} statement.
19957 Part of the code for a return statement is the ``epilog'' of the function.
19958 This is the code that returns to the caller. There is only one copy of
19959 this epilog code, and it is typically associated with the last return
19960 statement in the function if there is more than one return. In some
19961 implementations, this epilog is associated with the first statement
19962 of the function.
19964 The result is that if you use the @code{next} command from a return
19965 statement that is not the last return statement of the function you
19966 may see a strange apparent jump to the last return statement or to
19967 the start of the function. You should simply ignore this odd jump.
19968 The value returned is always that from the first return statement
19969 that was stepped through.
19971 @node Ada Exceptions
19972 @section Breaking on Ada Exceptions
19973 @cindex Exceptions
19975 @noindent
19976 You can set breakpoints that trip when your program raises
19977 selected exceptions.
19979 @table @code
19980 @item break exception
19981 Set a breakpoint that trips whenever (any task in the) program raises
19982 any exception.
19984 @item break exception @var{name}
19985 Set a breakpoint that trips whenever (any task in the) program raises
19986 the exception @var{name}.
19988 @item break exception unhandled
19989 Set a breakpoint that trips whenever (any task in the) program raises an
19990 exception for which there is no handler.
19992 @item info exceptions
19993 @itemx info exceptions @var{regexp}
19994 The @code{info exceptions} command permits the user to examine all defined
19995 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19996 argument, prints out only those exceptions whose name matches @var{regexp}.
19997 @end table
19999 @node Ada Tasks
20000 @section Ada Tasks
20001 @cindex Tasks
20003 @noindent
20004 @code{GDB} allows the following task-related commands:
20006 @table @code
20007 @item info tasks
20008 This command shows a list of current Ada tasks, as in the following example:
20010 @smallexample
20011 @iftex
20012 @leftskip=0cm
20013 @end iftex
20014 (gdb) info tasks
20015   ID       TID P-ID   Thread Pri State                 Name
20016    1   8088000   0   807e000  15 Child Activation Wait main_task
20017    2   80a4000   1   80ae000  15 Accept/Select Wait    b
20018    3   809a800   1   80a4800  15 Child Activation Wait a
20019 *  4   80ae800   3   80b8000  15 Running               c
20020 @end smallexample
20022 @noindent
20023 In this listing, the asterisk before the first task indicates it to be the
20024 currently running task. The first column lists the task ID that is used
20025 to refer to tasks in the following commands.
20027 @item break @var{linespec} task @var{taskid}
20028 @itemx break @var{linespec} task @var{taskid} if @dots{}
20029 @cindex Breakpoints and tasks
20030 These commands are like the @code{break @dots{} thread @dots{}}.
20031 @var{linespec} specifies source lines.
20033 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
20034 to specify that you only want @code{GDB} to stop the program when a
20035 particular Ada task reaches this breakpoint. @var{taskid} is one of the
20036 numeric task identifiers assigned by @code{GDB}, shown in the first
20037 column of the @samp{info tasks} display.
20039 If you do not specify @samp{task @var{taskid}} when you set a
20040 breakpoint, the breakpoint applies to @emph{all} tasks of your
20041 program.
20043 You can use the @code{task} qualifier on conditional breakpoints as
20044 well; in this case, place @samp{task @var{taskid}} before the
20045 breakpoint condition (before the @code{if}).
20047 @item task @var{taskno}
20048 @cindex Task switching
20050 This command allows to switch to the task referred by @var{taskno}. In
20051 particular, This allows to browse the backtrace of the specified
20052 task. It is advised to switch back to the original task before
20053 continuing execution otherwise the scheduling of the program may be
20054 perturbated.
20055 @end table
20057 @noindent
20058 For more detailed information on the tasking support,
20059 see @cite{Debugging with GDB}.
20061 @node Debugging Generic Units
20062 @section Debugging Generic Units
20063 @cindex Debugging Generic Units
20064 @cindex Generics
20066 @noindent
20067 GNAT always uses code expansion for generic instantiation. This means that
20068 each time an instantiation occurs, a complete copy of the original code is
20069 made, with appropriate substitutions of formals by actuals.
20071 It is not possible to refer to the original generic entities in
20072 @code{GDB}, but it is always possible to debug a particular instance of
20073 a generic, by using the appropriate expanded names. For example, if we have
20075 @smallexample @c ada
20076 @group
20077 @cartouche
20078 procedure g is
20080    generic package k is
20081       procedure kp (v1 : in out integer);
20082    end k;
20084    package body k is
20085       procedure kp (v1 : in out integer) is
20086       begin
20087          v1 := v1 + 1;
20088       end kp;
20089    end k;
20091    package k1 is new k;
20092    package k2 is new k;
20094    var : integer := 1;
20096 begin
20097    k1.kp (var);
20098    k2.kp (var);
20099    k1.kp (var);
20100    k2.kp (var);
20101 end;
20102 @end cartouche
20103 @end group
20104 @end smallexample
20106 @noindent
20107 Then to break on a call to procedure kp in the k2 instance, simply
20108 use the command:
20110 @smallexample
20111 (gdb) break g.k2.kp
20112 @end smallexample
20114 @noindent
20115 When the breakpoint occurs, you can step through the code of the
20116 instance in the normal manner and examine the values of local variables, as for
20117 other units.
20119 @node GNAT Abnormal Termination or Failure to Terminate
20120 @section GNAT Abnormal Termination or Failure to Terminate
20121 @cindex GNAT Abnormal Termination or Failure to Terminate
20123 @noindent
20124 When presented with programs that contain serious errors in syntax
20125 or semantics,
20126 GNAT may on rare occasions  experience problems in operation, such
20127 as aborting with a
20128 segmentation fault or illegal memory access, raising an internal
20129 exception, terminating abnormally, or failing to terminate at all.
20130 In such cases, you can activate
20131 various features of GNAT that can help you pinpoint the construct in your
20132 program that is the likely source of the problem.
20134 The following strategies are presented in increasing order of
20135 difficulty, corresponding to your experience in using GNAT and your
20136 familiarity with compiler internals.
20138 @enumerate
20139 @item
20140 Run @command{gcc} with the @option{-gnatf}. This first
20141 switch causes all errors on a given line to be reported. In its absence,
20142 only the first error on a line is displayed.
20144 The @option{-gnatdO} switch causes errors to be displayed as soon as they
20145 are encountered, rather than after compilation is terminated. If GNAT
20146 terminates prematurely or goes into an infinite loop, the last error
20147 message displayed may help to pinpoint the culprit.
20149 @item
20150 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
20151 mode, @command{gcc} produces ongoing information about the progress of the
20152 compilation and provides the name of each procedure as code is
20153 generated. This switch allows you to find which Ada procedure was being
20154 compiled when it encountered a code generation problem.
20156 @item
20157 @cindex @option{-gnatdc} switch
20158 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
20159 switch that does for the front-end what @option{^-v^VERBOSE^} does
20160 for the back end. The system prints the name of each unit,
20161 either a compilation unit or nested unit, as it is being analyzed.
20162 @item
20163 Finally, you can start
20164 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
20165 front-end of GNAT, and can be run independently (normally it is just
20166 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
20167 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
20168 @code{where} command is the first line of attack; the variable
20169 @code{lineno} (seen by @code{print lineno}), used by the second phase of
20170 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
20171 which the execution stopped, and @code{input_file name} indicates the name of
20172 the source file.
20173 @end enumerate
20175 @node Naming Conventions for GNAT Source Files
20176 @section Naming Conventions for GNAT Source Files
20178 @noindent
20179 In order to examine the workings of the GNAT system, the following
20180 brief description of its organization may be helpful:
20182 @itemize @bullet
20183 @item
20184 Files with prefix @file{^sc^SC^} contain the lexical scanner.
20186 @item
20187 All files prefixed with @file{^par^PAR^} are components of the parser. The
20188 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
20189 parsing of select statements can be found in @file{par-ch9.adb}.
20191 @item
20192 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
20193 numbers correspond to chapters of the Ada standard. For example, all
20194 issues involving context clauses can be found in @file{sem_ch10.adb}. In
20195 addition, some features of the language require sufficient special processing
20196 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
20197 dynamic dispatching, etc.
20199 @item
20200 All files prefixed with @file{^exp^EXP^} perform normalization and
20201 expansion of the intermediate representation (abstract syntax tree, or AST).
20202 these files use the same numbering scheme as the parser and semantics files.
20203 For example, the construction of record initialization procedures is done in
20204 @file{exp_ch3.adb}.
20206 @item
20207 The files prefixed with @file{^bind^BIND^} implement the binder, which
20208 verifies the consistency of the compilation, determines an order of
20209 elaboration, and generates the bind file.
20211 @item
20212 The files @file{atree.ads} and @file{atree.adb} detail the low-level
20213 data structures used by the front-end.
20215 @item
20216 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
20217 the abstract syntax tree as produced by the parser.
20219 @item
20220 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
20221 all entities, computed during semantic analysis.
20223 @item
20224 Library management issues are dealt with in files with prefix
20225 @file{^lib^LIB^}.
20227 @item
20228 @findex Ada
20229 @cindex Annex A
20230 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
20231 defined in Annex A.
20233 @item
20234 @findex Interfaces
20235 @cindex Annex B
20236 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
20237 defined in Annex B.
20239 @item
20240 @findex System
20241 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
20242 both language-defined children and GNAT run-time routines.
20244 @item
20245 @findex GNAT
20246 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
20247 general-purpose packages, fully documented in their specifications. All
20248 the other @file{.c} files are modifications of common @command{gcc} files.
20249 @end itemize
20251 @node Getting Internal Debugging Information
20252 @section Getting Internal Debugging Information
20254 @noindent
20255 Most compilers have internal debugging switches and modes. GNAT
20256 does also, except GNAT internal debugging switches and modes are not
20257 secret. A summary and full description of all the compiler and binder
20258 debug flags are in the file @file{debug.adb}. You must obtain the
20259 sources of the compiler to see the full detailed effects of these flags.
20261 The switches that print the source of the program (reconstructed from
20262 the internal tree) are of general interest for user programs, as are the
20263 options to print
20264 the full internal tree, and the entity table (the symbol table
20265 information). The reconstructed source provides a readable version of the
20266 program after the front-end has completed analysis and  expansion,
20267 and is useful when studying the performance of specific constructs.
20268 For example, constraint checks are indicated, complex aggregates
20269 are replaced with loops and assignments, and tasking primitives
20270 are replaced with run-time calls.
20272 @node Stack Traceback
20273 @section Stack Traceback
20274 @cindex traceback
20275 @cindex stack traceback
20276 @cindex stack unwinding
20278 @noindent
20279 Traceback is a mechanism to display the sequence of subprogram calls that
20280 leads to a specified execution point in a program. Often (but not always)
20281 the execution point is an instruction at which an exception has been raised.
20282 This mechanism is also known as @i{stack unwinding} because it obtains
20283 its information by scanning the run-time stack and recovering the activation
20284 records of all active subprograms. Stack unwinding is one of the most
20285 important tools for program debugging.
20287 The first entry stored in traceback corresponds to the deepest calling level,
20288 that is to say the subprogram currently executing the instruction
20289 from which we want to obtain the traceback.
20291 Note that there is no runtime performance penalty when stack traceback
20292 is enabled, and no exception is raised during program execution.
20294 @menu
20295 * Non-Symbolic Traceback::
20296 * Symbolic Traceback::
20297 @end menu
20299 @node Non-Symbolic Traceback
20300 @subsection Non-Symbolic Traceback
20301 @cindex traceback, non-symbolic
20303 @noindent
20304 Note: this feature is not supported on all platforms. See
20305 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
20306 platforms.
20308 @menu
20309 * Tracebacks From an Unhandled Exception::
20310 * Tracebacks From Exception Occurrences (non-symbolic)::
20311 * Tracebacks From Anywhere in a Program (non-symbolic)::
20312 @end menu
20314 @node Tracebacks From an Unhandled Exception
20315 @subsubsection Tracebacks From an Unhandled Exception
20317 @noindent
20318 A runtime non-symbolic traceback is a list of addresses of call instructions.
20319 To enable this feature you must use the @option{-E}
20320 @code{gnatbind}'s option. With this option a stack traceback is stored as part
20321 of exception information. You can retrieve this information using the
20322 @code{addr2line} tool.
20324 Here is a simple example:
20326 @smallexample @c ada
20327 @cartouche
20328 procedure STB is
20330    procedure P1 is
20331    begin
20332       raise Constraint_Error;
20333    end P1;
20335    procedure P2 is
20336    begin
20337       P1;
20338    end P2;
20340 begin
20341    P2;
20342 end STB;
20343 @end cartouche
20344 @end smallexample
20346 @smallexample
20347 $ gnatmake stb -bargs -E
20348 $ stb
20350 Execution terminated by unhandled exception
20351 Exception name: CONSTRAINT_ERROR
20352 Message: stb.adb:5
20353 Call stack traceback locations:
20354 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20355 @end smallexample
20357 @noindent
20358 As we see the traceback lists a sequence of addresses for the unhandled
20359 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20360 guess that this exception come from procedure P1. To translate these
20361 addresses into the source lines where the calls appear, the
20362 @code{addr2line} tool, described below, is invaluable. The use of this tool
20363 requires the program to be compiled with debug information.
20365 @smallexample
20366 $ gnatmake -g stb -bargs -E
20367 $ stb
20369 Execution terminated by unhandled exception
20370 Exception name: CONSTRAINT_ERROR
20371 Message: stb.adb:5
20372 Call stack traceback locations:
20373 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20375 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
20376    0x4011f1 0x77e892a4
20378 00401373 at d:/stb/stb.adb:5
20379 0040138B at d:/stb/stb.adb:10
20380 0040139C at d:/stb/stb.adb:14
20381 00401335 at d:/stb/b~stb.adb:104
20382 004011C4 at /build/.../crt1.c:200
20383 004011F1 at /build/.../crt1.c:222
20384 77E892A4 in ?? at ??:0
20385 @end smallexample
20387 @noindent
20388 The @code{addr2line} tool has several other useful options:
20390 @table @code
20391 @item --functions
20392 to get the function name corresponding to any location
20394 @item --demangle=gnat
20395 to use the gnat decoding mode for the function names. Note that
20396 for binutils version 2.9.x the option is simply @option{--demangle}.
20397 @end table
20399 @smallexample
20400 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20401    0x40139c 0x401335 0x4011c4 0x4011f1
20403 00401373 in stb.p1 at d:/stb/stb.adb:5
20404 0040138B in stb.p2 at d:/stb/stb.adb:10
20405 0040139C in stb at d:/stb/stb.adb:14
20406 00401335 in main at d:/stb/b~stb.adb:104
20407 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
20408 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
20409 @end smallexample
20411 @noindent
20412 From this traceback we can see that the exception was raised in
20413 @file{stb.adb} at line 5, which was reached from a procedure call in
20414 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
20415 which contains the call to the main program.
20416 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
20417 and the output will vary from platform to platform.
20419 It is also possible to use @code{GDB} with these traceback addresses to debug
20420 the program. For example, we can break at a given code location, as reported
20421 in the stack traceback:
20423 @smallexample
20424 $ gdb -nw stb
20425 @ifclear vms
20426 @noindent
20427 Furthermore, this feature is not implemented inside Windows DLL. Only
20428 the non-symbolic traceback is reported in this case.
20429 @end ifclear
20431 (gdb) break *0x401373
20432 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20433 @end smallexample
20435 @noindent
20436 It is important to note that the stack traceback addresses
20437 do not change when debug information is included. This is particularly useful
20438 because it makes it possible to release software without debug information (to
20439 minimize object size), get a field report that includes a stack traceback
20440 whenever an internal bug occurs, and then be able to retrieve the sequence
20441 of calls with the same program compiled with debug information.
20443 @node Tracebacks From Exception Occurrences (non-symbolic)
20444 @subsubsection Tracebacks From Exception Occurrences
20446 @noindent
20447 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
20448 The stack traceback is attached to the exception information string, and can
20449 be retrieved in an exception handler within the Ada program, by means of the
20450 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20452 @smallexample @c ada
20453 with Ada.Text_IO;
20454 with Ada.Exceptions;
20456 procedure STB is
20458    use Ada;
20459    use Ada.Exceptions;
20461    procedure P1 is
20462       K : Positive := 1;
20463    begin
20464       K := K - 1;
20465    exception
20466       when E : others =>
20467          Text_IO.Put_Line (Exception_Information (E));
20468    end P1;
20470    procedure P2 is
20471    begin
20472       P1;
20473    end P2;
20475 begin
20476    P2;
20477 end STB;
20478 @end smallexample
20480 @noindent
20481 This program will output:
20483 @smallexample
20484 $ stb
20486 Exception name: CONSTRAINT_ERROR
20487 Message: stb.adb:12
20488 Call stack traceback locations:
20489 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20490 @end smallexample
20492 @node Tracebacks From Anywhere in a Program (non-symbolic)
20493 @subsubsection Tracebacks From Anywhere in a Program
20495 @noindent
20496 It is also possible to retrieve a stack traceback from anywhere in a
20497 program. For this you need to
20498 use the @code{GNAT.Traceback} API. This package includes a procedure called
20499 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20500 display procedures described below. It is not necessary to use the
20501 @option{-E gnatbind} option in this case, because the stack traceback mechanism
20502 is invoked explicitly.
20504 @noindent
20505 In the following example we compute a traceback at a specific location in
20506 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20507 convert addresses to strings:
20509 @smallexample @c ada
20510 with Ada.Text_IO;
20511 with GNAT.Traceback;
20512 with GNAT.Debug_Utilities;
20514 procedure STB is
20516    use Ada;
20517    use GNAT;
20518    use GNAT.Traceback;
20520    procedure P1 is
20521       TB  : Tracebacks_Array (1 .. 10);
20522       --  We are asking for a maximum of 10 stack frames.
20523       Len : Natural;
20524       --  Len will receive the actual number of stack frames returned.
20525    begin
20526       Call_Chain (TB, Len);
20528       Text_IO.Put ("In STB.P1 : ");
20530       for K in 1 .. Len loop
20531          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20532          Text_IO.Put (' ');
20533       end loop;
20535       Text_IO.New_Line;
20536    end P1;
20538    procedure P2 is
20539    begin
20540       P1;
20541    end P2;
20543 begin
20544    P2;
20545 end STB;
20546 @end smallexample
20548 @smallexample
20549 $ gnatmake -g stb
20550 $ stb
20552 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20553 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20554 @end smallexample
20556 @noindent
20557 You can then get further information by invoking the @code{addr2line}
20558 tool as described earlier (note that the hexadecimal addresses
20559 need to be specified in C format, with a leading ``0x'').
20561 @node Symbolic Traceback
20562 @subsection Symbolic Traceback
20563 @cindex traceback, symbolic
20565 @noindent
20566 A symbolic traceback is a stack traceback in which procedure names are
20567 associated with each code location.
20569 @noindent
20570 Note that this feature is not supported on all platforms. See
20571 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
20572 list of currently supported platforms.
20574 @noindent
20575 Note that the symbolic traceback requires that the program be compiled
20576 with debug information. If it is not compiled with debug information
20577 only the non-symbolic information will be valid.
20579 @menu
20580 * Tracebacks From Exception Occurrences (symbolic)::
20581 * Tracebacks From Anywhere in a Program (symbolic)::
20582 @end menu
20584 @node Tracebacks From Exception Occurrences (symbolic)
20585 @subsubsection Tracebacks From Exception Occurrences
20587 @smallexample @c ada
20588 with Ada.Text_IO;
20589 with GNAT.Traceback.Symbolic;
20591 procedure STB is
20593    procedure P1 is
20594    begin
20595       raise Constraint_Error;
20596    end P1;
20598    procedure P2 is
20599    begin
20600       P1;
20601    end P2;
20603    procedure P3 is
20604    begin
20605       P2;
20606    end P3;
20608 begin
20609    P3;
20610 exception
20611    when E : others =>
20612       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20613 end STB;
20614 @end smallexample
20616 @smallexample
20617 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
20618 $ stb
20620 0040149F in stb.p1 at stb.adb:8
20621 004014B7 in stb.p2 at stb.adb:13
20622 004014CF in stb.p3 at stb.adb:18
20623 004015DD in ada.stb at stb.adb:22
20624 00401461 in main at b~stb.adb:168
20625 004011C4 in __mingw_CRTStartup at crt1.c:200
20626 004011F1 in mainCRTStartup at crt1.c:222
20627 77E892A4 in ?? at ??:0
20628 @end smallexample
20630 @noindent
20631 In the above example the ``.\'' syntax in the @command{gnatmake} command
20632 is currently required by @command{addr2line} for files that are in
20633 the current working directory.
20634 Moreover, the exact sequence of linker options may vary from platform
20635 to platform.
20636 The above @option{-largs} section is for Windows platforms. By contrast,
20637 under Unix there is no need for the @option{-largs} section.
20638 Differences across platforms are due to details of linker implementation.
20640 @node Tracebacks From Anywhere in a Program (symbolic)
20641 @subsubsection Tracebacks From Anywhere in a Program
20643 @noindent
20644 It is possible to get a symbolic stack traceback
20645 from anywhere in a program, just as for non-symbolic tracebacks.
20646 The first step is to obtain a non-symbolic
20647 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20648 information. Here is an example:
20650 @smallexample @c ada
20651 with Ada.Text_IO;
20652 with GNAT.Traceback;
20653 with GNAT.Traceback.Symbolic;
20655 procedure STB is
20657    use Ada;
20658    use GNAT.Traceback;
20659    use GNAT.Traceback.Symbolic;
20661    procedure P1 is
20662       TB  : Tracebacks_Array (1 .. 10);
20663       --  We are asking for a maximum of 10 stack frames.
20664       Len : Natural;
20665       --  Len will receive the actual number of stack frames returned.
20666    begin
20667       Call_Chain (TB, Len);
20668       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20669    end P1;
20671    procedure P2 is
20672    begin
20673       P1;
20674    end P2;
20676 begin
20677    P2;
20678 end STB;
20679 @end smallexample
20682 @c ******************************
20683 @ifset vms
20684 @node Compatibility with HP Ada
20685 @chapter Compatibility with HP Ada
20686 @cindex Compatibility
20688 @noindent
20689 @cindex DEC Ada
20690 @cindex HP Ada
20691 @cindex Compatibility between GNAT and HP Ada
20692 This chapter compares HP Ada (formerly known as ``DEC Ada'')
20693 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
20694 GNAT is highly compatible
20695 with HP Ada, and it should generally be straightforward to port code
20696 from the HP Ada environment to GNAT. However, there are a few language
20697 and implementation differences of which the user must be aware. These
20698 differences are discussed in this chapter. In
20699 addition, the operating environment and command structure for the
20700 compiler are different, and these differences are also discussed.
20702 For further details on these and other compatibility issues,
20703 see Appendix E of the HP publication
20704 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
20706 Except where otherwise indicated, the description of GNAT for OpenVMS
20707 applies to both the Alpha and I64 platforms.
20709 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
20710 I64 OpenVMS, see @ref{Transitioning from Alpha to I64 OpenVMS}.
20712 The discussion in this chapter addresses specifically the implementation
20713 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
20714 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20715 GNAT always follows the Alpha implementation.
20717 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
20718 attributes are recognized, although only a subset of them can sensibly
20719 be implemented.  The description of pragmas in the
20720 @cite{GNAT Reference Manual} indicates whether or not they are applicable
20721 to non-VMS systems.
20724 @menu
20725 * Ada 95 Compatibility::
20726 * Differences in the Definition of Package System::
20727 * Language-Related Features::
20728 * The Package STANDARD::
20729 * The Package SYSTEM::
20730 * Tasking and Task-Related Features::
20731 * Pragmas and Pragma-Related Features::
20732 * Library of Predefined Units::
20733 * Bindings::
20734 * Main Program Definition::
20735 * Implementation-Defined Attributes::
20736 * Compiler and Run-Time Interfacing::
20737 * Program Compilation and Library Management::
20738 * Input-Output::
20739 * Implementation Limits::
20740 * Tools and Utilities::
20741 @end menu
20743 @node Ada 95 Compatibility
20744 @section Ada 95 Compatibility
20746 @noindent
20747 GNAT is an Ada 95 compiler, and HP Ada is an Ada 83
20748 compiler. Ada 95 is almost completely upwards compatible
20749 with Ada 83, and therefore Ada 83 programs will compile
20750 and run under GNAT with
20751 no changes or only minor changes. The Ada 95 Reference
20752 Manual provides details on specific incompatibilities.
20754 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
20755 as well as the pragma @code{ADA_83}, to force the compiler to
20756 operate in Ada 83 mode. This mode does not guarantee complete
20757 conformance to Ada 83, but in practice is sufficient to
20758 eliminate most sources of incompatibilities.
20759 In particular, it eliminates the recognition of the
20760 additional Ada 95 keywords, so that their use as identifiers
20761 in Ada 83 programs is legal, and handles the cases of packages
20762 with optional bodies, and generics that instantiate unconstrained
20763 types without the use of @code{(<>)}.
20765 @node Differences in the Definition of Package System
20766 @section Differences in the Definition of Package @code{System}
20768 @noindent
20769 Both Ada 95 and Ada 83 permit a compiler to add
20770 implementation-dependent declarations to package @code{System}.
20771 In normal mode,
20772 GNAT does not take advantage of this permission, and the version of
20773 @code{System} provided by GNAT exactly matches that in Ada 95.
20775 However, HP Ada adds an extensive set of declarations to package
20776 @code{System},
20777 as fully documented in the HP Ada manuals. To minimize changes required
20778 for programs that make use of these extensions, GNAT provides the pragma
20779 @code{Extend_System} for extending the definition of package System. By using:
20780 @cindex pragma @code{Extend_System}
20781 @cindex @code{Extend_System} pragma
20783 @smallexample @c ada
20784 @group
20785 @cartouche
20786 pragma Extend_System (Aux_DEC);
20787 @end cartouche
20788 @end group
20789 @end smallexample
20791 @noindent
20792 the set of definitions in @code{System} is extended to include those in
20793 package @code{System.Aux_DEC}.
20794 @cindex @code{System.Aux_DEC} package
20795 @cindex @code{Aux_DEC} package (child of @code{System})
20796 These definitions are incorporated directly into package @code{System},
20797 as though they had been declared there. For a
20798 list of the declarations added, see the specification of this package,
20799 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
20800 @cindex @file{s-auxdec.ads} file
20801 The pragma @code{Extend_System} is a configuration pragma, which means that
20802 it can be placed in the file @file{gnat.adc}, so that it will automatically
20803 apply to all subsequent compilations. See @ref{Configuration Pragmas},
20804 for further details.
20806 An alternative approach that avoids the use of the non-standard
20807 @code{Extend_System} pragma is to add a context clause to the unit that
20808 references these facilities:
20810 @smallexample @c ada
20811 @cartouche
20812 with System.Aux_DEC;
20813 use  System.Aux_DEC;
20814 @end cartouche
20815 @end smallexample
20817 @noindent
20818 The effect is not quite semantically identical to incorporating
20819 the declarations directly into package @code{System},
20820 but most programs will not notice a difference
20821 unless they use prefix notation (e.g. @code{System.Integer_8})
20822 to reference the entities directly in package @code{System}.
20823 For units containing such references,
20824 the prefixes must either be removed, or the pragma @code{Extend_System}
20825 must be used.
20827 @node Language-Related Features
20828 @section Language-Related Features
20830 @noindent
20831 The following sections highlight differences in types,
20832 representations of types, operations, alignment, and
20833 related topics.
20835 @menu
20836 * Integer Types and Representations::
20837 * Floating-Point Types and Representations::
20838 * Pragmas Float_Representation and Long_Float::
20839 * Fixed-Point Types and Representations::
20840 * Record and Array Component Alignment::
20841 * Address Clauses::
20842 * Other Representation Clauses::
20843 @end menu
20845 @node Integer Types and Representations
20846 @subsection Integer Types and Representations
20848 @noindent
20849 The set of predefined integer types is identical in HP Ada and GNAT.
20850 Furthermore the representation of these integer types is also identical,
20851 including the capability of size clauses forcing biased representation.
20853 In addition,
20854 HP Ada for OpenVMS Alpha systems has defined the
20855 following additional integer types in package @code{System}:
20857 @itemize @bullet
20859 @item
20860 @code{INTEGER_8}
20862 @item
20863 @code{INTEGER_16}
20865 @item
20866 @code{INTEGER_32}
20868 @item
20869 @code{INTEGER_64}
20871 @item
20872 @code{LARGEST_INTEGER}
20873 @end itemize
20875 @noindent
20876 In GNAT, the first four of these types may be obtained from the
20877 standard Ada 95 package @code{Interfaces}.
20878 Alternatively, by use of the pragma @code{Extend_System}, identical
20879 declarations can be referenced directly in package @code{System}.
20880 On both GNAT and HP Ada, the maximum integer size is 64 bits.
20882 @node Floating-Point Types and Representations
20883 @subsection Floating-Point Types and Representations
20884 @cindex Floating-Point types
20886 @noindent
20887 The set of predefined floating-point types is identical in HP Ada and GNAT.
20888 Furthermore the representation of these floating-point
20889 types is also identical. One important difference is that the default
20890 representation for HP Ada is @code{VAX_Float}, but the default representation
20891 for GNAT is IEEE.
20893 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
20894 pragma @code{Float_Representation} as described in the HP Ada
20895 documentation.
20896 For example, the declarations:
20898 @smallexample @c ada
20899 @cartouche
20900 type F_Float is digits 6;
20901 pragma Float_Representation (VAX_Float, F_Float);
20902 @end cartouche
20903 @end smallexample
20905 @noindent
20906 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
20907 format.
20908 This set of declarations actually appears in @code{System.Aux_DEC},
20909 which contains
20910 the full set of additional floating-point declarations provided in
20911 the HP Ada version of package @code{System}.
20912 This and similar declarations may be accessed in a user program
20913 by using pragma @code{Extend_System}. The use of this
20914 pragma, and the related pragma @code{Long_Float} is described in further
20915 detail in the following section.
20917 @node Pragmas Float_Representation and Long_Float
20918 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
20920 @noindent
20921 HP Ada provides the pragma @code{Float_Representation}, which
20922 acts as a program library switch to allow control over
20923 the internal representation chosen for the predefined
20924 floating-point types declared in the package @code{Standard}.
20925 The format of this pragma is as follows:
20927 @smallexample @c ada
20928 @cartouche
20929 pragma Float_Representation(VAX_Float | IEEE_Float);
20930 @end cartouche
20931 @end smallexample
20933 @noindent
20934 This pragma controls the representation of floating-point
20935 types as follows:
20937 @itemize @bullet
20938 @item
20939 @code{VAX_Float} specifies that floating-point
20940 types are represented by default with the VAX system hardware types
20941 @code{F-floating}, @code{D-floating}, @code{G-floating}.
20942 Note that the @code{H-floating}
20943 type was available only on VAX systems, and is not available
20944 in either HP Ada or GNAT.
20946 @item
20947 @code{IEEE_Float} specifies that floating-point
20948 types are represented by default with the IEEE single and
20949 double floating-point types.
20950 @end itemize
20952 @noindent
20953 GNAT provides an identical implementation of the pragma
20954 @code{Float_Representation}, except that it functions as a
20955 configuration pragma. Note that the
20956 notion of configuration pragma corresponds closely to the
20957 HP Ada notion of a program library switch.
20959 When no pragma is used in GNAT, the default is @code{IEEE_Float},
20960 which is different
20961 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
20962 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
20963 advisable to change the format of numbers passed to standard library
20964 routines, and if necessary explicit type conversions may be needed.
20966 The use of @code{IEEE_Float} is recommended in GNAT since it is more
20967 efficient, and (given that it conforms to an international standard)
20968 potentially more portable.
20969 The situation in which @code{VAX_Float} may be useful is in interfacing
20970 to existing code and data that expect the use of @code{VAX_Float}.
20971 In such a situation use the predefined @code{VAX_Float}
20972 types in package @code{System}, as extended by
20973 @code{Extend_System}. For example, use @code{System.F_Float}
20974 to specify the 32-bit @code{F-Float} format.
20976 @noindent
20977 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
20978 to allow control over the internal representation chosen
20979 for the predefined type @code{Long_Float} and for floating-point
20980 type declarations with digits specified in the range 7 .. 15.
20981 The format of this pragma is as follows:
20983 @smallexample @c ada
20984 @cartouche
20985 pragma Long_Float (D_FLOAT | G_FLOAT);
20986 @end cartouche
20987 @end smallexample
20989 @node Fixed-Point Types and Representations
20990 @subsection Fixed-Point Types and Representations
20992 @noindent
20993 On HP Ada for OpenVMS Alpha systems, rounding is
20994 away from zero for both positive and negative numbers.
20995 Therefore, @code{+0.5} rounds to @code{1},
20996 and @code{-0.5} rounds to @code{-1}.
20998 On GNAT the results of operations
20999 on fixed-point types are in accordance with the Ada 95
21000 rules. In particular, results of operations on decimal
21001 fixed-point types are truncated.
21003 @node Record and Array Component Alignment
21004 @subsection Record and Array Component Alignment
21006 @noindent
21007 On HP Ada for OpenVMS Alpha, all non composite components
21008 are aligned on natural boundaries. For example, 1-byte
21009 components are aligned on byte boundaries, 2-byte
21010 components on 2-byte boundaries, 4-byte components on 4-byte
21011 byte boundaries, and so on. The OpenVMS Alpha hardware
21012 runs more efficiently with naturally aligned data.
21014 On GNAT, alignment rules are compatible
21015 with HP Ada for OpenVMS Alpha.
21017 @node Address Clauses
21018 @subsection Address Clauses
21020 @noindent
21021 In HP Ada and GNAT, address clauses are supported for
21022 objects and imported subprograms.
21023 The predefined type @code{System.Address} is a private type
21024 in both compilers on Alpha OpenVMS, with the same representation
21025 (it is simply a machine pointer). Addition, subtraction, and comparison
21026 operations are available in the standard Ada 95 package
21027 @code{System.Storage_Elements}, or in package @code{System}
21028 if it is extended to include @code{System.Aux_DEC} using a
21029 pragma @code{Extend_System} as previously described.
21031 Note that code that @code{with}'s both this extended package @code{System}
21032 and the package @code{System.Storage_Elements} should not @code{use}
21033 both packages, or ambiguities will result. In general it is better
21034 not to mix these two sets of facilities. The Ada 95 package was
21035 designed specifically to provide the kind of features that HP Ada
21036 adds directly to package @code{System}.
21038 The type @code{System.Address} is a 64-bit integer type in GNAT for
21039 I64 OpenVMS.  For more information,
21040 see @ref{Transitioning from Alpha to I64 OpenVMS}.
21042 GNAT is compatible with HP Ada in its handling of address
21043 clauses, except for some limitations in
21044 the form of address clauses for composite objects with
21045 initialization. Such address clauses are easily replaced
21046 by the use of an explicitly-defined constant as described
21047 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
21048 of declarations:
21050 @smallexample @c ada
21051 @cartouche
21052 X, Y : Integer := Init_Func;
21053 Q : String (X .. Y) := "abc";
21055 for Q'Address use Compute_Address;
21056 @end cartouche
21057 @end smallexample
21059 @noindent
21060 will be rejected by GNAT, since the address cannot be computed at the time
21061 that @code{Q} is declared. To achieve the intended effect, write instead:
21063 @smallexample @c ada
21064 @group
21065 @cartouche
21066 X, Y : Integer := Init_Func;
21067 Q_Address : constant Address := Compute_Address;
21068 Q : String (X .. Y) := "abc";
21070 for Q'Address use Q_Address;
21071 @end cartouche
21072 @end group
21073 @end smallexample
21075 @noindent
21076 which will be accepted by GNAT (and other Ada 95 compilers), and is also
21077 compatible with Ada 83. A fuller description of the restrictions
21078 on address specifications is found in the @cite{GNAT Reference Manual}.
21080 @node Other Representation Clauses
21081 @subsection Other Representation Clauses
21083 @noindent
21084 GNAT implements in a compatible manner all the representation
21085 clauses supported by HP Ada. In addition, GNAT
21086 implements the representation clause forms that were introduced in Ada 95,
21087 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
21089 @node The Package STANDARD
21090 @section The Package @code{STANDARD}
21092 @noindent
21093 The package @code{STANDARD}, as implemented by HP Ada, is fully
21094 described in the Ada 95 Reference Manual and in the HP Ada
21095 Language Reference Manual. As implemented by GNAT, the
21096 package @code{STANDARD} is described in the Ada 95 Reference
21097 Manual.
21099 In addition, HP Ada supports the Latin-1 character set in
21100 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
21101 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
21102 the type @code{WIDE_CHARACTER}.
21104 The floating-point types supported by GNAT are those
21105 supported by HP Ada, but the defaults are different, and are controlled by
21106 pragmas. See @ref{Floating-Point Types and Representations}, for details.
21108 @node The Package SYSTEM
21109 @section The Package @code{SYSTEM}
21111 @noindent
21112 HP Ada provides a specific version of the package
21113 @code{SYSTEM} for each platform on which the language is implemented.
21114 For the complete specification of the package @code{SYSTEM}, see
21115 Appendix F of the @cite{HP Ada Language Reference Manual}.
21117 On HP Ada, the package @code{SYSTEM} includes the following conversion
21118 functions:
21119 @itemize @bullet
21120 @item @code{TO_ADDRESS(INTEGER)}
21122 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
21124 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
21126 @item @code{TO_INTEGER(ADDRESS)}
21128 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
21130 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
21131               functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
21132 @end itemize
21134 @noindent
21135 By default, GNAT supplies a version of @code{SYSTEM} that matches
21136 the definition given in the Ada 95 Reference Manual.
21137 This
21138 is a subset of the HP system definitions, which is as
21139 close as possible to the original definitions. The only difference
21140 is that the definition of @code{SYSTEM_NAME} is different:
21142 @smallexample @c ada
21143 @cartouche
21144 type Name is (SYSTEM_NAME_GNAT);
21145 System_Name : constant Name := SYSTEM_NAME_GNAT;
21146 @end cartouche
21147 @end smallexample
21149 @noindent
21150 Also, GNAT adds the new Ada 95 declarations for
21151 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
21153 However, the use of the following pragma causes GNAT
21154 to extend the definition of package @code{SYSTEM} so that it
21155 encompasses the full set of HP-specific extensions,
21156 including the functions listed above:
21158 @smallexample @c ada
21159 @cartouche
21160 pragma Extend_System (Aux_DEC);
21161 @end cartouche
21162 @end smallexample
21164 @noindent
21165 The pragma @code{Extend_System} is a configuration pragma that
21166 is most conveniently placed in the @file{gnat.adc} file. See the
21167 @cite{GNAT Reference Manual} for further details.
21169 HP Ada does not allow the recompilation of the package
21170 @code{SYSTEM}. Instead HP Ada provides several pragmas
21171 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
21172 to modify values in the package @code{SYSTEM}.
21173 On OpenVMS Alpha systems, the pragma
21174 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
21175 its single argument.
21177 GNAT does permit the recompilation of package @code{SYSTEM} using
21178 the special switch @option{-gnatg}, and this switch can be used if
21179 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
21180 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
21181 or @code{MEMORY_SIZE} by any other means.
21183 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
21184 enumeration literal @code{SYSTEM_NAME_GNAT}.
21186 The definitions provided by the use of
21188 @smallexample @c ada
21189 pragma Extend_System (AUX_Dec);
21190 @end smallexample
21192 @noindent
21193 are virtually identical to those provided by the HP Ada 83 package
21194 @code{SYSTEM}. One important difference is that the name of the
21195 @code{TO_ADDRESS}
21196 function for type @code{UNSIGNED_LONGWORD} is changed to
21197 @code{TO_ADDRESS_LONG}.
21198 See the @cite{GNAT Reference Manual} for a discussion of why this change was
21199 necessary.
21201 @noindent
21202 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
21203 is in fact
21204 an extension to Ada 83 not strictly compatible with the reference manual.
21205 GNAT, in order to be exactly compatible with the standard,
21206 does not provide this capability. In HP Ada 83, the
21207 point of this definition is to deal with a call like:
21209 @smallexample @c ada
21210 TO_ADDRESS (16#12777#);
21211 @end smallexample
21213 @noindent
21214 Normally, according to Ada 83 semantics, one would expect this to be
21215 ambiguous, since it matches both the @code{INTEGER} and
21216 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
21217 However, in HP Ada 83, there is no ambiguity, since the
21218 definition using @i{universal_integer} takes precedence.
21220 In GNAT, since the version with @i{universal_integer} cannot be supplied,
21221 it is
21222 not possible to be 100% compatible. Since there are many programs using
21223 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
21224 GNAT was
21225 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
21226 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
21228 @smallexample @c ada
21229 function To_Address (X : Integer) return Address;
21230 pragma Pure_Function (To_Address);
21232 function To_Address_Long (X : Unsigned_Longword) return Address;
21233 pragma Pure_Function (To_Address_Long);
21234 @end smallexample
21236 @noindent
21237 This means that programs using @code{TO_ADDRESS} for
21238 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
21240 @node Tasking and Task-Related Features
21241 @section Tasking and Task-Related Features
21243 @noindent
21244 This section compares the treatment of tasking in GNAT
21245 and in HP Ada for OpenVMS Alpha.
21246 The GNAT description applies to both Alpha and I64 OpenVMS.
21247 For detailed information on tasking in
21248 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
21249 relevant run-time reference manual.
21251 @menu
21252 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
21253 * Assigning Task IDs::
21254 * Task IDs and Delays::
21255 * Task-Related Pragmas::
21256 * Scheduling and Task Priority::
21257 * The Task Stack::
21258 * External Interrupts::
21259 @end menu
21261 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21262 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
21264 @noindent
21265 On OpenVMS Alpha systems, each Ada task (except a passive
21266 task) is implemented as a single stream of execution
21267 that is created and managed by the kernel. On these
21268 systems, HP Ada tasking support is based on DECthreads,
21269 an implementation of the POSIX standard for threads.
21271 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
21272 code that calls DECthreads routines can be used together.
21273 The interaction between Ada tasks and DECthreads routines
21274 can have some benefits. For example when on OpenVMS Alpha,
21275 HP Ada can call C code that is already threaded.
21277 GNAT uses the facilities of DECthreads,
21278 and Ada tasks are mapped to threads.
21281 @node Assigning Task IDs
21282 @subsection Assigning Task IDs
21284 @noindent
21285 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
21286 the environment task that executes the main program. On
21287 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
21288 that have been created but are not yet activated.
21290 On OpenVMS Alpha systems, task IDs are assigned at
21291 activation. On GNAT systems, task IDs are also assigned at
21292 task creation but do not have the same form or values as
21293 task ID values in HP Ada. There is no null task, and the
21294 environment task does not have a specific task ID value.
21296 @node Task IDs and Delays
21297 @subsection Task IDs and Delays
21299 @noindent
21300 On OpenVMS Alpha systems, tasking delays are implemented
21301 using Timer System Services. The Task ID is used for the
21302 identification of the timer request (the @code{REQIDT} parameter).
21303 If Timers are used in the application take care not to use
21304 @code{0} for the identification, because cancelling such a timer
21305 will cancel all timers and may lead to unpredictable results.
21307 @node Task-Related Pragmas
21308 @subsection Task-Related Pragmas
21310 @noindent
21311 Ada supplies the pragma @code{TASK_STORAGE}, which allows
21312 specification of the size of the guard area for a task
21313 stack. (The guard area forms an area of memory that has no
21314 read or write access and thus helps in the detection of
21315 stack overflow.) On OpenVMS Alpha systems, if the pragma
21316 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
21317 area is created. In the absence of a pragma @code{TASK_STORAGE},
21318 a default guard area is created.
21320 GNAT supplies the following task-related pragmas:
21322 @itemize @bullet
21323 @item  @code{TASK_INFO}
21325               This pragma appears within a task definition and
21326               applies to the task in which it appears. The argument
21327               must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
21329 @item  @code{TASK_STORAGE}
21331               GNAT implements pragma @code{TASK_STORAGE} in the same way as
21332               HP Ada.
21333               Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
21334               @code{SUPPRESS}, and @code{VOLATILE}.
21335 @end itemize
21336 @node Scheduling and Task Priority
21337 @subsection Scheduling and Task Priority
21339 @noindent
21340 HP Ada implements the Ada language requirement that
21341 when two tasks are eligible for execution and they have
21342 different priorities, the lower priority task does not
21343 execute while the higher priority task is waiting. The HP
21344 Ada Run-Time Library keeps a task running until either the
21345 task is suspended or a higher priority task becomes ready.
21347 On OpenVMS Alpha systems, the default strategy is round-
21348 robin with preemption. Tasks of equal priority take turns
21349 at the processor. A task is run for a certain period of
21350 time and then placed at the tail of the ready queue for
21351 its priority level.
21353 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
21354 which can be used to enable or disable round-robin
21355 scheduling of tasks with the same priority.
21356 See the relevant HP Ada run-time reference manual for
21357 information on using the pragmas to control HP Ada task
21358 scheduling.
21360 GNAT follows the scheduling rules of Annex D (Real-Time
21361 Annex) of the Ada 95 Reference Manual. In general, this
21362 scheduling strategy is fully compatible with HP Ada
21363 although it provides some additional constraints (as
21364 fully documented in Annex D).
21365 GNAT implements time slicing control in a manner compatible with
21366 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
21367 are identical to the HP Ada 83 pragma of the same name.
21368 Note that it is not possible to mix GNAT tasking and
21369 HP Ada 83 tasking in the same program, since the two run-time
21370 libraries are not compatible.
21372 @node The Task Stack
21373 @subsection The Task Stack
21375 @noindent
21376 In HP Ada, a task stack is allocated each time a
21377 non-passive task is activated. As soon as the task is
21378 terminated, the storage for the task stack is deallocated.
21379 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
21380 a default stack size is used. Also, regardless of the size
21381 specified, some additional space is allocated for task
21382 management purposes. On OpenVMS Alpha systems, at least
21383 one page is allocated.
21385 GNAT handles task stacks in a similar manner. In accordance with
21386 the Ada 95 rules, it provides the pragma @code{STORAGE_SIZE} as
21387 an alternative method for controlling the task stack size.
21388 The specification of the attribute @code{T'STORAGE_SIZE} is also
21389 supported in a manner compatible with HP Ada.
21391 @node External Interrupts
21392 @subsection External Interrupts
21394 @noindent
21395 On HP Ada, external interrupts can be associated with task entries.
21396 GNAT is compatible with HP Ada in its handling of external interrupts.
21398 @node Pragmas and Pragma-Related Features
21399 @section Pragmas and Pragma-Related Features
21401 @noindent
21402 Both HP Ada and GNAT supply all language-defined pragmas
21403 as specified by the Ada 83 standard. GNAT also supplies all
21404 language-defined pragmas specified in the Ada 95 Reference Manual.
21405 In addition, GNAT implements the implementation-defined pragmas
21406 from HP Ada 83.
21408 @itemize @bullet
21409 @item  @code{AST_ENTRY}
21411 @item  @code{COMMON_OBJECT}
21413 @item  @code{COMPONENT_ALIGNMENT}
21415 @item  @code{EXPORT_EXCEPTION}
21417 @item  @code{EXPORT_FUNCTION}
21419 @item  @code{EXPORT_OBJECT}
21421 @item  @code{EXPORT_PROCEDURE}
21423 @item  @code{EXPORT_VALUED_PROCEDURE}
21425 @item  @code{FLOAT_REPRESENTATION}
21427 @item  @code{IDENT}
21429 @item  @code{IMPORT_EXCEPTION}
21431 @item  @code{IMPORT_FUNCTION}
21433 @item  @code{IMPORT_OBJECT}
21435 @item  @code{IMPORT_PROCEDURE}
21437 @item  @code{IMPORT_VALUED_PROCEDURE}
21439 @item  @code{INLINE_GENERIC}
21441 @item  @code{INTERFACE_NAME}
21443 @item  @code{LONG_FLOAT}
21445 @item  @code{MAIN_STORAGE}
21447 @item  @code{PASSIVE}
21449 @item  @code{PSET_OBJECT}
21451 @item  @code{SHARE_GENERIC}
21453 @item  @code{SUPPRESS_ALL}
21455 @item  @code{TASK_STORAGE}
21457 @item  @code{TIME_SLICE}
21459 @item  @code{TITLE}
21460 @end itemize
21462 @noindent
21463 These pragmas are all fully implemented, with the exception of @code{TITLE},
21464 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
21465 recognized, but which have no
21466 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
21467 use of protected objects in Ada 95. In GNAT, all generics are inlined.
21469 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
21470 a separate subprogram specification which must appear before the
21471 subprogram body.
21473 GNAT also supplies a number of implementation-defined pragmas as follows:
21474 @itemize @bullet
21475 @item  @code{ABORT_DEFER}
21477 @item  @code{ADA_83}
21479 @item  @code{ADA_95}
21481 @item  @code{ADA_05}
21483 @item  @code{ANNOTATE}
21485 @item  @code{ASSERT}
21487 @item  @code{C_PASS_BY_COPY}
21489 @item  @code{CPP_CLASS}
21491 @item  @code{CPP_CONSTRUCTOR}
21493 @item  @code{CPP_DESTRUCTOR}
21495 @item  @code{CPP_VIRTUAL}
21497 @item  @code{CPP_VTABLE}
21499 @item  @code{DEBUG}
21501 @item  @code{EXTEND_SYSTEM}
21503 @item  @code{LINKER_ALIAS}
21505 @item  @code{LINKER_SECTION}
21507 @item  @code{MACHINE_ATTRIBUTE}
21509 @item  @code{NO_RETURN}
21511 @item  @code{PURE_FUNCTION}
21513 @item  @code{SOURCE_FILE_NAME}
21515 @item  @code{SOURCE_REFERENCE}
21517 @item  @code{TASK_INFO}
21519 @item  @code{UNCHECKED_UNION}
21521 @item  @code{UNIMPLEMENTED_UNIT}
21523 @item  @code{UNIVERSAL_DATA}
21525 @item  @code{UNSUPPRESS}
21527 @item  @code{WARNINGS}
21529 @item  @code{WEAK_EXTERNAL}
21530 @end itemize
21532 @noindent
21533 For full details on these GNAT implementation-defined pragmas, see
21534 the GNAT Reference Manual.
21536 @menu
21537 * Restrictions on the Pragma INLINE::
21538 * Restrictions on the Pragma INTERFACE::
21539 * Restrictions on the Pragma SYSTEM_NAME::
21540 @end menu
21542 @node Restrictions on the Pragma INLINE
21543 @subsection Restrictions on Pragma @code{INLINE}
21545 @noindent
21546 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
21547 @itemize @bullet
21548 @item  Parameters cannot have a task type.
21550 @item  Function results cannot be task types, unconstrained
21551 array types, or unconstrained types with discriminants.
21553 @item  Bodies cannot declare the following:
21554 @itemize @bullet
21555 @item  Subprogram body or stub (imported subprogram is allowed)
21557 @item  Tasks
21559 @item  Generic declarations
21561 @item  Instantiations
21563 @item  Exceptions
21565 @item  Access types (types derived from access types allowed)
21567 @item  Array or record types
21569 @item  Dependent tasks
21571 @item  Direct recursive calls of subprogram or containing
21572 subprogram, directly or via a renaming
21574 @end itemize
21575 @end itemize
21577 @noindent
21578 In GNAT, the only restriction on pragma @code{INLINE} is that the
21579 body must occur before the call if both are in the same
21580 unit, and the size must be appropriately small. There are
21581 no other specific restrictions which cause subprograms to
21582 be incapable of being inlined.
21584 @node  Restrictions on the Pragma INTERFACE
21585 @subsection  Restrictions on Pragma @code{INTERFACE}
21587 @noindent
21588 The following restrictions on pragma @code{INTERFACE}
21589 are enforced by both HP Ada and GNAT:
21590 @itemize @bullet
21591 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
21592 Default is the default on OpenVMS Alpha systems.
21594 @item  Parameter passing: Language specifies default
21595 mechanisms but can be overridden with an @code{EXPORT} pragma.
21597 @itemize @bullet
21598 @item  Ada: Use internal Ada rules.
21600 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
21601 record or task type. Result cannot be a string, an
21602 array, or a record.
21604 @item  Fortran: Parameters cannot have a task type. Result cannot
21605 be a string, an array, or a record.
21606 @end itemize
21607 @end itemize
21609 @noindent
21610 GNAT is entirely upwards compatible with HP Ada, and in addition allows
21611 record parameters for all languages.
21613 @node  Restrictions on the Pragma SYSTEM_NAME
21614 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
21616 @noindent
21617 For HP Ada for OpenVMS Alpha, the enumeration literal
21618 for the type @code{NAME} is @code{OPENVMS_AXP}.
21619 In GNAT, the enumeration
21620 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
21622 @node  Library of Predefined Units
21623 @section  Library of Predefined Units
21625 @noindent
21626 A library of predefined units is provided as part of the
21627 HP Ada and GNAT implementations. HP Ada does not provide
21628 the package @code{MACHINE_CODE} but instead recommends importing
21629 assembler code.
21631 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
21632 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
21633 version.
21634 The HP Ada Predefined Library units are modified to remove Ada 95
21635 incompatibilities and to make them interoperable with GNAT
21636 (@pxref{Changes to DECLIB}, for details).
21637 The units are located in the @file{DECLIB} directory.
21640 The GNAT RTL is contained in
21641 the @file{ADALIB} directory, and
21642 the default search path is set up to find @code{DECLIB} units in preference
21643 to @code{ADALIB} units with the same name (@code{TEXT_IO},
21644 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
21647 @menu
21648 * Changes to DECLIB::
21649 @end menu
21651 @node Changes to DECLIB
21652 @subsection Changes to @code{DECLIB}
21654 @noindent
21655 The changes made to the HP Ada predefined library for GNAT and Ada 95
21656 compatibility are minor and include the following:
21658 @itemize @bullet
21659 @item  Adjusting the location of pragmas and record representation
21660 clauses to obey Ada 95 rules
21662 @item  Adding the proper notation to generic formal parameters
21663 that take unconstrained types in instantiation
21665 @item  Adding pragma @code{ELABORATE_BODY} to package specifications
21666 that have package bodies not otherwise allowed
21668 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
21669 ``@code{PROTECTD}''.
21670 Currently these are found only in the @code{STARLET} package spec.
21672 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
21673 where the address size is constrained to 32 bits.
21674 @end itemize
21676 @noindent
21677 None of the above changes is visible to users.
21679 @node Bindings
21680 @section Bindings
21682 @noindent
21683 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
21684 @itemize @bullet
21686 @item  Command Language Interpreter (CLI interface)
21688 @item  DECtalk Run-Time Library (DTK interface)
21690 @item  Librarian utility routines (LBR interface)
21692 @item  General Purpose Run-Time Library (LIB interface)
21694 @item  Math Run-Time Library (MTH interface)
21696 @item  National Character Set Run-Time Library (NCS interface)
21698 @item  Compiled Code Support Run-Time Library (OTS interface)
21700 @item  Parallel Processing Run-Time Library (PPL interface)
21702 @item  Screen Management Run-Time Library (SMG interface)
21704 @item  Sort Run-Time Library (SOR interface)
21706 @item  String Run-Time Library (STR interface)
21708 @item STARLET System Library
21709 @findex Starlet
21711 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21713 @item  X Windows Toolkit (XT interface)
21715 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21716 @end itemize
21718 @noindent
21719 GNAT provides implementations of these HP bindings in the @code{DECLIB}
21720 directory.
21722 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
21723 in the
21724 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21725 A pragma @code{Linker_Options} has been added to packages @code{Xm},
21726 @code{Xt}, and @code{X_Lib}
21727 causing the default X/Motif sharable image libraries to be linked in. This
21728 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21729 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21731 It may be necessary to edit these options files to update or correct the
21732 library names if, for example, the newer X/Motif bindings from
21733 @file{ADA$EXAMPLES}
21734 had been (previous to installing GNAT) copied and renamed to supersede the
21735 default @file{ADA$PREDEFINED} versions.
21737 @menu
21738 * Shared Libraries and Options Files::
21739 * Interfaces to C::
21740 @end menu
21742 @node Shared Libraries and Options Files
21743 @subsection Shared Libraries and Options Files
21745 @noindent
21746 When using the HP Ada
21747 predefined X and Motif bindings, the linking with their sharable images is
21748 done automatically by @command{GNAT LINK}.
21749 When using other X and Motif bindings, you need
21750 to add the corresponding sharable images to the command line for
21751 @code{GNAT LINK}. When linking with shared libraries, or with
21752 @file{.OPT} files, you must
21753 also add them to the command line for @command{GNAT LINK}.
21755 A shared library to be used with GNAT is built in the same way as other
21756 libraries under VMS. The VMS Link command can be used in standard fashion.
21758 @node Interfaces to C
21759 @subsection Interfaces to C
21761 @noindent
21762 HP Ada
21763 provides the following Ada types and operations:
21765 @itemize @bullet
21766 @item C types package (@code{C_TYPES})
21768 @item C strings (@code{C_TYPES.NULL_TERMINATED})
21770 @item Other_types (@code{SHORT_INT})
21771 @end itemize
21773 @noindent
21774 Interfacing to C with GNAT, you can use the above approach
21775 described for HP Ada or the facilities of Annex B of
21776 the Ada 95 Reference Manual (packages @code{INTERFACES.C},
21777 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
21778 information, see the section ``Interfacing to C'' in the
21779 @cite{GNAT Reference Manual}.
21781 The @option{-gnatF} qualifier forces default and explicit
21782 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
21783 to be uppercased for compatibility with the default behavior
21784 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
21786 @node Main Program Definition
21787 @section Main Program Definition
21789 @noindent
21790 The following section discusses differences in the
21791 definition of main programs on HP Ada and GNAT.
21792 On HP Ada, main programs are defined to meet the
21793 following conditions:
21794 @itemize @bullet
21795 @item  Procedure with no formal parameters (returns @code{0} upon
21796        normal completion)
21798 @item  Procedure with no formal parameters (returns @code{42} when
21799        an unhandled exception is raised)
21801 @item  Function with no formal parameters whose returned value
21802        is of a discrete type
21804 @item  Procedure with one @code{out} formal of a discrete type for
21805        which a specification of pragma @code{EXPORT_VALUED_PROCEDURE}
21806        is given.
21808 @end itemize
21810 @noindent
21811 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
21812 a main function or main procedure returns a discrete
21813 value whose size is less than 64 bits (32 on VAX systems),
21814 the value is zero- or sign-extended as appropriate.
21815 On GNAT, main programs are defined as follows:
21816 @itemize @bullet
21817 @item  Must be a non-generic, parameterless subprogram that
21818 is either a procedure or function returning an Ada
21819 @code{STANDARD.INTEGER} (the predefined type)
21821 @item  Cannot be a generic subprogram or an instantiation of a
21822 generic subprogram
21823 @end itemize
21825 @node Implementation-Defined Attributes
21826 @section Implementation-Defined Attributes
21828 @noindent
21829 GNAT provides all HP Ada implementation-defined
21830 attributes.
21832 @node Compiler and Run-Time Interfacing
21833 @section Compiler and Run-Time Interfacing
21835 @noindent
21836 HP Ada provides the following qualifiers to pass options to the linker
21837 (ACS LINK):
21838 @itemize @bullet
21839 @item  @option{/WAIT} and @option{/SUBMIT}
21841 @item  @option{/COMMAND}
21843 @item  @option{/[NO]MAP}
21845 @item  @option{/OUTPUT=@i{file-spec}}
21847 @item  @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
21848 @end itemize
21850 @noindent
21851 To pass options to the linker, GNAT provides the following
21852 switches:
21854 @itemize @bullet
21855 @item   @option{/EXECUTABLE=@i{exec-name}}
21857 @item   @option{/VERBOSE}
21859 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK}
21860 @end itemize
21862 @noindent
21863 For more information on these switches, see
21864 @ref{Switches for gnatlink}.
21865 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
21866 to control optimization. HP Ada also supplies the
21867 following pragmas:
21868 @itemize @bullet
21869 @item  @code{OPTIMIZE}
21871 @item  @code{INLINE}
21873 @item  @code{INLINE_GENERIC}
21875 @item  @code{SUPPRESS_ALL}
21877 @item  @code{PASSIVE}
21878 @end itemize
21880 @noindent
21881 In GNAT, optimization is controlled strictly by command
21882 line parameters, as described in the corresponding section of this guide.
21883 The HP pragmas for control of optimization are
21884 recognized but ignored.
21886 Note that in GNAT, the default is optimization off, whereas in HP Ada
21887 the default is that optimization is turned on.
21889 @node Program Compilation and Library Management
21890 @section Program Compilation and Library Management
21892 @noindent
21893 HP Ada and GNAT provide a comparable set of commands to
21894 build programs. HP Ada also provides a program library,
21895 which is a concept that does not exist on GNAT. Instead,
21896 GNAT provides directories of sources that are compiled as
21897 needed.
21899 The following table summarizes
21900 the HP Ada commands and provides
21901 equivalent GNAT commands. In this table, some GNAT
21902 equivalents reflect the fact that GNAT does not use the
21903 concept of a program library. Instead, it uses a model
21904 in which collections of source and object files are used
21905 in a manner consistent with other languages like C and
21906 Fortran. Therefore, standard system file commands are used
21907 to manipulate these elements. Those GNAT commands are marked with
21908 an asterisk.
21909 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
21911 @need 1500
21912 @multitable @columnfractions .35 .65
21914 @item @emph{HP Ada Command}
21915 @tab @emph{GNAT Equivalent / Description}
21917 @item @command{ADA}
21918 @tab @command{GNAT COMPILE}@*
21919 Invokes the compiler to compile one or more Ada source files.
21921 @item @command{ACS ATTACH}@*
21922 @tab [No equivalent]@*
21923 Switches control of terminal from current process running the program
21924 library manager.
21926 @item @command{ACS CHECK}
21927 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21928 Forms the execution closure of one
21929 or more compiled units and checks completeness and currency.
21931 @item @command{ACS COMPILE}
21932 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21933 Forms the execution closure of one or
21934 more specified units, checks completeness and currency,
21935 identifies units that have revised source files, compiles same,
21936 and recompiles units that are or will become obsolete.
21937 Also completes incomplete generic instantiations.
21939 @item @command{ACS COPY FOREIGN}
21940 @tab Copy (*)@*
21941 Copies a foreign object file into the program library as a
21942 library unit body.
21944 @item @command{ACS COPY UNIT}
21945 @tab Copy (*)@*
21946 Copies a compiled unit from one program library to another.
21948 @item @command{ACS CREATE LIBRARY}
21949 @tab Create /directory (*)@*
21950 Creates a program library.
21952 @item @command{ACS CREATE SUBLIBRARY}
21953 @tab Create /directory (*)@*
21954 Creates a program sublibrary.
21956 @item @command{ACS DELETE LIBRARY}
21957 @tab @*
21958 Deletes a program library and its contents.
21960 @item @command{ACS DELETE SUBLIBRARY}
21961 @tab @*
21962 Deletes a program sublibrary and its contents.
21964 @item @command{ACS DELETE UNIT}
21965 @tab Delete file (*)@*
21966 On OpenVMS systems, deletes one or more compiled units from
21967 the current program library.
21969 @item @command{ACS DIRECTORY}
21970 @tab Directory (*)@*
21971 On OpenVMS systems, lists units contained in the current
21972 program library.
21974 @item @command{ACS ENTER FOREIGN}
21975 @tab Copy (*)@*
21976 Allows the import of a foreign body as an Ada library
21977 specification and enters a reference to a pointer.
21979 @item @command{ACS ENTER UNIT}
21980 @tab Copy (*)@*
21981 Enters a reference (pointer) from the current program library to
21982 a unit compiled into another program library.
21984 @item @command{ACS EXIT}
21985 @tab [No equivalent]@*
21986 Exits from the program library manager.
21988 @item @command{ACS EXPORT}
21989 @tab Copy (*)@*
21990 Creates an object file that contains system-specific object code
21991 for one or more units. With GNAT, object files can simply be copied
21992 into the desired directory.
21994 @item @command{ACS EXTRACT SOURCE}
21995 @tab Copy (*)@*
21996 Allows access to the copied source file for each Ada compilation unit
21998 @item @command{ACS HELP}
21999 @tab @command{HELP GNAT}@*
22000 Provides online help.
22002 @item @command{ACS LINK}
22003 @tab @command{GNAT LINK}@*
22004 Links an object file containing Ada units into an executable file.
22006 @item @command{ACS LOAD}
22007 @tab Copy (*)@*
22008 Loads (partially compiles) Ada units into the program library.
22009 Allows loading a program from a collection of files into a library
22010 without knowing the relationship among units.
22012 @item @command{ACS MERGE}
22013 @tab Copy (*)@*
22014 Merges into the current program library, one or more units from
22015 another library where they were modified.
22017 @item @command{ACS RECOMPILE}
22018 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
22019 Recompiles from   external or copied source files any obsolete
22020 unit in the closure. Also, completes any incomplete generic
22021 instantiations.
22023 @item @command{ACS REENTER}
22024 @tab @command{GNAT MAKE}@*
22025 Reenters current references to units compiled after last entered
22026 with the @command{ACS ENTER UNIT} command.
22028 @item @command{ACS SET LIBRARY}
22029 @tab Set default (*)@*
22030 Defines a program library to be the compilation context as well
22031 as the target library for compiler output and commands in general.
22033 @item @command{ACS SET PRAGMA}
22034 @tab Edit @file{gnat.adc} (*)@*
22035 Redefines specified  values of the library characteristics
22036 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
22037 and @code{Float_Representation}.
22039 @item @command{ACS SET SOURCE}
22040 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
22041 Defines the source file search list for the @command{ACS COMPILE} command.
22043 @item @command{ACS SHOW LIBRARY}
22044 @tab Directory (*)@*
22045 Lists information about one or more program libraries.
22047 @item @command{ACS SHOW PROGRAM}
22048 @tab [No equivalent]@*
22049 Lists information about the execution closure of one or
22050 more units in the program library.
22052 @item @command{ACS SHOW SOURCE}
22053 @tab Show logical @code{ADA_INCLUDE_PATH}@*
22054 Shows the source file search used when compiling units.
22056 @item @command{ACS SHOW VERSION}
22057 @tab Compile with @option{VERBOSE} option
22058 Displays the version number of the compiler and program library
22059 manager used.
22061 @item @command{ACS SPAWN}
22062 @tab [No equivalent]@*
22063 Creates a subprocess of the current process (same as @command{DCL SPAWN}
22064 command).
22066 @item @command{ACS VERIFY}
22067 @tab [No equivalent]@*
22068 Performs a series of consistency checks on a program library to
22069 determine whether the library structure and library files are in
22070 valid form.
22071 @end multitable
22073 @noindent
22075 @node Input-Output
22076 @section Input-Output
22078 @noindent
22079 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
22080 Management Services (RMS) to perform operations on
22081 external files.
22083 @noindent
22084 HP Ada and GNAT predefine an identical set of input-
22085 output packages. To make the use of the
22086 generic @code{TEXT_IO} operations more convenient, HP Ada
22087 provides predefined library packages that instantiate the
22088 integer and floating-point operations for the predefined
22089 integer and floating-point types as shown in the following table.
22091 @multitable @columnfractions .45 .55
22092 @item @emph{Package Name} @tab Instantiation
22094 @item @code{INTEGER_TEXT_IO}
22095 @tab @code{INTEGER_IO(INTEGER)}
22097 @item @code{SHORT_INTEGER_TEXT_IO}
22098 @tab @code{INTEGER_IO(SHORT_INTEGER)}
22100 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
22101 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
22103 @item @code{FLOAT_TEXT_IO}
22104 @tab @code{FLOAT_IO(FLOAT)}
22106 @item @code{LONG_FLOAT_TEXT_IO}
22107 @tab @code{FLOAT_IO(LONG_FLOAT)}
22108 @end multitable
22110 @noindent
22111 The HP Ada predefined packages and their operations
22112 are implemented using OpenVMS Alpha files and input-output
22113 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
22114 Familiarity with the following is recommended:
22115 @itemize @bullet
22116 @item  RMS file organizations and access methods
22118 @item  OpenVMS file specifications and directories
22120 @item  OpenVMS File Definition Language (FDL)
22121 @end itemize
22123 @noindent
22124 GNAT provides I/O facilities that are completely
22125 compatible with HP Ada. The distribution includes the
22126 standard HP Ada versions of all I/O packages, operating
22127 in a manner compatible with HP Ada. In particular, the
22128 following packages are by default the HP Ada (Ada 83)
22129 versions of these packages rather than the renamings
22130 suggested in Annex J of the Ada 95 Reference Manual:
22131 @itemize @bullet
22132 @item  @code{TEXT_IO}
22134 @item  @code{SEQUENTIAL_IO}
22136 @item  @code{DIRECT_IO}
22137 @end itemize
22139 @noindent
22140 The use of the standard Ada 95 syntax for child packages (for
22141 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
22142 packages, as defined in the Ada 95 Reference Manual.
22143 GNAT provides HP-compatible predefined instantiations
22144 of the @code{TEXT_IO} packages, and also
22145 provides the standard predefined instantiations required
22146 by the Ada 95 Reference Manual.
22148 For further information on how GNAT interfaces to the file
22149 system or how I/O is implemented in programs written in
22150 mixed languages, see the chapter ``Implementation of the
22151 Standard I/O'' in the @cite{GNAT Reference Manual}.
22152 This chapter covers the following:
22153 @itemize @bullet
22154 @item  Standard I/O packages
22156 @item  @code{FORM} strings
22158 @item  @code{ADA.DIRECT_IO}
22160 @item  @code{ADA.SEQUENTIAL_IO}
22162 @item  @code{ADA.TEXT_IO}
22164 @item  Stream pointer positioning
22166 @item  Reading and writing non-regular files
22168 @item  @code{GET_IMMEDIATE}
22170 @item  Treating @code{TEXT_IO} files as streams
22172 @item  Shared files
22174 @item  Open modes
22175 @end itemize
22177 @node Implementation Limits
22178 @section Implementation Limits
22180 @noindent
22181 The following table lists implementation limits for HP Ada
22182 and GNAT systems.
22183 @multitable @columnfractions .60 .20 .20
22184 @sp 1
22185 @item  @emph{Compilation Parameter}
22186 @tab   @emph{HP Ada}
22187 @tab   @emph{GNAT}
22188 @sp 1
22190 @item  In a subprogram or entry  declaration, maximum number of
22191        formal parameters that are of an unconstrained record type
22192 @tab   32
22193 @tab   No set limit
22194 @sp 1
22196 @item  Maximum identifier length (number of characters)
22197 @tab   255
22198 @tab   255
22199 @sp 1
22201 @item  Maximum number of characters in a source line
22202 @tab   255
22203 @tab   255
22204 @sp 1
22206 @item  Maximum collection size   (number of bytes)
22207 @tab   2**31-1
22208 @tab   2**31-1
22209 @sp 1
22211 @item  Maximum number of discriminants for a record type
22212 @tab   245
22213 @tab   No set limit
22214 @sp 1
22216 @item  Maximum number of formal parameters in an entry or
22217        subprogram declaration
22218 @tab   246
22219 @tab    No set limit
22220 @sp 1
22222 @item  Maximum number of dimensions in an array type
22223 @tab   255
22224 @tab   No set limit
22225 @sp 1
22227 @item  Maximum number of library  units and subunits in a compilation.
22228 @tab   4095
22229 @tab   No set limit
22230 @sp 1
22232 @item  Maximum number of library units and subunits in an execution.
22233 @tab   16383
22234 @tab   No set limit
22235 @sp 1
22237 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
22238        or @code{PSECT_OBJECT}
22239 @tab   32757
22240 @tab   No set limit
22241 @sp 1
22243 @item  Maximum number of enumeration literals in an enumeration type
22244        definition
22245 @tab   65535
22246 @tab   No set limit
22247 @sp 1
22249 @item  Maximum number of lines in a source file
22250 @tab   65534
22251 @tab   No set limit
22252 @sp 1
22254 @item  Maximum number of bits in any object
22255 @tab   2**31-1
22256 @tab   2**31-1
22257 @sp 1
22259 @item  Maximum size of the static portion of a stack frame (approximate)
22260 @tab   2**31-1
22261 @tab   2**31-1
22262 @end multitable
22264 @node Tools and Utilities
22265 @section Tools and Utilities
22267 @noindent
22268 The following table lists some of the OpenVMS development tools
22269 available for HP Ada, and the corresponding tools for
22270 use with @value{EDITION} on Alpha and I64 platforms.
22271 Aside from the debugger, all the OpenVMS tools identified are part
22272 of the DECset package.
22275 @iftex
22276 @c Specify table in TeX since Texinfo does a poor job
22277 @tex
22278 \smallskip
22279 \smallskip
22280 \settabs\+Language-Sensitive Editor\quad
22281    &Product with HP Ada\quad
22282    &\cr
22283 \+\it Tool
22284    &\it Product with HP Ada
22285    & \it Product with GNAT Pro\cr
22286 \smallskip
22287 \+Code Management System
22288    &HP CMS
22289    & HP CMS\cr
22290 \smallskip
22291 \+Language-Sensitive Editor
22292    &HP LSE
22293    & emacs or HP LSE (Alpha)\cr
22295    &
22296    & HP LSE (I64)\cr
22297 \smallskip
22298 \+Debugger
22299    &OpenVMS Debug
22300    & gdb (Alpha),\cr
22302    &
22303    & OpenVMS Debug (I64)\cr
22304 \smallskip
22305 \+Source Code Analyzer /
22306    &HP SCA
22307    & GNAT XREF\cr
22308 \+Cross Referencer
22309    &
22310    &\cr
22311 \smallskip
22312 \+Test Manager
22313    &HP Digital Test
22314    & HP DTM\cr
22316    &Manager (DTM)
22317    &\cr
22318 \smallskip
22319 \+Performance and
22320    & HP PCA
22321    & HP PCA\cr
22322 \+Coverage Analyzer
22323    &
22324    &\cr
22325 \smallskip
22326 \+Module Management
22327    & HP MMS
22328    & Not applicable\cr
22329 \+ System
22330    &
22331    &\cr
22332 \smallskip
22333 \smallskip
22334 @end tex
22335 @end iftex
22337 @ifnottex
22338 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
22339 @c the TeX version above for the printed version
22340 @flushleft
22341 @c @multitable @columnfractions .3 .4 .4
22342 @multitable {Source Code Analyzer /}{Product with HP Ada}{Product with GNAT Pro}
22343 @item @i{Tool}
22344  @tab @i{Product with HP Ada}
22345  @tab @i{Product with @value{EDITION}}
22346 @item Code Management@*System
22347  @tab HP CMS
22348  @tab HP CMS
22349 @item Language-Sensitive@*Editor
22350  @tab HP LSE
22351  @tab emacs or HP LSE (Alpha)
22352 @item
22353  @tab
22354  @tab HP LSE (I64)
22355 @item Debugger
22356  @tab OpenVMS Debug
22357  @tab gdb (Alpha),
22358 @item
22359  @tab
22360  @tab OpenVMS Debug (I64)
22361 @item Source Code Analyzer /@*Cross Referencer
22362  @tab HP SCA
22363  @tab GNAT XREF
22364 @item Test Manager
22365  @tab HP Digital Test@*Manager (DTM)
22366  @tab HP DTM
22367 @item Performance and@*Coverage Analyzer
22368  @tab HP PCA
22369  @tab HP PCA
22370 @item Module Management@*System
22371  @tab HP MMS
22372  @tab Not applicable
22373 @end multitable
22374 @end flushleft
22375 @end ifnottex
22377 @end ifset
22380 @c **************************************
22381 @node Platform-Specific Information for the Run-Time Libraries
22382 @appendix Platform-Specific Information for the Run-Time Libraries
22383 @cindex Tasking and threads libraries
22384 @cindex Threads libraries and tasking
22385 @cindex Run-time libraries (platform-specific information)
22387 @noindent
22388 The GNAT run-time implementation may vary with respect to both the
22389 underlying threads library and the exception handling scheme.
22390 For threads support, one or more of the following are supplied:
22391 @itemize @bullet
22392 @item @b{native threads library}, a binding to the thread package from
22393 the underlying operating system
22395 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
22396 POSIX thread package
22397 @end itemize
22399 @noindent
22400 For exception handling, either or both of two models are supplied:
22401 @itemize @bullet
22402 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
22403 Most programs should experience a substantial speed improvement by
22404 being compiled with a ZCX run-time.
22405 This is especially true for
22406 tasking applications or applications with many exception handlers.}
22407 @cindex Zero-Cost Exceptions
22408 @cindex ZCX (Zero-Cost Exceptions)
22409 which uses binder-generated tables that
22410 are interrogated at run time to locate a handler
22412 @item @b{setjmp / longjmp} (``SJLJ''),
22413 @cindex setjmp/longjmp Exception Model
22414 @cindex SJLJ (setjmp/longjmp Exception Model)
22415 which uses dynamically-set data to establish
22416 the set of handlers
22417 @end itemize
22419 @noindent
22420 This appendix summarizes which combinations of threads and exception support
22421 are supplied on various GNAT platforms.
22422 It then shows how to select a particular library either
22423 permanently or temporarily,
22424 explains the properties of (and tradeoffs among) the various threads
22425 libraries, and provides some additional
22426 information about several specific platforms.
22428 @menu
22429 * Summary of Run-Time Configurations::
22430 * Specifying a Run-Time Library::
22431 * Choosing the Scheduling Policy::
22432 * Solaris-Specific Considerations::
22433 * Linux-Specific Considerations::
22434 * AIX-Specific Considerations::
22435 @end menu
22437 @node Summary of Run-Time Configurations
22438 @section Summary of Run-Time Configurations
22440 @multitable @columnfractions .30 .70
22441 @item @b{alpha-openvms}
22442 @item @code{@ @ }@i{rts-native (default)}
22443 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22444 @item @code{@ @ @ @ }Exceptions @tab ZCX
22446 @item @b{alpha-tru64}
22447 @item @code{@ @ }@i{rts-native (default)}
22448 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22449 @item @code{@ @ @ @ }Exceptions @tab ZCX
22451 @item @code{@ @ }@i{rts-sjlj}
22452 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
22453 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22455 @item @b{ia64-hp_linux}
22456 @item @code{@ @ }@i{rts-native (default)}
22457 @item @code{@ @ @ @ }Tasking    @tab pthread library
22458 @item @code{@ @ @ @ }Exceptions @tab ZCX
22460 @item @b{ia64-hpux}
22461 @item @code{@ @ }@i{rts-native (default)}
22462 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22463 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22465 @item @b{ia64-openvms}
22466 @item @code{@ @ }@i{rts-native (default)}
22467 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
22468 @item @code{@ @ @ @ }Exceptions @tab ZCX
22470 @item @b{ia64-sgi_linux}
22471 @item @code{@ @ }@i{rts-native (default)}
22472 @item @code{@ @ @ @ }Tasking    @tab pthread library
22473 @item @code{@ @ @ @ }Exceptions @tab ZCX
22475 @item @b{mips-irix}
22476 @item @code{@ @ }@i{rts-native (default)}
22477 @item @code{@ @ @ @ }Tasking    @tab native IRIX threads
22478 @item @code{@ @ @ @ }Exceptions @tab ZCX
22480 @item @b{pa-hpux}
22481 @item @code{@ @ }@i{rts-native (default)}
22482 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22483 @item @code{@ @ @ @ }Exceptions @tab ZCX
22485 @item @code{@ @ }@i{rts-sjlj}
22486 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
22487 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22489 @item @b{ppc-aix}
22490 @item @code{@ @ }@i{rts-native (default)}
22491 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
22492 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22494 @item @b{ppc-darwin}
22495 @item @code{@ @ }@i{rts-native (default)}
22496 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
22497 @item @code{@ @ @ @ }Exceptions @tab ZCX
22499 @item @b{sparc-solaris}  @tab
22500 @item @code{@ @ }@i{rts-native (default)}
22501 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22502 @item @code{@ @ @ @ }Exceptions @tab ZCX
22504 @item @code{@ @ }@i{rts-m64}
22505 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
22506 @item @code{@ @ @ @ }Exceptions  @tab ZCX
22507 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
22508 @item    @tab Use only on Solaris 8 or later.
22509 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
22511 @item @code{@ @ }@i{rts-pthread}
22512 @item @code{@ @ @ @ }Tasking    @tab pthread library
22513 @item @code{@ @ @ @ }Exceptions @tab ZCX
22515 @item @code{@ @ }@i{rts-sjlj}
22516 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
22517 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22519 @item @b{x86-linux}
22520 @item @code{@ @ }@i{rts-native (default)}
22521 @item @code{@ @ @ @ }Tasking    @tab pthread library
22522 @item @code{@ @ @ @ }Exceptions @tab ZCX
22524 @item @code{@ @ }@i{rts-sjlj}
22525 @item @code{@ @ @ @ }Tasking    @tab pthread library
22526 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22528 @item @b{x86-lynx}
22529 @item @code{@ @ }@i{rts-native (default)}
22530 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
22531 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22533 @item @b{x86-windows}
22534 @item @code{@ @ }@i{rts-native (default)}
22535 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22536 @item @code{@ @ @ @ }Exceptions @tab ZCX
22538 @item @code{@ @ }@i{rts-sjlj (default)}
22539 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
22540 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22542 @item @b{x86_64-linux}
22543 @item @code{@ @ }@i{rts-native (default)}
22544 @item @code{@ @ @ @ }Tasking    @tab pthread library
22545 @item @code{@ @ @ @ }Exceptions @tab ZCX
22547 @item @code{@ @ }@i{rts-sjlj}
22548 @item @code{@ @ @ @ }Tasking    @tab pthread library
22549 @item @code{@ @ @ @ }Exceptions @tab SJLJ
22551 @end multitable
22553 @node Specifying a Run-Time Library
22554 @section Specifying a Run-Time Library
22556 @noindent
22557 The @file{adainclude} subdirectory containing the sources of the GNAT
22558 run-time library, and the @file{adalib} subdirectory containing the
22559 @file{ALI} files and the static and/or shared GNAT library, are located
22560 in the gcc target-dependent area:
22562 @smallexample
22563 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
22564 @end smallexample
22566 @noindent
22567 As indicated above, on some platforms several run-time libraries are supplied.
22568 These libraries are installed in the target dependent area and
22569 contain a complete source and binary subdirectory. The detailed description
22570 below explains the differences between the different libraries in terms of
22571 their thread support.
22573 The default run-time library (when GNAT is installed) is @emph{rts-native}.
22574 This default run time is selected by the means of soft links.
22575 For example on x86-linux:
22577 @smallexample
22578 @group
22579  $(target-dir)
22580      |
22581      +--- adainclude----------+
22582      |                        |
22583      +--- adalib-----------+  |
22584      |                     |  |
22585      +--- rts-native       |  |
22586      |    |                |  |
22587      |    +--- adainclude <---+
22588      |    |                |
22589      |    +--- adalib <----+
22590      |
22591      +--- rts-sjlj
22592           |
22593           +--- adainclude
22594           |
22595           +--- adalib
22596 @end group
22597 @end smallexample
22599 @noindent
22600 If the @i{rts-sjlj} library is to be selected on a permanent basis,
22601 these soft links can be modified with the following commands:
22603 @smallexample
22604 $ cd $target
22605 $ rm -f adainclude adalib
22606 $ ln -s rts-sjlj/adainclude adainclude
22607 $ ln -s rts-sjlj/adalib adalib
22608 @end smallexample
22610 @noindent
22611 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
22612 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
22613 @file{$target/ada_object_path}.
22615 Selecting another run-time library temporarily can be
22616 achieved by the regular mechanism for GNAT object or source path selection:
22618 @itemize @bullet
22619 @item
22620 Set the environment variables:
22622 @smallexample
22623 $ ADA_INCLUDE_PATH=$target/rts-sjlj/adainclude:$ADA_INCLUDE_PATH
22624 $ ADA_OBJECTS_PATH=$target/rts-sjlj/adalib:$ADA_OBJECTS_PATH
22625 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
22626 @end smallexample
22628 @item
22629 Use @option{-aI$target/rts-sjlj/adainclude}
22630 and @option{-aO$target/rts-sjlj/adalib}
22631 on the @command{gnatmake} command line
22633 @item
22634 Use the switch @option{--RTS}; e.g., @option{--RTS=sjlj}
22635 @cindex @option{--RTS} option
22636 @end itemize
22638 @node Choosing the Scheduling Policy
22639 @section Choosing the Scheduling Policy
22641 @noindent
22642 When using a POSIX threads implementation, you have a choice of several
22643 scheduling policies: @code{SCHED_FIFO},
22644 @cindex @code{SCHED_FIFO} scheduling policy
22645 @code{SCHED_RR}
22646 @cindex @code{SCHED_RR} scheduling policy
22647 and @code{SCHED_OTHER}.
22648 @cindex @code{SCHED_OTHER} scheduling policy
22649 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22650 or @code{SCHED_RR} requires special (e.g., root) privileges.
22652 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22653 @code{SCHED_FIFO},
22654 @cindex @code{SCHED_FIFO} scheduling policy
22655 you can use one of the following:
22657 @itemize @bullet
22658 @item
22659 @code{pragma Time_Slice (0.0)}
22660 @cindex pragma Time_Slice
22661 @item
22662 the corresponding binder option @option{-T0}
22663 @cindex @option{-T0} option
22664 @item
22665 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22666 @cindex pragma Task_Dispatching_Policy
22667 @end itemize
22669 @noindent
22670 To specify @code{SCHED_RR},
22671 @cindex @code{SCHED_RR} scheduling policy
22672 you should use @code{pragma Time_Slice} with a
22673 value greater than @code{0.0}, or else use the corresponding @option{-T}
22674 binder option.
22676 @node Solaris-Specific Considerations
22677 @section Solaris-Specific Considerations
22678 @cindex Solaris Sparc threads libraries
22680 @noindent
22681 This section addresses some topics related to the various threads libraries
22682 on Sparc Solaris and then provides some information on building and
22683 debugging 64-bit applications.
22685 @menu
22686 * Solaris Threads Issues::
22687 * Building and Debugging 64-bit Applications::
22688 @end menu
22690 @node Solaris Threads Issues
22691 @subsection Solaris Threads Issues
22693 @noindent
22694 GNAT under Solaris comes with an alternate tasking run-time library
22695 based on POSIX threads --- @emph{rts-pthread}.
22696 @cindex rts-pthread threads library
22697 This run-time library has the advantage of being mostly shared across all
22698 POSIX-compliant thread implementations, and it also provides under
22699 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
22700 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
22701 and @code{PTHREAD_PRIO_PROTECT}
22702 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
22703 semantics that can be selected using the predefined pragma
22704 @code{Locking_Policy}
22705 @cindex pragma Locking_Policy (under rts-pthread)
22706 with respectively
22707 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
22708 @cindex @code{Inheritance_Locking} (under rts-pthread)
22709 @cindex @code{Ceiling_Locking} (under rts-pthread)
22711 As explained above, the native run-time library is based on the Solaris thread
22712 library (@code{libthread}) and is the default library.
22714 When the Solaris threads library is used (this is the default), programs
22715 compiled with GNAT can automatically take advantage of
22716 and can thus execute on multiple processors.
22717 The user can alternatively specify a processor on which the program should run
22718 to emulate a single-processor system. The multiprocessor / uniprocessor choice
22719 is made by
22720 setting the environment variable @code{GNAT_PROCESSOR}
22721 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
22722 to one of the following:
22724 @table @code
22725 @item -2
22726 Use the default configuration (run the program on all
22727          available processors) - this is the same as having
22728          @code{GNAT_PROCESSOR} unset
22730 @item -1
22731 Let the run-time implementation choose one processor and run the program on
22732          that processor
22734 @item 0 .. Last_Proc
22735 Run the program on the specified processor.
22736   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
22737 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
22738 @end table
22740 @node Building and Debugging 64-bit Applications
22741 @subsection Building and Debugging 64-bit Applications
22743 @noindent
22744 In a 64-bit application, all the sources involved must be compiled with the
22745 @option{-m64} command-line option, and a specific GNAT library (compiled with
22746 this option) is required.
22747 The easiest way to build a 64bit application is to add
22748 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
22750 To debug these applications, a special version of gdb called @command{gdb64}
22751 needs to be used.
22753 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
22754 amounts to:
22756 @smallexample
22757      $ gnatmake -m64 -g --RTS=m64 hello.adb
22758      $ gdb64 hello
22759 @end smallexample
22761 @node Linux-Specific Considerations
22762 @section Linux-Specific Considerations
22763 @cindex Linux threads libraries
22765 @noindent
22766 On GNU/Linux without NPTL support (usually system with GNU C Library
22767 older than 2.3), the signal model is not POSIX compliant, which means
22768 that to send a signal to the process, you need to send the signal to all
22769 threads, e.g. by using @code{killpg()}.
22771 @node AIX-Specific Considerations
22772 @section AIX-Specific Considerations
22773 @cindex AIX resolver library
22775 @noindent
22776 On AIX, the resolver library initializes some internal structure on
22777 the first call to @code{get*by*} functions, which are used to implement
22778 @code{GNAT.Sockets.Get_Host_By_Name} and
22779 @code{GNAT.Sockets.Get_Host_By_Addrss}.
22780 If such initialization occurs within an Ada task, and the stack size for
22781 the task is the default size, a stack overflow may occur.
22783 To avoid this overflow, the user should either ensure that the first call
22784 to @code{GNAT.Sockets.Get_Host_By_Name} or
22785 @code{GNAT.Sockets.Get_Host_By_Addrss}
22786 occurs in the environment task, or use @code{pragma Storage_Size} to
22787 specify a sufficiently large size for the stack of the task that contains
22788 this call.
22790 @c *******************************
22791 @node Example of Binder Output File
22792 @appendix Example of Binder Output File
22794 @noindent
22795 This Appendix displays the source code for @command{gnatbind}'s output
22796 file generated for a simple ``Hello World'' program.
22797 Comments have been added for clarification purposes.
22799 @smallexample @c adanocomment
22800 @iftex
22801 @leftskip=0cm
22802 @end iftex
22803 --  The package is called Ada_Main unless this name is actually used
22804 --  as a unit name in the partition, in which case some other unique
22805 --  name is used.
22807 with System;
22808 package ada_main is
22810    Elab_Final_Code : Integer;
22811    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22813    --  The main program saves the parameters (argument count,
22814    --  argument values, environment pointer) in global variables
22815    --  for later access by other units including
22816    --  Ada.Command_Line.
22818    gnat_argc : Integer;
22819    gnat_argv : System.Address;
22820    gnat_envp : System.Address;
22822    --  The actual variables are stored in a library routine. This
22823    --  is useful for some shared library situations, where there
22824    --  are problems if variables are not in the library.
22826    pragma Import (C, gnat_argc);
22827    pragma Import (C, gnat_argv);
22828    pragma Import (C, gnat_envp);
22830    --  The exit status is similarly an external location
22832    gnat_exit_status : Integer;
22833    pragma Import (C, gnat_exit_status);
22835    GNAT_Version : constant String :=
22836                     "GNAT Version: 3.15w (20010315)";
22837    pragma Export (C, GNAT_Version, "__gnat_version");
22839    --  This is the generated adafinal routine that performs
22840    --  finalization at the end of execution. In the case where
22841    --  Ada is the main program, this main program makes a call
22842    --  to adafinal at program termination.
22844    procedure adafinal;
22845    pragma Export (C, adafinal, "adafinal");
22847    --  This is the generated adainit routine that performs
22848    --  initialization at the start of execution. In the case
22849    --  where Ada is the main program, this main program makes
22850    --  a call to adainit at program startup.
22852    procedure adainit;
22853    pragma Export (C, adainit, "adainit");
22855    --  This routine is called at the start of execution. It is
22856    --  a dummy routine that is used by the debugger to breakpoint
22857    --  at the start of execution.
22859    procedure Break_Start;
22860    pragma Import (C, Break_Start, "__gnat_break_start");
22862    --  This is the actual generated main program (it would be
22863    --  suppressed if the no main program switch were used). As
22864    --  required by standard system conventions, this program has
22865    --  the external name main.
22867    function main
22868      (argc : Integer;
22869       argv : System.Address;
22870       envp : System.Address)
22871       return Integer;
22872    pragma Export (C, main, "main");
22874    --  The following set of constants give the version
22875    --  identification values for every unit in the bound
22876    --  partition. This identification is computed from all
22877    --  dependent semantic units, and corresponds to the
22878    --  string that would be returned by use of the
22879    --  Body_Version or Version attributes.
22881    type Version_32 is mod 2 ** 32;
22882    u00001 : constant Version_32 := 16#7880BEB3#;
22883    u00002 : constant Version_32 := 16#0D24CBD0#;
22884    u00003 : constant Version_32 := 16#3283DBEB#;
22885    u00004 : constant Version_32 := 16#2359F9ED#;
22886    u00005 : constant Version_32 := 16#664FB847#;
22887    u00006 : constant Version_32 := 16#68E803DF#;
22888    u00007 : constant Version_32 := 16#5572E604#;
22889    u00008 : constant Version_32 := 16#46B173D8#;
22890    u00009 : constant Version_32 := 16#156A40CF#;
22891    u00010 : constant Version_32 := 16#033DABE0#;
22892    u00011 : constant Version_32 := 16#6AB38FEA#;
22893    u00012 : constant Version_32 := 16#22B6217D#;
22894    u00013 : constant Version_32 := 16#68A22947#;
22895    u00014 : constant Version_32 := 16#18CC4A56#;
22896    u00015 : constant Version_32 := 16#08258E1B#;
22897    u00016 : constant Version_32 := 16#367D5222#;
22898    u00017 : constant Version_32 := 16#20C9ECA4#;
22899    u00018 : constant Version_32 := 16#50D32CB6#;
22900    u00019 : constant Version_32 := 16#39A8BB77#;
22901    u00020 : constant Version_32 := 16#5CF8FA2B#;
22902    u00021 : constant Version_32 := 16#2F1EB794#;
22903    u00022 : constant Version_32 := 16#31AB6444#;
22904    u00023 : constant Version_32 := 16#1574B6E9#;
22905    u00024 : constant Version_32 := 16#5109C189#;
22906    u00025 : constant Version_32 := 16#56D770CD#;
22907    u00026 : constant Version_32 := 16#02F9DE3D#;
22908    u00027 : constant Version_32 := 16#08AB6B2C#;
22909    u00028 : constant Version_32 := 16#3FA37670#;
22910    u00029 : constant Version_32 := 16#476457A0#;
22911    u00030 : constant Version_32 := 16#731E1B6E#;
22912    u00031 : constant Version_32 := 16#23C2E789#;
22913    u00032 : constant Version_32 := 16#0F1BD6A1#;
22914    u00033 : constant Version_32 := 16#7C25DE96#;
22915    u00034 : constant Version_32 := 16#39ADFFA2#;
22916    u00035 : constant Version_32 := 16#571DE3E7#;
22917    u00036 : constant Version_32 := 16#5EB646AB#;
22918    u00037 : constant Version_32 := 16#4249379B#;
22919    u00038 : constant Version_32 := 16#0357E00A#;
22920    u00039 : constant Version_32 := 16#3784FB72#;
22921    u00040 : constant Version_32 := 16#2E723019#;
22922    u00041 : constant Version_32 := 16#623358EA#;
22923    u00042 : constant Version_32 := 16#107F9465#;
22924    u00043 : constant Version_32 := 16#6843F68A#;
22925    u00044 : constant Version_32 := 16#63305874#;
22926    u00045 : constant Version_32 := 16#31E56CE1#;
22927    u00046 : constant Version_32 := 16#02917970#;
22928    u00047 : constant Version_32 := 16#6CCBA70E#;
22929    u00048 : constant Version_32 := 16#41CD4204#;
22930    u00049 : constant Version_32 := 16#572E3F58#;
22931    u00050 : constant Version_32 := 16#20729FF5#;
22932    u00051 : constant Version_32 := 16#1D4F93E8#;
22933    u00052 : constant Version_32 := 16#30B2EC3D#;
22934    u00053 : constant Version_32 := 16#34054F96#;
22935    u00054 : constant Version_32 := 16#5A199860#;
22936    u00055 : constant Version_32 := 16#0E7F912B#;
22937    u00056 : constant Version_32 := 16#5760634A#;
22938    u00057 : constant Version_32 := 16#5D851835#;
22940    --  The following Export pragmas export the version numbers
22941    --  with symbolic names ending in B (for body) or S
22942    --  (for spec) so that they can be located in a link. The
22943    --  information provided here is sufficient to track down
22944    --  the exact versions of units used in a given build.
22946    pragma Export (C, u00001, "helloB");
22947    pragma Export (C, u00002, "system__standard_libraryB");
22948    pragma Export (C, u00003, "system__standard_libraryS");
22949    pragma Export (C, u00004, "adaS");
22950    pragma Export (C, u00005, "ada__text_ioB");
22951    pragma Export (C, u00006, "ada__text_ioS");
22952    pragma Export (C, u00007, "ada__exceptionsB");
22953    pragma Export (C, u00008, "ada__exceptionsS");
22954    pragma Export (C, u00009, "gnatS");
22955    pragma Export (C, u00010, "gnat__heap_sort_aB");
22956    pragma Export (C, u00011, "gnat__heap_sort_aS");
22957    pragma Export (C, u00012, "systemS");
22958    pragma Export (C, u00013, "system__exception_tableB");
22959    pragma Export (C, u00014, "system__exception_tableS");
22960    pragma Export (C, u00015, "gnat__htableB");
22961    pragma Export (C, u00016, "gnat__htableS");
22962    pragma Export (C, u00017, "system__exceptionsS");
22963    pragma Export (C, u00018, "system__machine_state_operationsB");
22964    pragma Export (C, u00019, "system__machine_state_operationsS");
22965    pragma Export (C, u00020, "system__machine_codeS");
22966    pragma Export (C, u00021, "system__storage_elementsB");
22967    pragma Export (C, u00022, "system__storage_elementsS");
22968    pragma Export (C, u00023, "system__secondary_stackB");
22969    pragma Export (C, u00024, "system__secondary_stackS");
22970    pragma Export (C, u00025, "system__parametersB");
22971    pragma Export (C, u00026, "system__parametersS");
22972    pragma Export (C, u00027, "system__soft_linksB");
22973    pragma Export (C, u00028, "system__soft_linksS");
22974    pragma Export (C, u00029, "system__stack_checkingB");
22975    pragma Export (C, u00030, "system__stack_checkingS");
22976    pragma Export (C, u00031, "system__tracebackB");
22977    pragma Export (C, u00032, "system__tracebackS");
22978    pragma Export (C, u00033, "ada__streamsS");
22979    pragma Export (C, u00034, "ada__tagsB");
22980    pragma Export (C, u00035, "ada__tagsS");
22981    pragma Export (C, u00036, "system__string_opsB");
22982    pragma Export (C, u00037, "system__string_opsS");
22983    pragma Export (C, u00038, "interfacesS");
22984    pragma Export (C, u00039, "interfaces__c_streamsB");
22985    pragma Export (C, u00040, "interfaces__c_streamsS");
22986    pragma Export (C, u00041, "system__file_ioB");
22987    pragma Export (C, u00042, "system__file_ioS");
22988    pragma Export (C, u00043, "ada__finalizationB");
22989    pragma Export (C, u00044, "ada__finalizationS");
22990    pragma Export (C, u00045, "system__finalization_rootB");
22991    pragma Export (C, u00046, "system__finalization_rootS");
22992    pragma Export (C, u00047, "system__finalization_implementationB");
22993    pragma Export (C, u00048, "system__finalization_implementationS");
22994    pragma Export (C, u00049, "system__string_ops_concat_3B");
22995    pragma Export (C, u00050, "system__string_ops_concat_3S");
22996    pragma Export (C, u00051, "system__stream_attributesB");
22997    pragma Export (C, u00052, "system__stream_attributesS");
22998    pragma Export (C, u00053, "ada__io_exceptionsS");
22999    pragma Export (C, u00054, "system__unsigned_typesS");
23000    pragma Export (C, u00055, "system__file_control_blockS");
23001    pragma Export (C, u00056, "ada__finalization__list_controllerB");
23002    pragma Export (C, u00057, "ada__finalization__list_controllerS");
23004    -- BEGIN ELABORATION ORDER
23005    -- ada (spec)
23006    -- gnat (spec)
23007    -- gnat.heap_sort_a (spec)
23008    -- gnat.heap_sort_a (body)
23009    -- gnat.htable (spec)
23010    -- gnat.htable (body)
23011    -- interfaces (spec)
23012    -- system (spec)
23013    -- system.machine_code (spec)
23014    -- system.parameters (spec)
23015    -- system.parameters (body)
23016    -- interfaces.c_streams (spec)
23017    -- interfaces.c_streams (body)
23018    -- system.standard_library (spec)
23019    -- ada.exceptions (spec)
23020    -- system.exception_table (spec)
23021    -- system.exception_table (body)
23022    -- ada.io_exceptions (spec)
23023    -- system.exceptions (spec)
23024    -- system.storage_elements (spec)
23025    -- system.storage_elements (body)
23026    -- system.machine_state_operations (spec)
23027    -- system.machine_state_operations (body)
23028    -- system.secondary_stack (spec)
23029    -- system.stack_checking (spec)
23030    -- system.soft_links (spec)
23031    -- system.soft_links (body)
23032    -- system.stack_checking (body)
23033    -- system.secondary_stack (body)
23034    -- system.standard_library (body)
23035    -- system.string_ops (spec)
23036    -- system.string_ops (body)
23037    -- ada.tags (spec)
23038    -- ada.tags (body)
23039    -- ada.streams (spec)
23040    -- system.finalization_root (spec)
23041    -- system.finalization_root (body)
23042    -- system.string_ops_concat_3 (spec)
23043    -- system.string_ops_concat_3 (body)
23044    -- system.traceback (spec)
23045    -- system.traceback (body)
23046    -- ada.exceptions (body)
23047    -- system.unsigned_types (spec)
23048    -- system.stream_attributes (spec)
23049    -- system.stream_attributes (body)
23050    -- system.finalization_implementation (spec)
23051    -- system.finalization_implementation (body)
23052    -- ada.finalization (spec)
23053    -- ada.finalization (body)
23054    -- ada.finalization.list_controller (spec)
23055    -- ada.finalization.list_controller (body)
23056    -- system.file_control_block (spec)
23057    -- system.file_io (spec)
23058    -- system.file_io (body)
23059    -- ada.text_io (spec)
23060    -- ada.text_io (body)
23061    -- hello (body)
23062    -- END ELABORATION ORDER
23064 end ada_main;
23066 --  The following source file name pragmas allow the generated file
23067 --  names to be unique for different main programs. They are needed
23068 --  since the package name will always be Ada_Main.
23070 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
23071 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
23073 --  Generated package body for Ada_Main starts here
23075 package body ada_main is
23077    --  The actual finalization is performed by calling the
23078    --  library routine in System.Standard_Library.Adafinal
23080    procedure Do_Finalize;
23081    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
23083    -------------
23084    -- adainit --
23085    -------------
23087 @findex adainit
23088    procedure adainit is
23090       --  These booleans are set to True once the associated unit has
23091       --  been elaborated. It is also used to avoid elaborating the
23092       --  same unit twice.
23094       E040 : Boolean;
23095       pragma Import (Ada, E040, "interfaces__c_streams_E");
23097       E008 : Boolean;
23098       pragma Import (Ada, E008, "ada__exceptions_E");
23100       E014 : Boolean;
23101       pragma Import (Ada, E014, "system__exception_table_E");
23103       E053 : Boolean;
23104       pragma Import (Ada, E053, "ada__io_exceptions_E");
23106       E017 : Boolean;
23107       pragma Import (Ada, E017, "system__exceptions_E");
23109       E024 : Boolean;
23110       pragma Import (Ada, E024, "system__secondary_stack_E");
23112       E030 : Boolean;
23113       pragma Import (Ada, E030, "system__stack_checking_E");
23115       E028 : Boolean;
23116       pragma Import (Ada, E028, "system__soft_links_E");
23118       E035 : Boolean;
23119       pragma Import (Ada, E035, "ada__tags_E");
23121       E033 : Boolean;
23122       pragma Import (Ada, E033, "ada__streams_E");
23124       E046 : Boolean;
23125       pragma Import (Ada, E046, "system__finalization_root_E");
23127       E048 : Boolean;
23128       pragma Import (Ada, E048, "system__finalization_implementation_E");
23130       E044 : Boolean;
23131       pragma Import (Ada, E044, "ada__finalization_E");
23133       E057 : Boolean;
23134       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
23136       E055 : Boolean;
23137       pragma Import (Ada, E055, "system__file_control_block_E");
23139       E042 : Boolean;
23140       pragma Import (Ada, E042, "system__file_io_E");
23142       E006 : Boolean;
23143       pragma Import (Ada, E006, "ada__text_io_E");
23145       --  Set_Globals is a library routine that stores away the
23146       --  value of the indicated set of global values in global
23147       --  variables within the library.
23149       procedure Set_Globals
23150         (Main_Priority            : Integer;
23151          Time_Slice_Value         : Integer;
23152          WC_Encoding              : Character;
23153          Locking_Policy           : Character;
23154          Queuing_Policy           : Character;
23155          Task_Dispatching_Policy  : Character;
23156          Adafinal                 : System.Address;
23157          Unreserve_All_Interrupts : Integer;
23158          Exception_Tracebacks     : Integer);
23159 @findex __gnat_set_globals
23160       pragma Import (C, Set_Globals, "__gnat_set_globals");
23162       --  SDP_Table_Build is a library routine used to build the
23163       --  exception tables. See unit Ada.Exceptions in files
23164       --  a-except.ads/adb for full details of how zero cost
23165       --  exception handling works. This procedure, the call to
23166       --  it, and the two following tables are all omitted if the
23167       --  build is in longjmp/setjump exception mode.
23169 @findex SDP_Table_Build
23170 @findex Zero Cost Exceptions
23171       procedure SDP_Table_Build
23172         (SDP_Addresses   : System.Address;
23173          SDP_Count       : Natural;
23174          Elab_Addresses  : System.Address;
23175          Elab_Addr_Count : Natural);
23176       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
23178       --  Table of Unit_Exception_Table addresses. Used for zero
23179       --  cost exception handling to build the top level table.
23181       ST : aliased constant array (1 .. 23) of System.Address := (
23182         Hello'UET_Address,
23183         Ada.Text_Io'UET_Address,
23184         Ada.Exceptions'UET_Address,
23185         Gnat.Heap_Sort_A'UET_Address,
23186         System.Exception_Table'UET_Address,
23187         System.Machine_State_Operations'UET_Address,
23188         System.Secondary_Stack'UET_Address,
23189         System.Parameters'UET_Address,
23190         System.Soft_Links'UET_Address,
23191         System.Stack_Checking'UET_Address,
23192         System.Traceback'UET_Address,
23193         Ada.Streams'UET_Address,
23194         Ada.Tags'UET_Address,
23195         System.String_Ops'UET_Address,
23196         Interfaces.C_Streams'UET_Address,
23197         System.File_Io'UET_Address,
23198         Ada.Finalization'UET_Address,
23199         System.Finalization_Root'UET_Address,
23200         System.Finalization_Implementation'UET_Address,
23201         System.String_Ops_Concat_3'UET_Address,
23202         System.Stream_Attributes'UET_Address,
23203         System.File_Control_Block'UET_Address,
23204         Ada.Finalization.List_Controller'UET_Address);
23206       --  Table of addresses of elaboration routines. Used for
23207       --  zero cost exception handling to make sure these
23208       --  addresses are included in the top level procedure
23209       --  address table.
23211       EA : aliased constant array (1 .. 23) of System.Address := (
23212         adainit'Code_Address,
23213         Do_Finalize'Code_Address,
23214         Ada.Exceptions'Elab_Spec'Address,
23215         System.Exceptions'Elab_Spec'Address,
23216         Interfaces.C_Streams'Elab_Spec'Address,
23217         System.Exception_Table'Elab_Body'Address,
23218         Ada.Io_Exceptions'Elab_Spec'Address,
23219         System.Stack_Checking'Elab_Spec'Address,
23220         System.Soft_Links'Elab_Body'Address,
23221         System.Secondary_Stack'Elab_Body'Address,
23222         Ada.Tags'Elab_Spec'Address,
23223         Ada.Tags'Elab_Body'Address,
23224         Ada.Streams'Elab_Spec'Address,
23225         System.Finalization_Root'Elab_Spec'Address,
23226         Ada.Exceptions'Elab_Body'Address,
23227         System.Finalization_Implementation'Elab_Spec'Address,
23228         System.Finalization_Implementation'Elab_Body'Address,
23229         Ada.Finalization'Elab_Spec'Address,
23230         Ada.Finalization.List_Controller'Elab_Spec'Address,
23231         System.File_Control_Block'Elab_Spec'Address,
23232         System.File_Io'Elab_Body'Address,
23233         Ada.Text_Io'Elab_Spec'Address,
23234         Ada.Text_Io'Elab_Body'Address);
23236    --  Start of processing for adainit
23238    begin
23240       --  Call SDP_Table_Build to build the top level procedure
23241       --  table for zero cost exception handling (omitted in
23242       --  longjmp/setjump mode).
23244       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
23246       --  Call Set_Globals to record various information for
23247       --  this partition.  The values are derived by the binder
23248       --  from information stored in the ali files by the compiler.
23250 @findex __gnat_set_globals
23251       Set_Globals
23252         (Main_Priority            => -1,
23253          --  Priority of main program, -1 if no pragma Priority used
23255          Time_Slice_Value         => -1,
23256          --  Time slice from Time_Slice pragma, -1 if none used
23258          WC_Encoding              => 'b',
23259          --  Wide_Character encoding used, default is brackets
23261          Locking_Policy           => ' ',
23262          --  Locking_Policy used, default of space means not
23263          --  specified, otherwise it is the first character of
23264          --  the policy name.
23266          Queuing_Policy           => ' ',
23267          --  Queuing_Policy used, default of space means not
23268          --  specified, otherwise it is the first character of
23269          --  the policy name.
23271          Task_Dispatching_Policy  => ' ',
23272          --  Task_Dispatching_Policy used, default of space means
23273          --  not specified, otherwise first character of the
23274          --  policy name.
23276          Adafinal                 => System.Null_Address,
23277          --  Address of Adafinal routine, not used anymore
23279          Unreserve_All_Interrupts => 0,
23280          --  Set true if pragma Unreserve_All_Interrupts was used
23282          Exception_Tracebacks     => 0);
23283          --  Indicates if exception tracebacks are enabled
23285       Elab_Final_Code := 1;
23287       --  Now we have the elaboration calls for all units in the partition.
23288       --  The Elab_Spec and Elab_Body attributes generate references to the
23289       --  implicit elaboration procedures generated by the compiler for
23290       --  each unit that requires elaboration.
23292       if not E040 then
23293          Interfaces.C_Streams'Elab_Spec;
23294       end if;
23295       E040 := True;
23296       if not E008 then
23297          Ada.Exceptions'Elab_Spec;
23298       end if;
23299       if not E014 then
23300          System.Exception_Table'Elab_Body;
23301          E014 := True;
23302       end if;
23303       if not E053 then
23304          Ada.Io_Exceptions'Elab_Spec;
23305          E053 := True;
23306       end if;
23307       if not E017 then
23308          System.Exceptions'Elab_Spec;
23309          E017 := True;
23310       end if;
23311       if not E030 then
23312          System.Stack_Checking'Elab_Spec;
23313       end if;
23314       if not E028 then
23315          System.Soft_Links'Elab_Body;
23316          E028 := True;
23317       end if;
23318       E030 := True;
23319       if not E024 then
23320          System.Secondary_Stack'Elab_Body;
23321          E024 := True;
23322       end if;
23323       if not E035 then
23324          Ada.Tags'Elab_Spec;
23325       end if;
23326       if not E035 then
23327          Ada.Tags'Elab_Body;
23328          E035 := True;
23329       end if;
23330       if not E033 then
23331          Ada.Streams'Elab_Spec;
23332          E033 := True;
23333       end if;
23334       if not E046 then
23335          System.Finalization_Root'Elab_Spec;
23336       end if;
23337       E046 := True;
23338       if not E008 then
23339          Ada.Exceptions'Elab_Body;
23340          E008 := True;
23341       end if;
23342       if not E048 then
23343          System.Finalization_Implementation'Elab_Spec;
23344       end if;
23345       if not E048 then
23346          System.Finalization_Implementation'Elab_Body;
23347          E048 := True;
23348       end if;
23349       if not E044 then
23350          Ada.Finalization'Elab_Spec;
23351       end if;
23352       E044 := True;
23353       if not E057 then
23354          Ada.Finalization.List_Controller'Elab_Spec;
23355       end if;
23356       E057 := True;
23357       if not E055 then
23358          System.File_Control_Block'Elab_Spec;
23359          E055 := True;
23360       end if;
23361       if not E042 then
23362          System.File_Io'Elab_Body;
23363          E042 := True;
23364       end if;
23365       if not E006 then
23366          Ada.Text_Io'Elab_Spec;
23367       end if;
23368       if not E006 then
23369          Ada.Text_Io'Elab_Body;
23370          E006 := True;
23371       end if;
23373       Elab_Final_Code := 0;
23374    end adainit;
23376    --------------
23377    -- adafinal --
23378    --------------
23380 @findex adafinal
23381    procedure adafinal is
23382    begin
23383       Do_Finalize;
23384    end adafinal;
23386    ----------
23387    -- main --
23388    ----------
23390    --  main is actually a function, as in the ANSI C standard,
23391    --  defined to return the exit status. The three parameters
23392    --  are the argument count, argument values and environment
23393    --  pointer.
23395 @findex Main Program
23396    function main
23397      (argc : Integer;
23398       argv : System.Address;
23399       envp : System.Address)
23400       return Integer
23401    is
23402       --  The initialize routine performs low level system
23403       --  initialization using a standard library routine which
23404       --  sets up signal handling and performs any other
23405       --  required setup. The routine can be found in file
23406       --  a-init.c.
23408 @findex __gnat_initialize
23409       procedure initialize;
23410       pragma Import (C, initialize, "__gnat_initialize");
23412       --  The finalize routine performs low level system
23413       --  finalization using a standard library routine. The
23414       --  routine is found in file a-final.c and in the standard
23415       --  distribution is a dummy routine that does nothing, so
23416       --  really this is a hook for special user finalization.
23418 @findex __gnat_finalize
23419       procedure finalize;
23420       pragma Import (C, finalize, "__gnat_finalize");
23422       --  We get to the main program of the partition by using
23423       --  pragma Import because if we try to with the unit and
23424       --  call it Ada style, then not only do we waste time
23425       --  recompiling it, but also, we don't really know the right
23426       --  switches (e.g. identifier character set) to be used
23427       --  to compile it.
23429       procedure Ada_Main_Program;
23430       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
23432    --  Start of processing for main
23434    begin
23435       --  Save global variables
23437       gnat_argc := argc;
23438       gnat_argv := argv;
23439       gnat_envp := envp;
23441       --  Call low level system initialization
23443       Initialize;
23445       --  Call our generated Ada initialization routine
23447       adainit;
23449       --  This is the point at which we want the debugger to get
23450       --  control
23452       Break_Start;
23454       --  Now we call the main program of the partition
23456       Ada_Main_Program;
23458       --  Perform Ada finalization
23460       adafinal;
23462       --  Perform low level system finalization
23464       Finalize;
23466       --  Return the proper exit status
23467       return (gnat_exit_status);
23468    end;
23470 --  This section is entirely comments, so it has no effect on the
23471 --  compilation of the Ada_Main package. It provides the list of
23472 --  object files and linker options, as well as some standard
23473 --  libraries needed for the link. The gnatlink utility parses
23474 --  this b~hello.adb file to read these comment lines to generate
23475 --  the appropriate command line arguments for the call to the
23476 --  system linker. The BEGIN/END lines are used for sentinels for
23477 --  this parsing operation.
23479 --  The exact file names will of course depend on the environment,
23480 --  host/target and location of files on the host system.
23482 @findex Object file list
23483 -- BEGIN Object file/option list
23484    --   ./hello.o
23485    --   -L./
23486    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
23487    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
23488 -- END Object file/option list
23490 end ada_main;
23491 @end smallexample
23493 @noindent
23494 The Ada code in the above example is exactly what is generated by the
23495 binder. We have added comments to more clearly indicate the function
23496 of each part of the generated @code{Ada_Main} package.
23498 The code is standard Ada in all respects, and can be processed by any
23499 tools that handle Ada. In particular, it is possible to use the debugger
23500 in Ada mode to debug the generated @code{Ada_Main} package. For example,
23501 suppose that for reasons that you do not understand, your program is crashing
23502 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
23503 you can place a breakpoint on the call:
23505 @smallexample @c ada
23506 Ada.Text_Io'Elab_Body;
23507 @end smallexample
23509 @noindent
23510 and trace the elaboration routine for this package to find out where
23511 the problem might be (more usually of course you would be debugging
23512 elaboration code in your own application).
23514 @node Elaboration Order Handling in GNAT
23515 @appendix Elaboration Order Handling in GNAT
23516 @cindex Order of elaboration
23517 @cindex Elaboration control
23519 @menu
23520 * Elaboration Code in Ada 95::
23521 * Checking the Elaboration Order in Ada 95::
23522 * Controlling the Elaboration Order in Ada 95::
23523 * Controlling Elaboration in GNAT - Internal Calls::
23524 * Controlling Elaboration in GNAT - External Calls::
23525 * Default Behavior in GNAT - Ensuring Safety::
23526 * Treatment of Pragma Elaborate::
23527 * Elaboration Issues for Library Tasks::
23528 * Mixing Elaboration Models::
23529 * What to Do If the Default Elaboration Behavior Fails::
23530 * Elaboration for Access-to-Subprogram Values::
23531 * Summary of Procedures for Elaboration Control::
23532 * Other Elaboration Order Considerations::
23533 @end menu
23535 @noindent
23536 This chapter describes the handling of elaboration code in Ada 95 and
23537 in GNAT, and discusses how the order of elaboration of program units can
23538 be controlled in GNAT, either automatically or with explicit programming
23539 features.
23541 @node Elaboration Code in Ada 95
23542 @section Elaboration Code in Ada 95
23544 @noindent
23545 Ada 95 provides rather general mechanisms for executing code at elaboration
23546 time, that is to say before the main program starts executing. Such code arises
23547 in three contexts:
23549 @table @asis
23550 @item Initializers for variables.
23551 Variables declared at the library level, in package specs or bodies, can
23552 require initialization that is performed at elaboration time, as in:
23553 @smallexample @c ada
23554 @cartouche
23555 Sqrt_Half : Float := Sqrt (0.5);
23556 @end cartouche
23557 @end smallexample
23559 @item Package initialization code
23560 Code in a @code{BEGIN-END} section at the outer level of a package body is
23561 executed as part of the package body elaboration code.
23563 @item Library level task allocators
23564 Tasks that are declared using task allocators at the library level
23565 start executing immediately and hence can execute at elaboration time.
23566 @end table
23568 @noindent
23569 Subprogram calls are possible in any of these contexts, which means that
23570 any arbitrary part of the program may be executed as part of the elaboration
23571 code. It is even possible to write a program which does all its work at
23572 elaboration time, with a null main program, although stylistically this
23573 would usually be considered an inappropriate way to structure
23574 a program.
23576 An important concern arises in the context of elaboration code:
23577 we have to be sure that it is executed in an appropriate order. What we
23578 have is a series of elaboration code sections, potentially one section
23579 for each unit in the program. It is important that these execute
23580 in the correct order. Correctness here means that, taking the above
23581 example of the declaration of @code{Sqrt_Half},
23582 if some other piece of
23583 elaboration code references @code{Sqrt_Half},
23584 then it must run after the
23585 section of elaboration code that contains the declaration of
23586 @code{Sqrt_Half}.
23588 There would never be any order of elaboration problem if we made a rule
23589 that whenever you @code{with} a unit, you must elaborate both the spec and body
23590 of that unit before elaborating the unit doing the @code{with}'ing:
23592 @smallexample @c ada
23593 @group
23594 @cartouche
23595 with Unit_1;
23596 package Unit_2 is ...
23597 @end cartouche
23598 @end group
23599 @end smallexample
23601 @noindent
23602 would require that both the body and spec of @code{Unit_1} be elaborated
23603 before the spec of @code{Unit_2}. However, a rule like that would be far too
23604 restrictive. In particular, it would make it impossible to have routines
23605 in separate packages that were mutually recursive.
23607 You might think that a clever enough compiler could look at the actual
23608 elaboration code and determine an appropriate correct order of elaboration,
23609 but in the general case, this is not possible. Consider the following
23610 example.
23612 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
23613 that references
23614 the variable @code{Sqrt_1}, which is declared in the elaboration code
23615 of the body of @code{Unit_1}:
23617 @smallexample @c ada
23618 @cartouche
23619 Sqrt_1 : Float := Sqrt (0.1);
23620 @end cartouche
23621 @end smallexample
23623 @noindent
23624 The elaboration code of the body of @code{Unit_1} also contains:
23626 @smallexample @c ada
23627 @group
23628 @cartouche
23629 if expression_1 = 1 then
23630    Q := Unit_2.Func_2;
23631 end if;
23632 @end cartouche
23633 @end group
23634 @end smallexample
23636 @noindent
23637 @code{Unit_2} is exactly parallel,
23638 it has a procedure @code{Func_2} that references
23639 the variable @code{Sqrt_2}, which is declared in the elaboration code of
23640 the body @code{Unit_2}:
23642 @smallexample @c ada
23643 @cartouche
23644 Sqrt_2 : Float := Sqrt (0.1);
23645 @end cartouche
23646 @end smallexample
23648 @noindent
23649 The elaboration code of the body of @code{Unit_2} also contains:
23651 @smallexample @c ada
23652 @group
23653 @cartouche
23654 if expression_2 = 2 then
23655    Q := Unit_1.Func_1;
23656 end if;
23657 @end cartouche
23658 @end group
23659 @end smallexample
23661 @noindent
23662 Now the question is, which of the following orders of elaboration is
23663 acceptable:
23665 @smallexample
23666 @group
23667 Spec of Unit_1
23668 Spec of Unit_2
23669 Body of Unit_1
23670 Body of Unit_2
23671 @end group
23672 @end smallexample
23674 @noindent
23677 @smallexample
23678 @group
23679 Spec of Unit_2
23680 Spec of Unit_1
23681 Body of Unit_2
23682 Body of Unit_1
23683 @end group
23684 @end smallexample
23686 @noindent
23687 If you carefully analyze the flow here, you will see that you cannot tell
23688 at compile time the answer to this question.
23689 If @code{expression_1} is not equal to 1,
23690 and @code{expression_2} is not equal to 2,
23691 then either order is acceptable, because neither of the function calls is
23692 executed. If both tests evaluate to true, then neither order is acceptable
23693 and in fact there is no correct order.
23695 If one of the two expressions is true, and the other is false, then one
23696 of the above orders is correct, and the other is incorrect. For example,
23697 if @code{expression_1} = 1 and @code{expression_2} /= 2,
23698 then the call to @code{Func_2}
23699 will occur, but not the call to @code{Func_1.}
23700 This means that it is essential
23701 to elaborate the body of @code{Unit_1} before
23702 the body of @code{Unit_2}, so the first
23703 order of elaboration is correct and the second is wrong.
23705 By making @code{expression_1} and @code{expression_2}
23706 depend on input data, or perhaps
23707 the time of day, we can make it impossible for the compiler or binder
23708 to figure out which of these expressions will be true, and hence it
23709 is impossible to guarantee a safe order of elaboration at run time.
23711 @node Checking the Elaboration Order in Ada 95
23712 @section Checking the Elaboration Order in Ada 95
23714 @noindent
23715 In some languages that involve the same kind of elaboration problems,
23716 e.g. Java and C++, the programmer is expected to worry about these
23717 ordering problems himself, and it is common to
23718 write a program in which an incorrect elaboration order  gives
23719 surprising results, because it references variables before they
23720 are initialized.
23721 Ada 95 is designed to be a safe language, and a programmer-beware approach is
23722 clearly not sufficient. Consequently, the language provides three lines
23723 of defense:
23725 @table @asis
23726 @item Standard rules
23727 Some standard rules restrict the possible choice of elaboration
23728 order. In particular, if you @code{with} a unit, then its spec is always
23729 elaborated before the unit doing the @code{with}. Similarly, a parent
23730 spec is always elaborated before the child spec, and finally
23731 a spec is always elaborated before its corresponding body.
23733 @item Dynamic elaboration checks
23734 @cindex Elaboration checks
23735 @cindex Checks, elaboration
23736 Dynamic checks are made at run time, so that if some entity is accessed
23737 before it is elaborated (typically  by means of a subprogram call)
23738 then the exception (@code{Program_Error}) is raised.
23740 @item Elaboration control
23741 Facilities are provided for the programmer to specify the desired order
23742 of elaboration.
23743 @end table
23745 Let's look at these facilities in more detail. First, the rules for
23746 dynamic checking. One possible rule would be simply to say that the
23747 exception is raised if you access a variable which has not yet been
23748 elaborated. The trouble with this approach is that it could require
23749 expensive checks on every variable reference. Instead Ada 95 has two
23750 rules which are a little more restrictive, but easier to check, and
23751 easier to state:
23753 @table @asis
23754 @item Restrictions on calls
23755 A subprogram can only be called at elaboration time if its body
23756 has been elaborated. The rules for elaboration given above guarantee
23757 that the spec of the subprogram has been elaborated before the
23758 call, but not the body. If this rule is violated, then the
23759 exception @code{Program_Error} is raised.
23761 @item Restrictions on instantiations
23762 A generic unit can only be instantiated if the body of the generic
23763 unit has been elaborated. Again, the rules for elaboration given above
23764 guarantee that the spec of the generic unit has been elaborated
23765 before the instantiation, but not the body. If this rule is
23766 violated, then the exception @code{Program_Error} is raised.
23767 @end table
23769 @noindent
23770 The idea is that if the body has been elaborated, then any variables
23771 it references must have been elaborated; by checking for the body being
23772 elaborated we guarantee that none of its references causes any
23773 trouble. As we noted above, this is a little too restrictive, because a
23774 subprogram that has no non-local references in its body may in fact be safe
23775 to call. However, it really would be unsafe to rely on this, because
23776 it would mean that the caller was aware of details of the implementation
23777 in the body. This goes against the basic tenets of Ada.
23779 A plausible implementation can be described as follows.
23780 A Boolean variable is associated with each subprogram
23781 and each generic unit. This variable is initialized to False, and is set to
23782 True at the point body is elaborated. Every call or instantiation checks the
23783 variable, and raises @code{Program_Error} if the variable is False.
23785 Note that one might think that it would be good enough to have one Boolean
23786 variable for each package, but that would not deal with cases of trying
23787 to call a body in the same package as the call
23788 that has not been elaborated yet.
23789 Of course a compiler may be able to do enough analysis to optimize away
23790 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23791 does such optimizations, but still the easiest conceptual model is to
23792 think of there being one variable per subprogram.
23794 @node Controlling the Elaboration Order in Ada 95
23795 @section Controlling the Elaboration Order in Ada 95
23797 @noindent
23798 In the previous section we discussed the rules in Ada 95 which ensure
23799 that @code{Program_Error} is raised if an incorrect elaboration order is
23800 chosen. This prevents erroneous executions, but we need mechanisms to
23801 specify a correct execution and avoid the exception altogether.
23802 To achieve this, Ada 95 provides a number of features for controlling
23803 the order of elaboration. We discuss these features in this section.
23805 First, there are several ways of indicating to the compiler that a given
23806 unit has no elaboration problems:
23808 @table @asis
23809 @item packages that do not require a body
23810 In Ada 95, a library package that does not require a body does not permit
23811 a body. This means that if we have a such a package, as in:
23813 @smallexample @c ada
23814 @group
23815 @cartouche
23816 package Definitions is
23817    generic
23818       type m is new integer;
23819    package Subp is
23820       type a is array (1 .. 10) of m;
23821       type b is array (1 .. 20) of m;
23822    end Subp;
23823 end Definitions;
23824 @end cartouche
23825 @end group
23826 @end smallexample
23828 @noindent
23829 A package that @code{with}'s @code{Definitions} may safely instantiate
23830 @code{Definitions.Subp} because the compiler can determine that there
23831 definitely is no package body to worry about in this case
23833 @item pragma Pure
23834 @cindex pragma Pure
23835 @findex Pure
23836 Places sufficient restrictions on a unit to guarantee that
23837 no call to any subprogram in the unit can result in an
23838 elaboration problem. This means that the compiler does not need
23839 to worry about the point of elaboration of such units, and in
23840 particular, does not need to check any calls to any subprograms
23841 in this unit.
23843 @item pragma Preelaborate
23844 @findex Preelaborate
23845 @cindex pragma Preelaborate
23846 This pragma places slightly less stringent restrictions on a unit than
23847 does pragma Pure,
23848 but these restrictions are still sufficient to ensure that there
23849 are no elaboration problems with any calls to the unit.
23851 @item pragma Elaborate_Body
23852 @findex Elaborate_Body
23853 @cindex pragma Elaborate_Body
23854 This pragma requires that the body of a unit be elaborated immediately
23855 after its spec. Suppose a unit @code{A} has such a pragma,
23856 and unit @code{B} does
23857 a @code{with} of unit @code{A}. Recall that the standard rules require
23858 the spec of unit @code{A}
23859 to be elaborated before the @code{with}'ing unit; given the pragma in
23860 @code{A}, we also know that the body of @code{A}
23861 will be elaborated before @code{B}, so
23862 that calls to @code{A} are safe and do not need a check.
23863 @end table
23865 @noindent
23866 Note that,
23867 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23868 the use of
23869 @code{Elaborate_Body} does not guarantee that the program is
23870 free of elaboration problems, because it may not be possible
23871 to satisfy the requested elaboration order.
23872 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23873 If a programmer
23874 marks @code{Unit_1} as @code{Elaborate_Body},
23875 and not @code{Unit_2,} then the order of
23876 elaboration will be:
23878 @smallexample
23879 @group
23880 Spec of Unit_2
23881 Spec of Unit_1
23882 Body of Unit_1
23883 Body of Unit_2
23884 @end group
23885 @end smallexample
23887 @noindent
23888 Now that means that the call to @code{Func_1} in @code{Unit_2}
23889 need not be checked,
23890 it must be safe. But the call to @code{Func_2} in
23891 @code{Unit_1} may still fail if
23892 @code{Expression_1} is equal to 1,
23893 and the programmer must still take
23894 responsibility for this not being the case.
23896 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23897 eliminated, except for calls entirely within a body, which are
23898 in any case fully under programmer control. However, using the pragma
23899 everywhere is not always possible.
23900 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23901 we marked both of them as having pragma @code{Elaborate_Body}, then
23902 clearly there would be no possible elaboration order.
23904 The above pragmas allow a server to guarantee safe use by clients, and
23905 clearly this is the preferable approach. Consequently a good rule in
23906 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23907 and if this is not possible,
23908 mark them as @code{Elaborate_Body} if possible.
23909 As we have seen, there are situations where neither of these
23910 three pragmas can be used.
23911 So we also provide methods for clients to control the
23912 order of elaboration of the servers on which they depend:
23914 @table @asis
23915 @item pragma Elaborate (unit)
23916 @findex Elaborate
23917 @cindex pragma Elaborate
23918 This pragma is placed in the context clause, after a @code{with} clause,
23919 and it requires that the body of the named unit be elaborated before
23920 the unit in which the pragma occurs. The idea is to use this pragma
23921 if the current unit calls at elaboration time, directly or indirectly,
23922 some subprogram in the named unit.
23924 @item pragma Elaborate_All (unit)
23925 @findex Elaborate_All
23926 @cindex pragma Elaborate_All
23927 This is a stronger version of the Elaborate pragma. Consider the
23928 following example:
23930 @smallexample
23931 Unit A @code{with}'s unit B and calls B.Func in elab code
23932 Unit B @code{with}'s unit C, and B.Func calls C.Func
23933 @end smallexample
23935 @noindent
23936 Now if we put a pragma @code{Elaborate (B)}
23937 in unit @code{A}, this ensures that the
23938 body of @code{B} is elaborated before the call, but not the
23939 body of @code{C}, so
23940 the call to @code{C.Func} could still cause @code{Program_Error} to
23941 be raised.
23943 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23944 not only that the body of the named unit be elaborated before the
23945 unit doing the @code{with}, but also the bodies of all units that the
23946 named unit uses, following @code{with} links transitively. For example,
23947 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23948 then it requires
23949 not only that the body of @code{B} be elaborated before @code{A},
23950 but also the
23951 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23952 @end table
23954 @noindent
23955 We are now in a position to give a usage rule in Ada 95 for avoiding
23956 elaboration problems, at least if dynamic dispatching and access to
23957 subprogram values are not used. We will handle these cases separately
23958 later.
23960 The rule is simple. If a unit has elaboration code that can directly or
23961 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23962 a generic package in a @code{with}'ed unit,
23963 then if the @code{with}'ed unit does not have
23964 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23965 a pragma @code{Elaborate_All}
23966 for the @code{with}'ed unit. By following this rule a client is
23967 assured that calls can be made without risk of an exception.
23969 For generic subprogram instantiations, the rule can be relaxed to
23970 require only a pragma @code{Elaborate} since elaborating the body
23971 of a subprogram cannot cause any transitive elaboration (we are
23972 not calling the subprogram in this case, just elaborating its
23973 declaration).
23975 If this rule is not followed, then a program may be in one of four
23976 states:
23978 @table @asis
23979 @item No order exists
23980 No order of elaboration exists which follows the rules, taking into
23981 account any @code{Elaborate}, @code{Elaborate_All},
23982 or @code{Elaborate_Body} pragmas. In
23983 this case, an Ada 95 compiler must diagnose the situation at bind
23984 time, and refuse to build an executable program.
23986 @item One or more orders exist, all incorrect
23987 One or more acceptable elaboration orders exists, and all of them
23988 generate an elaboration order problem. In this case, the binder
23989 can build an executable program, but @code{Program_Error} will be raised
23990 when the program is run.
23992 @item Several orders exist, some right, some incorrect
23993 One or more acceptable elaboration orders exists, and some of them
23994 work, and some do not. The programmer has not controlled
23995 the order of elaboration, so the binder may or may not pick one of
23996 the correct orders, and the program may or may not raise an
23997 exception when it is run. This is the worst case, because it means
23998 that the program may fail when moved to another compiler, or even
23999 another version of the same compiler.
24001 @item One or more orders exists, all correct
24002 One ore more acceptable elaboration orders exist, and all of them
24003 work. In this case the program runs successfully. This state of
24004 affairs can be guaranteed by following the rule we gave above, but
24005 may be true even if the rule is not followed.
24006 @end table
24008 @noindent
24009 Note that one additional advantage of following our rules on the use
24010 of @code{Elaborate} and @code{Elaborate_All}
24011 is that the program continues to stay in the ideal (all orders OK) state
24012 even if maintenance
24013 changes some bodies of some units. Conversely, if a program that does
24014 not follow this rule happens to be safe at some point, this state of affairs
24015 may deteriorate silently as a result of maintenance changes.
24017 You may have noticed that the above discussion did not mention
24018 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
24019 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
24020 code in the body makes calls to some other unit, so it is still necessary
24021 to use @code{Elaborate_All} on such units.
24023 @node Controlling Elaboration in GNAT - Internal Calls
24024 @section Controlling Elaboration in GNAT - Internal Calls
24026 @noindent
24027 In the case of internal calls, i.e. calls within a single package, the
24028 programmer has full control over the order of elaboration, and it is up
24029 to the programmer to elaborate declarations in an appropriate order. For
24030 example writing:
24032 @smallexample @c ada
24033 @group
24034 @cartouche
24035 function One return Float;
24037 Q : Float := One;
24039 function One return Float is
24040 begin
24041      return 1.0;
24042 end One;
24043 @end cartouche
24044 @end group
24045 @end smallexample
24047 @noindent
24048 will obviously raise @code{Program_Error} at run time, because function
24049 One will be called before its body is elaborated. In this case GNAT will
24050 generate a warning that the call will raise @code{Program_Error}:
24052 @smallexample
24053 @group
24054 @cartouche
24055  1. procedure y is
24056  2.    function One return Float;
24057  3.
24058  4.    Q : Float := One;
24059                     |
24060     >>> warning: cannot call "One" before body is elaborated
24061     >>> warning: Program_Error will be raised at run time
24063  5.
24064  6.    function One return Float is
24065  7.    begin
24066  8.         return 1.0;
24067  9.    end One;
24069 11. begin
24070 12.    null;
24071 13. end;
24072 @end cartouche
24073 @end group
24074 @end smallexample
24076 @noindent
24077 Note that in this particular case, it is likely that the call is safe, because
24078 the function @code{One} does not access any global variables.
24079 Nevertheless in Ada 95, we do not want the validity of the check to depend on
24080 the contents of the body (think about the separate compilation case), so this
24081 is still wrong, as we discussed in the previous sections.
24083 The error is easily corrected by rearranging the declarations so that the
24084 body of One appears before the declaration containing the call
24085 (note that in Ada 95,
24086 declarations can appear in any order, so there is no restriction that
24087 would prevent this reordering, and if we write:
24089 @smallexample @c ada
24090 @group
24091 @cartouche
24092 function One return Float;
24094 function One return Float is
24095 begin
24096      return 1.0;
24097 end One;
24099 Q : Float := One;
24100 @end cartouche
24101 @end group
24102 @end smallexample
24104 @noindent
24105 then all is well, no warning is generated, and no
24106 @code{Program_Error} exception
24107 will be raised.
24108 Things are more complicated when a chain of subprograms is executed:
24110 @smallexample @c ada
24111 @group
24112 @cartouche
24113 function A return Integer;
24114 function B return Integer;
24115 function C return Integer;
24117 function B return Integer is begin return A; end;
24118 function C return Integer is begin return B; end;
24120 X : Integer := C;
24122 function A return Integer is begin return 1; end;
24123 @end cartouche
24124 @end group
24125 @end smallexample
24127 @noindent
24128 Now the call to @code{C}
24129 at elaboration time in the declaration of @code{X} is correct, because
24130 the body of @code{C} is already elaborated,
24131 and the call to @code{B} within the body of
24132 @code{C} is correct, but the call
24133 to @code{A} within the body of @code{B} is incorrect, because the body
24134 of @code{A} has not been elaborated, so @code{Program_Error}
24135 will be raised on the call to @code{A}.
24136 In this case GNAT will generate a
24137 warning that @code{Program_Error} may be
24138 raised at the point of the call. Let's look at the warning:
24140 @smallexample
24141 @group
24142 @cartouche
24143  1. procedure x is
24144  2.    function A return Integer;
24145  3.    function B return Integer;
24146  4.    function C return Integer;
24147  5.
24148  6.    function B return Integer is begin return A; end;
24149                                                     |
24150     >>> warning: call to "A" before body is elaborated may
24151                  raise Program_Error
24152     >>> warning: "B" called at line 7
24153     >>> warning: "C" called at line 9
24155  7.    function C return Integer is begin return B; end;
24156  8.
24157  9.    X : Integer := C;
24159 11.    function A return Integer is begin return 1; end;
24161 13. begin
24162 14.    null;
24163 15. end;
24164 @end cartouche
24165 @end group
24166 @end smallexample
24168 @noindent
24169 Note that the message here says ``may raise'', instead of the direct case,
24170 where the message says ``will be raised''. That's because whether
24171 @code{A} is
24172 actually called depends in general on run-time flow of control.
24173 For example, if the body of @code{B} said
24175 @smallexample @c ada
24176 @group
24177 @cartouche
24178 function B return Integer is
24179 begin
24180    if some-condition-depending-on-input-data then
24181       return A;
24182    else
24183       return 1;
24184    end if;
24185 end B;
24186 @end cartouche
24187 @end group
24188 @end smallexample
24190 @noindent
24191 then we could not know until run time whether the incorrect call to A would
24192 actually occur, so @code{Program_Error} might
24193 or might not be raised. It is possible for a compiler to
24194 do a better job of analyzing bodies, to
24195 determine whether or not @code{Program_Error}
24196 might be raised, but it certainly
24197 couldn't do a perfect job (that would require solving the halting problem
24198 and is provably impossible), and because this is a warning anyway, it does
24199 not seem worth the effort to do the analysis. Cases in which it
24200 would be relevant are rare.
24202 In practice, warnings of either of the forms given
24203 above will usually correspond to
24204 real errors, and should be examined carefully and eliminated.
24205 In the rare case where a warning is bogus, it can be suppressed by any of
24206 the following methods:
24208 @itemize @bullet
24209 @item
24210 Compile with the @option{-gnatws} switch set
24212 @item
24213 Suppress @code{Elaboration_Check} for the called subprogram
24215 @item
24216 Use pragma @code{Warnings_Off} to turn warnings off for the call
24217 @end itemize
24219 @noindent
24220 For the internal elaboration check case,
24221 GNAT by default generates the
24222 necessary run-time checks to ensure
24223 that @code{Program_Error} is raised if any
24224 call fails an elaboration check. Of course this can only happen if a
24225 warning has been issued as described above. The use of pragma
24226 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
24227 some of these checks, meaning that it may be possible (but is not
24228 guaranteed) for a program to be able to call a subprogram whose body
24229 is not yet elaborated, without raising a @code{Program_Error} exception.
24231 @node Controlling Elaboration in GNAT - External Calls
24232 @section Controlling Elaboration in GNAT - External Calls
24234 @noindent
24235 The previous section discussed the case in which the execution of a
24236 particular thread of elaboration code occurred entirely within a
24237 single unit. This is the easy case to handle, because a programmer
24238 has direct and total control over the order of elaboration, and
24239 furthermore, checks need only be generated in cases which are rare
24240 and which the compiler can easily detect.
24241 The situation is more complex when separate compilation is taken into account.
24242 Consider the following:
24244 @smallexample @c ada
24245 @cartouche
24246 @group
24247 package Math is
24248    function Sqrt (Arg : Float) return Float;
24249 end Math;
24251 package body Math is
24252    function Sqrt (Arg : Float) return Float is
24253    begin
24254          ...
24255    end Sqrt;
24256 end Math;
24257 @end group
24258 @group
24259 with Math;
24260 package Stuff is
24261    X : Float := Math.Sqrt (0.5);
24262 end Stuff;
24264 with Stuff;
24265 procedure Main is
24266 begin
24267    ...
24268 end Main;
24269 @end group
24270 @end cartouche
24271 @end smallexample
24273 @noindent
24274 where @code{Main} is the main program. When this program is executed, the
24275 elaboration code must first be executed, and one of the jobs of the
24276 binder is to determine the order in which the units of a program are
24277 to be elaborated. In this case we have four units: the spec and body
24278 of @code{Math},
24279 the spec of @code{Stuff} and the body of @code{Main}).
24280 In what order should the four separate sections of elaboration code
24281 be executed?
24283 There are some restrictions in the order of elaboration that the binder
24284 can choose. In particular, if unit U has a @code{with}
24285 for a package @code{X}, then you
24286 are assured that the spec of @code{X}
24287 is elaborated before U , but you are
24288 not assured that the body of @code{X}
24289 is elaborated before U.
24290 This means that in the above case, the binder is allowed to choose the
24291 order:
24293 @smallexample
24294 spec of Math
24295 spec of Stuff
24296 body of Math
24297 body of Main
24298 @end smallexample
24300 @noindent
24301 but that's not good, because now the call to @code{Math.Sqrt}
24302 that happens during
24303 the elaboration of the @code{Stuff}
24304 spec happens before the body of @code{Math.Sqrt} is
24305 elaborated, and hence causes @code{Program_Error} exception to be raised.
24306 At first glance, one might say that the binder is misbehaving, because
24307 obviously you want to elaborate the body of something you @code{with}
24308 first, but
24309 that is not a general rule that can be followed in all cases. Consider
24311 @smallexample @c ada
24312 @group
24313 @cartouche
24314 package X is ...
24316 package Y is ...
24318 with X;
24319 package body Y is ...
24321 with Y;
24322 package body X is ...
24323 @end cartouche
24324 @end group
24325 @end smallexample
24327 @noindent
24328 This is a common arrangement, and, apart from the order of elaboration
24329 problems that might arise in connection with elaboration code, this works fine.
24330 A rule that says that you must first elaborate the body of anything you
24331 @code{with} cannot work in this case:
24332 the body of @code{X} @code{with}'s @code{Y},
24333 which means you would have to
24334 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
24335 which means
24336 you have to elaborate the body of @code{X} first, but ... and we have a
24337 loop that cannot be broken.
24339 It is true that the binder can in many cases guess an order of elaboration
24340 that is unlikely to cause a @code{Program_Error}
24341 exception to be raised, and it tries to do so (in the
24342 above example of @code{Math/Stuff/Spec}, the GNAT binder will
24343 by default
24344 elaborate the body of @code{Math} right after its spec, so all will be well).
24346 However, a program that blindly relies on the binder to be helpful can
24347 get into trouble, as we discussed in the previous sections, so
24348 GNAT
24349 provides a number of facilities for assisting the programmer in
24350 developing programs that are robust with respect to elaboration order.
24352 @node Default Behavior in GNAT - Ensuring Safety
24353 @section Default Behavior in GNAT - Ensuring Safety
24355 @noindent
24356 The default behavior in GNAT ensures elaboration safety. In its
24357 default mode GNAT implements the
24358 rule we previously described as the right approach. Let's restate it:
24360 @itemize
24361 @item
24362 @emph{If a unit has elaboration code that can directly or indirectly make a
24363 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
24364 package in a @code{with}'ed unit, then if the @code{with}'ed unit
24365 does not have pragma @code{Pure} or
24366 @code{Preelaborate}, then the client should have an
24367 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
24369 @emph{In the case of instantiating a generic subprogram, it is always
24370 sufficient to have only an @code{Elaborate} pragma for the
24371 @code{with}'ed unit.}
24372 @end itemize
24374 @noindent
24375 By following this rule a client is assured that calls and instantiations
24376 can be made without risk of an exception.
24378 In this mode GNAT traces all calls that are potentially made from
24379 elaboration code, and puts in any missing implicit @code{Elaborate}
24380 and @code{Elaborate_All} pragmas.
24381 The advantage of this approach is that no elaboration problems
24382 are possible if the binder can find an elaboration order that is
24383 consistent with these implicit @code{Elaborate} and
24384 @code{Elaborate_All} pragmas. The
24385 disadvantage of this approach is that no such order may exist.
24387 If the binder does not generate any diagnostics, then it means that it has
24388 found an elaboration order that is guaranteed to be safe. However, the binder
24389 may still be relying on implicitly generated @code{Elaborate} and
24390 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
24391 guaranteed.
24393 If it is important to guarantee portability, then the compilations should
24394 use the
24395 @option{-gnatwl}
24396 (warn on elaboration problems) switch. This will cause warning messages
24397 to be generated indicating the missing @code{Elaborate} and
24398 @code{Elaborate_All} pragmas.
24399 Consider the following source program:
24401 @smallexample @c ada
24402 @group
24403 @cartouche
24404 with k;
24405 package j is
24406   m : integer := k.r;
24407 end;
24408 @end cartouche
24409 @end group
24410 @end smallexample
24412 @noindent
24413 where it is clear that there
24414 should be a pragma @code{Elaborate_All}
24415 for unit @code{k}. An implicit pragma will be generated, and it is
24416 likely that the binder will be able to honor it. However, if you want
24417 to port this program to some other Ada compiler than GNAT.
24418 it is safer to include the pragma explicitly in the source. If this
24419 unit is compiled with the
24420 @option{-gnatwl}
24421 switch, then the compiler outputs a warning:
24423 @smallexample
24424 @group
24425 @cartouche
24426 1. with k;
24427 2. package j is
24428 3.   m : integer := k.r;
24429                      |
24430    >>> warning: call to "r" may raise Program_Error
24431    >>> warning: missing pragma Elaborate_All for "k"
24433 4. end;
24434 @end cartouche
24435 @end group
24436 @end smallexample
24438 @noindent
24439 and these warnings can be used as a guide for supplying manually
24440 the missing pragmas. It is usually a bad idea to use this warning
24441 option during development. That's because it will warn you when
24442 you need to put in a pragma, but cannot warn you when it is time
24443 to take it out. So the use of pragma @code{Elaborate_All} may lead to
24444 unnecessary dependencies and even false circularities.
24446 This default mode is more restrictive than the Ada Reference
24447 Manual, and it is possible to construct programs which will compile
24448 using the dynamic model described there, but will run into a
24449 circularity using the safer static model we have described.
24451 Of course any Ada compiler must be able to operate in a mode
24452 consistent with the requirements of the Ada Reference Manual,
24453 and in particular must have the capability of implementing the
24454 standard dynamic model of elaboration with run-time checks.
24456 In GNAT, this standard mode can be achieved either by the use of
24457 the @option{-gnatE} switch on the compiler (@command{gcc} or
24458 @command{gnatmake}) command, or by the use of the configuration pragma:
24460 @smallexample @c ada
24461 pragma Elaboration_Checks (RM);
24462 @end smallexample
24464 @noindent
24465 Either approach will cause the unit affected to be compiled using the
24466 standard dynamic run-time elaboration checks described in the Ada
24467 Reference Manual. The static model is generally preferable, since it
24468 is clearly safer to rely on compile and link time checks rather than
24469 run-time checks. However, in the case of legacy code, it may be
24470 difficult to meet the requirements of the static model. This
24471 issue is further discussed in
24472 @ref{What to Do If the Default Elaboration Behavior Fails}.
24474 Note that the static model provides a strict subset of the allowed
24475 behavior and programs of the Ada Reference Manual, so if you do
24476 adhere to the static model and no circularities exist,
24477 then you are assured that your program will
24478 work using the dynamic model, providing that you remove any
24479 pragma Elaborate statements from the source.
24481 @node Treatment of Pragma Elaborate
24482 @section Treatment of Pragma Elaborate
24483 @cindex Pragma Elaborate
24485 @noindent
24486 The use of @code{pragma Elaborate}
24487 should generally be avoided in Ada 95 programs.
24488 The reason for this is that there is no guarantee that transitive calls
24489 will be properly handled. Indeed at one point, this pragma was placed
24490 in Annex J (Obsolescent Features), on the grounds that it is never useful.
24492 Now that's a bit restrictive. In practice, the case in which
24493 @code{pragma Elaborate} is useful is when the caller knows that there
24494 are no transitive calls, or that the called unit contains all necessary
24495 transitive @code{pragma Elaborate} statements, and legacy code often
24496 contains such uses.
24498 Strictly speaking the static mode in GNAT should ignore such pragmas,
24499 since there is no assurance at compile time that the necessary safety
24500 conditions are met. In practice, this would cause GNAT to be incompatible
24501 with correctly written Ada 83 code that had all necessary
24502 @code{pragma Elaborate} statements in place. Consequently, we made the
24503 decision that GNAT in its default mode will believe that if it encounters
24504 a @code{pragma Elaborate} then the programmer knows what they are doing,
24505 and it will trust that no elaboration errors can occur.
24507 The result of this decision is two-fold. First to be safe using the
24508 static mode, you should remove all @code{pragma Elaborate} statements.
24509 Second, when fixing circularities in existing code, you can selectively
24510 use @code{pragma Elaborate} statements to convince the static mode of
24511 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
24512 statement.
24514 When using the static mode with @option{-gnatwl}, any use of
24515 @code{pragma Elaborate} will generate a warning about possible
24516 problems.
24518 @node Elaboration Issues for Library Tasks
24519 @section Elaboration Issues for Library Tasks
24520 @cindex Library tasks, elaboration issues
24521 @cindex Elaboration of library tasks
24523 @noindent
24524 In this section we examine special elaboration issues that arise for
24525 programs that declare library level tasks.
24527 Generally the model of execution of an Ada program is that all units are
24528 elaborated, and then execution of the program starts. However, the
24529 declaration of library tasks definitely does not fit this model. The
24530 reason for this is that library tasks start as soon as they are declared
24531 (more precisely, as soon as the statement part of the enclosing package
24532 body is reached), that is to say before elaboration
24533 of the program is complete. This means that if such a task calls a
24534 subprogram, or an entry in another task, the callee may or may not be
24535 elaborated yet, and in the standard
24536 Reference Manual model of dynamic elaboration checks, you can even
24537 get timing dependent Program_Error exceptions, since there can be
24538 a race between the elaboration code and the task code.
24540 The static model of elaboration in GNAT seeks to avoid all such
24541 dynamic behavior, by being conservative, and the conservative
24542 approach in this particular case is to assume that all the code
24543 in a task body is potentially executed at elaboration time if
24544 a task is declared at the library level.
24546 This can definitely result in unexpected circularities. Consider
24547 the following example
24549 @smallexample @c ada
24550 package Decls is
24551   task Lib_Task is
24552      entry Start;
24553   end Lib_Task;
24555   type My_Int is new Integer;
24557   function Ident (M : My_Int) return My_Int;
24558 end Decls;
24560 with Utils;
24561 package body Decls is
24562   task body Lib_Task is
24563   begin
24564      accept Start;
24565      Utils.Put_Val (2);
24566   end Lib_Task;
24568   function Ident (M : My_Int) return My_Int is
24569   begin
24570      return M;
24571   end Ident;
24572 end Decls;
24574 with Decls;
24575 package Utils is
24576   procedure Put_Val (Arg : Decls.My_Int);
24577 end Utils;
24579 with Text_IO;
24580 package body Utils is
24581   procedure Put_Val (Arg : Decls.My_Int) is
24582   begin
24583      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24584   end Put_Val;
24585 end Utils;
24587 with Decls;
24588 procedure Main is
24589 begin
24590    Decls.Lib_Task.Start;
24591 end;
24592 @end smallexample
24594 @noindent
24595 If the above example is compiled in the default static elaboration
24596 mode, then a circularity occurs. The circularity comes from the call
24597 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
24598 this call occurs in elaboration code, we need an implicit pragma
24599 @code{Elaborate_All} for @code{Utils}. This means that not only must
24600 the spec and body of @code{Utils} be elaborated before the body
24601 of @code{Decls}, but also the spec and body of any unit that is
24602 @code{with'ed} by the body of @code{Utils} must also be elaborated before
24603 the body of @code{Decls}. This is the transitive implication of
24604 pragma @code{Elaborate_All} and it makes sense, because in general
24605 the body of @code{Put_Val} might have a call to something in a
24606 @code{with'ed} unit.
24608 In this case, the body of Utils (actually its spec) @code{with's}
24609 @code{Decls}. Unfortunately this means that the body of @code{Decls}
24610 must be elaborated before itself, in case there is a call from the
24611 body of @code{Utils}.
24613 Here is the exact chain of events we are worrying about:
24615 @enumerate
24616 @item
24617 In the body of @code{Decls} a call is made from within the body of a library
24618 task to a subprogram in the package @code{Utils}. Since this call may
24619 occur at elaboration time (given that the task is activated at elaboration
24620 time), we have to assume the worst, i.e. that the
24621 call does happen at elaboration time.
24623 @item
24624 This means that the body and spec of @code{Util} must be elaborated before
24625 the body of @code{Decls} so that this call does not cause an access before
24626 elaboration.
24628 @item
24629 Within the body of @code{Util}, specifically within the body of
24630 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
24631 by this package.
24633 @item
24634 One such @code{with}'ed package is package @code{Decls}, so there
24635 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
24636 In fact there is such a call in this example, but we would have to
24637 assume that there was such a call even if it were not there, since
24638 we are not supposed to write the body of @code{Decls} knowing what
24639 is in the body of @code{Utils}; certainly in the case of the
24640 static elaboration model, the compiler does not know what is in
24641 other bodies and must assume the worst.
24643 @item
24644 This means that the spec and body of @code{Decls} must also be
24645 elaborated before we elaborate the unit containing the call, but
24646 that unit is @code{Decls}! This means that the body of @code{Decls}
24647 must be elaborated before itself, and that's a circularity.
24648 @end enumerate
24650 @noindent
24651 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
24652 the body of @code{Decls} you will get a true Ada Reference Manual
24653 circularity that makes the program illegal.
24655 In practice, we have found that problems with the static model of
24656 elaboration in existing code often arise from library tasks, so
24657 we must address this particular situation.
24659 Note that if we compile and run the program above, using the dynamic model of
24660 elaboration (that is to say use the @option{-gnatE} switch),
24661 then it compiles, binds,
24662 links, and runs, printing the expected result of 2. Therefore in some sense
24663 the circularity here is only apparent, and we need to capture
24664 the properties of this program that  distinguish it from other library-level
24665 tasks that have real elaboration problems.
24667 We have four possible answers to this question:
24669 @itemize @bullet
24671 @item
24672 Use the dynamic model of elaboration.
24674 If we use the @option{-gnatE} switch, then as noted above, the program works.
24675 Why is this? If we examine the task body, it is apparent that the task cannot
24676 proceed past the
24677 @code{accept} statement until after elaboration has been completed, because
24678 the corresponding entry call comes from the main program, not earlier.
24679 This is why the dynamic model works here. But that's really giving
24680 up on a precise analysis, and we prefer to take this approach only if we cannot
24681 solve the
24682 problem in any other manner. So let us examine two ways to reorganize
24683 the program to avoid the potential elaboration problem.
24685 @item
24686 Split library tasks into separate packages.
24688 Write separate packages, so that library tasks are isolated from
24689 other declarations as much as possible. Let us look at a variation on
24690 the above program.
24692 @smallexample @c ada
24693 package Decls1 is
24694   task Lib_Task is
24695      entry Start;
24696   end Lib_Task;
24697 end Decls1;
24699 with Utils;
24700 package body Decls1 is
24701   task body Lib_Task is
24702   begin
24703      accept Start;
24704      Utils.Put_Val (2);
24705   end Lib_Task;
24706 end Decls1;
24708 package Decls2 is
24709   type My_Int is new Integer;
24710   function Ident (M : My_Int) return My_Int;
24711 end Decls2;
24713 with Utils;
24714 package body Decls2 is
24715   function Ident (M : My_Int) return My_Int is
24716   begin
24717      return M;
24718   end Ident;
24719 end Decls2;
24721 with Decls2;
24722 package Utils is
24723   procedure Put_Val (Arg : Decls2.My_Int);
24724 end Utils;
24726 with Text_IO;
24727 package body Utils is
24728   procedure Put_Val (Arg : Decls2.My_Int) is
24729   begin
24730      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
24731   end Put_Val;
24732 end Utils;
24734 with Decls1;
24735 procedure Main is
24736 begin
24737    Decls1.Lib_Task.Start;
24738 end;
24739 @end smallexample
24741 @noindent
24742 All we have done is to split @code{Decls} into two packages, one
24743 containing the library task, and one containing everything else. Now
24744 there is no cycle, and the program compiles, binds, links and executes
24745 using the default static model of elaboration.
24747 @item
24748 Declare separate task types.
24750 A significant part of the problem arises because of the use of the
24751 single task declaration form. This means that the elaboration of
24752 the task type, and the elaboration of the task itself (i.e. the
24753 creation of the task) happen at the same time. A good rule
24754 of style in Ada 95 is to always create explicit task types. By
24755 following the additional step of placing task objects in separate
24756 packages from the task type declaration, many elaboration problems
24757 are avoided. Here is another modified example of the example program:
24759 @smallexample @c ada
24760 package Decls is
24761   task type Lib_Task_Type is
24762      entry Start;
24763   end Lib_Task_Type;
24765   type My_Int is new Integer;
24767   function Ident (M : My_Int) return My_Int;
24768 end Decls;
24770 with Utils;
24771 package body Decls is
24772   task body Lib_Task_Type is
24773   begin
24774      accept Start;
24775      Utils.Put_Val (2);
24776   end Lib_Task_Type;
24778   function Ident (M : My_Int) return My_Int is
24779   begin
24780      return M;
24781   end Ident;
24782 end Decls;
24784 with Decls;
24785 package Utils is
24786   procedure Put_Val (Arg : Decls.My_Int);
24787 end Utils;
24789 with Text_IO;
24790 package body Utils is
24791   procedure Put_Val (Arg : Decls.My_Int) is
24792   begin
24793      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
24794   end Put_Val;
24795 end Utils;
24797 with Decls;
24798 package Declst is
24799    Lib_Task : Decls.Lib_Task_Type;
24800 end Declst;
24802 with Declst;
24803 procedure Main is
24804 begin
24805    Declst.Lib_Task.Start;
24806 end;
24807 @end smallexample
24809 @noindent
24810 What we have done here is to replace the @code{task} declaration in
24811 package @code{Decls} with a @code{task type} declaration. Then we
24812 introduce a separate package @code{Declst} to contain the actual
24813 task object. This separates the elaboration issues for
24814 the @code{task type}
24815 declaration, which causes no trouble, from the elaboration issues
24816 of the task object, which is also unproblematic, since it is now independent
24817 of the elaboration of  @code{Utils}.
24818 This separation of concerns also corresponds to
24819 a generally sound engineering principle of separating declarations
24820 from instances. This version of the program also compiles, binds, links,
24821 and executes, generating the expected output.
24823 @item
24824 Use No_Entry_Calls_In_Elaboration_Code restriction.
24825 @cindex No_Entry_Calls_In_Elaboration_Code
24827 The previous two approaches described how a program can be restructured
24828 to avoid the special problems caused by library task bodies. in practice,
24829 however, such restructuring may be difficult to apply to existing legacy code,
24830 so we must consider solutions that do not require massive rewriting.
24832 Let us consider more carefully why our original sample program works
24833 under the dynamic model of elaboration. The reason is that the code
24834 in the task body blocks immediately on the @code{accept}
24835 statement. Now of course there is nothing to prohibit elaboration
24836 code from making entry calls (for example from another library level task),
24837 so we cannot tell in isolation that
24838 the task will not execute the accept statement  during elaboration.
24840 However, in practice it is very unusual to see elaboration code
24841 make any entry calls, and the pattern of tasks starting
24842 at elaboration time and then immediately blocking on @code{accept} or
24843 @code{select} statements is very common. What this means is that
24844 the compiler is being too pessimistic when it analyzes the
24845 whole package body as though it might be executed at elaboration
24846 time.
24848 If we know that the elaboration code contains no entry calls, (a very safe
24849 assumption most of the time, that could almost be made the default
24850 behavior), then we can compile all units of the program under control
24851 of the following configuration pragma:
24853 @smallexample
24854 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24855 @end smallexample
24857 @noindent
24858 This pragma can be placed in the @file{gnat.adc} file in the usual
24859 manner. If we take our original unmodified program and compile it
24860 in the presence of a @file{gnat.adc} containing the above pragma,
24861 then once again, we can compile, bind, link, and execute, obtaining
24862 the expected result. In the presence of this pragma, the compiler does
24863 not trace calls in a task body, that appear after the first @code{accept}
24864 or @code{select} statement, and therefore does not report a potential
24865 circularity in the original program.
24867 The compiler will check to the extent it can that the above
24868 restriction is not violated, but it is not always possible to do a
24869 complete check at compile time, so it is important to use this
24870 pragma only if the stated restriction is in fact met, that is to say
24871 no task receives an entry call before elaboration of all units is completed.
24873 @end itemize
24875 @node Mixing Elaboration Models
24876 @section Mixing Elaboration Models
24877 @noindent
24878 So far, we have assumed that the entire program is either compiled
24879 using the dynamic model or static model, ensuring consistency. It
24880 is possible to mix the two models, but rules have to be followed
24881 if this mixing is done to ensure that elaboration checks are not
24882 omitted.
24884 The basic rule is that @emph{a unit compiled with the static model cannot
24885 be @code{with'ed} by a unit compiled with the dynamic model}. The
24886 reason for this is that in the static model, a unit assumes that
24887 its clients guarantee to use (the equivalent of) pragma
24888 @code{Elaborate_All} so that no elaboration checks are required
24889 in inner subprograms, and this assumption is violated if the
24890 client is compiled with dynamic checks.
24892 The precise rule is as follows. A unit that is compiled with dynamic
24893 checks can only @code{with} a unit that meets at least one of the
24894 following criteria:
24896 @itemize @bullet
24898 @item
24899 The @code{with'ed} unit is itself compiled with dynamic elaboration
24900 checks (that is with the @option{-gnatE} switch.
24902 @item
24903 The @code{with'ed} unit is an internal GNAT implementation unit from
24904 the System, Interfaces, Ada, or GNAT hierarchies.
24906 @item
24907 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24909 @item
24910 The @code{with'ing} unit (that is the client) has an explicit pragma
24911 @code{Elaborate_All} for the @code{with'ed} unit.
24913 @end itemize
24915 @noindent
24916 If this rule is violated, that is if a unit with dynamic elaboration
24917 checks @code{with's} a unit that does not meet one of the above four
24918 criteria, then the binder (@code{gnatbind}) will issue a warning
24919 similar to that in the following example:
24921 @smallexample
24922 warning: "x.ads" has dynamic elaboration checks and with's
24923 warning:   "y.ads" which has static elaboration checks
24924 @end smallexample
24926 @noindent
24927 These warnings indicate that the rule has been violated, and that as a result
24928 elaboration checks may be missed in the resulting executable file.
24929 This warning may be suppressed using the @option{-ws} binder switch
24930 in the usual manner.
24932 One useful application of this mixing rule is in the case of a subsystem
24933 which does not itself @code{with} units from the remainder of the
24934 application. In this case, the entire subsystem can be compiled with
24935 dynamic checks to resolve a circularity in the subsystem, while
24936 allowing the main application that uses this subsystem to be compiled
24937 using the more reliable default static model.
24939 @node What to Do If the Default Elaboration Behavior Fails
24940 @section What to Do If the Default Elaboration Behavior Fails
24942 @noindent
24943 If the binder cannot find an acceptable order, it outputs detailed
24944 diagnostics. For example:
24945 @smallexample
24946 @group
24947 @iftex
24948 @leftskip=0cm
24949 @end iftex
24950 error: elaboration circularity detected
24951 info:   "proc (body)" must be elaborated before "pack (body)"
24952 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24953 info:     recompile "pack (body)" with -gnatwl
24954 info:                             for full details
24955 info:       "proc (body)"
24956 info:         is needed by its spec:
24957 info:       "proc (spec)"
24958 info:         which is withed by:
24959 info:       "pack (body)"
24960 info:  "pack (body)" must be elaborated before "proc (body)"
24961 info:     reason: pragma Elaborate in unit "proc (body)"
24962 @end group
24964 @end smallexample
24966 @noindent
24967 In this case we have a cycle that the binder cannot break. On the one
24968 hand, there is an explicit pragma Elaborate in @code{proc} for
24969 @code{pack}. This means that the body of @code{pack} must be elaborated
24970 before the body of @code{proc}. On the other hand, there is elaboration
24971 code in @code{pack} that calls a subprogram in @code{proc}. This means
24972 that for maximum safety, there should really be a pragma
24973 Elaborate_All in @code{pack} for @code{proc} which would require that
24974 the body of @code{proc} be elaborated before the body of
24975 @code{pack}. Clearly both requirements cannot be satisfied.
24976 Faced with a circularity of this kind, you have three different options.
24978 @table @asis
24979 @item Fix the program
24980 The most desirable option from the point of view of long-term maintenance
24981 is to rearrange the program so that the elaboration problems are avoided.
24982 One useful technique is to place the elaboration code into separate
24983 child packages. Another is to move some of the initialization code to
24984 explicitly called subprograms, where the program controls the order
24985 of initialization explicitly. Although this is the most desirable option,
24986 it may be impractical and involve too much modification, especially in
24987 the case of complex legacy code.
24989 @item Perform dynamic checks
24990 If the compilations are done using the
24991 @option{-gnatE}
24992 (dynamic elaboration check) switch, then GNAT behaves in a quite different
24993 manner. Dynamic checks are generated for all calls that could possibly result
24994 in raising an exception. With this switch, the compiler does not generate
24995 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
24996 exactly as specified in the Ada 95 Reference Manual. The binder will generate
24997 an executable program that may or may not raise @code{Program_Error}, and then
24998 it is the programmer's job to ensure that it does not raise an exception. Note
24999 that it is important to compile all units with the switch, it cannot be used
25000 selectively.
25002 @item Suppress checks
25003 The drawback of dynamic checks is that they generate a
25004 significant overhead at run time, both in space and time. If you
25005 are absolutely sure that your program cannot raise any elaboration
25006 exceptions, and you still want to use the dynamic elaboration model,
25007 then you can use the configuration pragma
25008 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
25009 example this pragma could be placed in the @file{gnat.adc} file.
25011 @item Suppress checks selectively
25012 When you know that certain calls or instantiations in elaboration code cannot
25013 possibly lead to an elaboration error, and the binder nevertheless complains
25014 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
25015 elaboration circularities, it is possible to remove those warnings locally and
25016 obtain a program that will bind. Clearly this can be unsafe, and it is the
25017 responsibility of the programmer to make sure that the resulting program has no
25018 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
25019 used with different granularity to suppress warnings and break elaboration
25020 circularities:
25022 @itemize @bullet
25023 @item
25024 Place the pragma that names the called subprogram in the declarative part
25025 that contains the call.
25027 @item
25028 Place the pragma in the declarative part, without naming an entity. This
25029 disables warnings on all calls in the corresponding  declarative region.
25031 @item
25032 Place the pragma in the package spec that declares the called subprogram,
25033 and name the subprogram. This disables warnings on all elaboration calls to
25034 that subprogram.
25036 @item
25037 Place the pragma in the package spec that declares the called subprogram,
25038 without naming any entity. This disables warnings on all elaboration calls to
25039 all subprograms declared in this spec.
25041 @item Use Pragma Elaborate
25042 As previously described in section @xref{Treatment of Pragma Elaborate},
25043 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
25044 that no elaboration checks are required on calls to the designated unit.
25045 There may be cases in which the caller knows that no transitive calls
25046 can occur, so that a @code{pragma Elaborate} will be sufficient in a
25047 case where @code{pragma Elaborate_All} would cause a circularity.
25048 @end itemize
25050 @noindent
25051 These five cases are listed in order of decreasing safety, and therefore
25052 require increasing programmer care in their application. Consider the
25053 following program:
25055 @smallexample @c adanocomment
25056 package Pack1 is
25057   function F1 return Integer;
25058   X1 : Integer;
25059 end Pack1;
25061 package Pack2 is
25062   function F2 return Integer;
25063   function Pure (x : integer) return integer;
25064   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
25065   --  pragma Suppress (Elaboration_Check);              -- (4)
25066 end Pack2;
25068 with Pack2;
25069 package body Pack1 is
25070   function F1 return Integer is
25071   begin
25072     return 100;
25073   end F1;
25074   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
25075 begin
25076   declare
25077     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
25078     --  pragma Suppress(Elaboration_Check);             -- (2)
25079   begin
25080     X1 := Pack2.F2 + 1;                --  Elab. call (2)
25081   end;
25082 end Pack1;
25084 with Pack1;
25085 package body Pack2 is
25086   function F2 return Integer is
25087   begin
25088      return Pack1.F1;
25089   end F2;
25090   function Pure (x : integer) return integer is
25091   begin
25092      return x ** 3 - 3 * x;
25093   end;
25094 end Pack2;
25096 with Pack1, Ada.Text_IO;
25097 procedure Proc3 is
25098 begin
25099   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
25100 end Proc3;
25101 @end smallexample
25102 In the absence of any pragmas, an attempt to bind this program produces
25103 the following diagnostics:
25104 @smallexample
25105 @group
25106 @iftex
25107 @leftskip=.5cm
25108 @end iftex
25109 error: elaboration circularity detected
25110 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
25111 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
25112 info:       recompile "pack1 (body)" with -gnatwl for full details
25113 info:          "pack1 (body)"
25114 info:             must be elaborated along with its spec:
25115 info:          "pack1 (spec)"
25116 info:             which is withed by:
25117 info:          "pack2 (body)"
25118 info:             which must be elaborated along with its spec:
25119 info:          "pack2 (spec)"
25120 info:             which is withed by:
25121 info:          "pack1 (body)"
25122 @end group
25123 @end smallexample
25124 The sources of the circularity are the two calls to @code{Pack2.Pure} and
25125 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
25126 F2 is safe, even though F2 calls F1, because the call appears after the
25127 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
25128 remove the warning on the call. It is also possible to use pragma (2)
25129 because there are no other potentially unsafe calls in the block.
25131 @noindent
25132 The call to @code{Pure} is safe because this function does not depend on the
25133 state of @code{Pack2}. Therefore any call to this function is safe, and it
25134 is correct to place pragma (3) in the corresponding package spec.
25136 @noindent
25137 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
25138 warnings on all calls to functions declared therein. Note that this is not
25139 necessarily safe, and requires more detailed examination of the subprogram
25140 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
25141 be already elaborated.
25142 @end table
25144 @noindent
25145 It is hard to generalize on which of these four approaches should be
25146 taken. Obviously if it is possible to fix the program so that the default
25147 treatment works, this is preferable, but this may not always be practical.
25148 It is certainly simple enough to use
25149 @option{-gnatE}
25150 but the danger in this case is that, even if the GNAT binder
25151 finds a correct elaboration order, it may not always do so,
25152 and certainly a binder from another Ada compiler might not. A
25153 combination of testing and analysis (for which the warnings generated
25154 with the
25155 @option{-gnatwl}
25156 switch can be useful) must be used to ensure that the program is free
25157 of errors. One switch that is useful in this testing is the
25158 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
25159 switch for
25160 @code{gnatbind}.
25161 Normally the binder tries to find an order that has the best chance of
25162 of avoiding elaboration problems. With this switch, the binder
25163 plays a devil's advocate role, and tries to choose the order that
25164 has the best chance of failing. If your program works even with this
25165 switch, then it has a better chance of being error free, but this is still
25166 not a guarantee.
25168 For an example of this approach in action, consider the C-tests (executable
25169 tests) from the ACVC suite. If these are compiled and run with the default
25170 treatment, then all but one of them succeed without generating any error
25171 diagnostics from the binder. However, there is one test that fails, and
25172 this is not surprising, because the whole point of this test is to ensure
25173 that the compiler can handle cases where it is impossible to determine
25174 a correct order statically, and it checks that an exception is indeed
25175 raised at run time.
25177 This one test must be compiled and run using the
25178 @option{-gnatE}
25179 switch, and then it passes. Alternatively, the entire suite can
25180 be run using this switch. It is never wrong to run with the dynamic
25181 elaboration switch if your code is correct, and we assume that the
25182 C-tests are indeed correct (it is less efficient, but efficiency is
25183 not a factor in running the ACVC tests.)
25185 @node Elaboration for Access-to-Subprogram Values
25186 @section Elaboration for Access-to-Subprogram Values
25187 @cindex Access-to-subprogram
25189 @noindent
25190 The introduction of access-to-subprogram types in Ada 95 complicates
25191 the handling of elaboration. The trouble is that it becomes
25192 impossible to tell at compile time which procedure
25193 is being called. This means that it is not possible for the binder
25194 to analyze the elaboration requirements in this case.
25196 If at the point at which the access value is created
25197 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
25198 the body of the subprogram is
25199 known to have been elaborated, then the access value is safe, and its use
25200 does not require a check. This may be achieved by appropriate arrangement
25201 of the order of declarations if the subprogram is in the current unit,
25202 or, if the subprogram is in another unit, by using pragma
25203 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
25204 on the referenced unit.
25206 If the referenced body is not known to have been elaborated at the point
25207 the access value is created, then any use of the access value must do a
25208 dynamic check, and this dynamic check will fail and raise a
25209 @code{Program_Error} exception if the body has not been elaborated yet.
25210 GNAT will generate the necessary checks, and in addition, if the
25211 @option{-gnatwl}
25212 switch is set, will generate warnings that such checks are required.
25214 The use of dynamic dispatching for tagged types similarly generates
25215 a requirement for dynamic checks, and premature calls to any primitive
25216 operation of a tagged type before the body of the operation has been
25217 elaborated, will result in the raising of @code{Program_Error}.
25219 @node Summary of Procedures for Elaboration Control
25220 @section Summary of Procedures for Elaboration Control
25221 @cindex Elaboration control
25223 @noindent
25224 First, compile your program with the default options, using none of
25225 the special elaboration control switches. If the binder successfully
25226 binds your program, then you can be confident that, apart from issues
25227 raised by the use of access-to-subprogram types and dynamic dispatching,
25228 the program is free of elaboration errors. If it is important that the
25229 program be portable, then use the
25230 @option{-gnatwl}
25231 switch to generate warnings about missing @code{Elaborate} or
25232 @code{Elaborate_All} pragmas, and supply the missing pragmas.
25234 If the program fails to bind using the default static elaboration
25235 handling, then you can fix the program to eliminate the binder
25236 message, or recompile the entire program with the
25237 @option{-gnatE} switch to generate dynamic elaboration checks,
25238 and, if you are sure there really are no elaboration problems,
25239 use a global pragma @code{Suppress (Elaboration_Check)}.
25241 @node Other Elaboration Order Considerations
25242 @section Other Elaboration Order Considerations
25243 @noindent
25244 This section has been entirely concerned with the issue of finding a valid
25245 elaboration order, as defined by the Ada Reference Manual. In a case
25246 where several elaboration orders are valid, the task is to find one
25247 of the possible valid elaboration orders (and the static model in GNAT
25248 will ensure that this is achieved).
25250 The purpose of the elaboration rules in the Ada Reference Manual is to
25251 make sure that no entity is accessed before it has been elaborated. For
25252 a subprogram, this means that the spec and body must have been elaborated
25253 before the subprogram is called. For an object, this means that the object
25254 must have been elaborated before its value is read or written. A violation
25255 of either of these two requirements is an access before elaboration order,
25256 and this section has been all about avoiding such errors.
25258 In the case where more than one order of elaboration is possible, in the
25259 sense that access before elaboration errors are avoided, then any one of
25260 the orders is ``correct'' in the sense that it meets the requirements of
25261 the Ada Reference Manual, and no such error occurs.
25263 However, it may be the case for a given program, that there are
25264 constraints on the order of elaboration that come not from consideration
25265 of avoiding elaboration errors, but rather from extra-lingual logic
25266 requirements. Consider this example:
25268 @smallexample @c ada
25269 with Init_Constants;
25270 package Constants is
25271    X : Integer := 0;
25272    Y : Integer := 0;
25273 end Constants;
25275 package Init_Constants is
25276    procedure P; -- require a body
25277 end Init_Constants;
25279 with Constants;
25280 package body Init_Constants is
25281    procedure P is begin null; end;
25282 begin
25283    Constants.X := 3;
25284    Constants.Y := 4;
25285 end Init_Constants;
25287 with Constants;
25288 package Calc is
25289    Z : Integer := Constants.X + Constants.Y;
25290 end Calc;
25292 with Calc;
25293 with Text_IO; use Text_IO;
25294 procedure Main is
25295 begin
25296    Put_Line (Calc.Z'Img);
25297 end Main;
25298 @end smallexample
25300 @noindent
25301 In this example, there is more than one valid order of elaboration. For
25302 example both the following are correct orders:
25304 @smallexample
25305 Init_Constants spec
25306 Constants spec
25307 Calc spec
25308 Init_Constants body
25309 Main body
25311   and
25313 Init_Constants spec
25314 Init_Constants body
25315 Constants spec
25316 Calc spec
25317 Main body
25318 @end smallexample
25320 @noindent
25321 There is no language rule to prefer one or the other, both are correct
25322 from an order of elaboration point of view. But the programmatic effects
25323 of the two orders are very different. In the first, the elaboration routine
25324 of @code{Calc} initializes @code{Z} to zero, and then the main program
25325 runs with this value of zero. But in the second order, the elaboration
25326 routine of @code{Calc} runs after the body of Init_Constants has set
25327 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
25328 runs.
25330 One could perhaps by applying pretty clever non-artificial intelligence
25331 to the situation guess that it is more likely that the second order of
25332 elaboration is the one desired, but there is no formal linguistic reason
25333 to prefer one over the other. In fact in this particular case, GNAT will
25334 prefer the second order, because of the rule that bodies are elaborated
25335 as soon as possible, but it's just luck that this is what was wanted
25336 (if indeed the second order was preferred).
25338 If the program cares about the order of elaboration routines in a case like
25339 this, it is important to specify the order required. In this particular
25340 case, that could have been achieved by adding to the spec of Calc:
25342 @smallexample @c ada
25343 pragma Elaborate_All (Constants);
25344 @end smallexample
25346 @noindent
25347 which requires that the body (if any) and spec of @code{Constants},
25348 as well as the body and spec of any unit @code{with}'ed by
25349 @code{Constants} be elaborated before @code{Calc} is elaborated.
25351 Clearly no automatic method can always guess which alternative you require,
25352 and if you are working with legacy code that had constraints of this kind
25353 which were not properly specified by adding @code{Elaborate} or
25354 @code{Elaborate_All} pragmas, then indeed it is possible that two different
25355 compilers can choose different orders.
25357 The @code{gnatbind}
25358 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
25359 out problems. This switch causes bodies to be elaborated as late as possible
25360 instead of as early as possible. In the example above, it would have forced
25361 the choice of the first elaboration order. If you get different results
25362 when using this switch, and particularly if one set of results is right,
25363 and one is wrong as far as you are concerned, it shows that you have some
25364 missing @code{Elaborate} pragmas. For the example above, we have the
25365 following output:
25367 @smallexample
25368 gnatmake -f -q main
25369 main
25371 gnatmake -f -q main -bargs -p
25372 main
25374 @end smallexample
25376 @noindent
25377 It is of course quite unlikely that both these results are correct, so
25378 it is up to you in a case like this to investigate the source of the
25379 difference, by looking at the two elaboration orders that are chosen,
25380 and figuring out which is correct, and then adding the necessary
25381 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
25383 @node Inline Assembler
25384 @appendix Inline Assembler
25386 @noindent
25387 If you need to write low-level software that interacts directly
25388 with the hardware, Ada provides two ways to incorporate assembly
25389 language code into your program.  First, you can import and invoke
25390 external routines written in assembly language, an Ada feature fully
25391 supported by GNAT.  However, for small sections of code it may be simpler
25392 or more efficient to include assembly language statements directly
25393 in your Ada source program, using the facilities of the implementation-defined
25394 package @code{System.Machine_Code}, which incorporates the gcc
25395 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
25396 including the following:
25398 @itemize @bullet
25399 @item No need to use non-Ada tools
25400 @item Consistent interface over different targets
25401 @item Automatic usage of the proper calling conventions
25402 @item Access to Ada constants and variables
25403 @item Definition of intrinsic routines
25404 @item Possibility of inlining a subprogram comprising assembler code
25405 @item Code optimizer can take Inline Assembler code into account
25406 @end itemize
25408 This chapter presents a series of examples to show you how to use
25409 the Inline Assembler.  Although it focuses on the Intel x86,
25410 the general approach applies also to other processors.
25411 It is assumed that you are familiar with Ada
25412 and with assembly language programming.
25414 @menu
25415 * Basic Assembler Syntax::
25416 * A Simple Example of Inline Assembler::
25417 * Output Variables in Inline Assembler::
25418 * Input Variables in Inline Assembler::
25419 * Inlining Inline Assembler Code::
25420 * Other Asm Functionality::
25421 @end menu
25423 @c ---------------------------------------------------------------------------
25424 @node Basic Assembler Syntax
25425 @section Basic Assembler Syntax
25427 @noindent
25428 The assembler used by GNAT and gcc is based not on the Intel assembly
25429 language, but rather on a language that descends from the AT&T Unix
25430 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
25431 The following table summarizes the main features of @emph{as} syntax
25432 and points out the differences from the Intel conventions.
25433 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
25434 pre-processor) documentation for further information.
25436 @table @asis
25437 @item Register names
25438 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
25440 Intel: No extra punctuation; for example @code{eax}
25442 @item Immediate operand
25443 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
25445 Intel: No extra punctuation; for example @code{4}
25447 @item Address
25448 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
25450 Intel: No extra punctuation; for example @code{loc}
25452 @item Memory contents
25453 gcc / @emph{as}: No extra punctuation; for example @code{loc}
25455 Intel: Square brackets; for example @code{[loc]}
25457 @item Register contents
25458 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
25460 Intel: Square brackets; for example @code{[eax]}
25462 @item Hexadecimal numbers
25463 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
25465 Intel: Trailing ``h''; for example @code{A0h}
25467 @item Operand size
25468 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
25469 a 16-bit word
25471 Intel: Implicit, deduced by assembler; for example @code{mov}
25473 @item Instruction repetition
25474 gcc / @emph{as}: Split into two lines; for example
25476 @code{rep}
25478 @code{stosl}
25480 Intel: Keep on one line; for example @code{rep stosl}
25482 @item Order of operands
25483 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
25485 Intel: Destination first; for example @code{mov eax, 4}
25486 @end table
25488 @c ---------------------------------------------------------------------------
25489 @node A Simple Example of Inline Assembler
25490 @section A Simple Example of Inline Assembler
25492 @noindent
25493 The following example will generate a single assembly language statement,
25494 @code{nop}, which does nothing.  Despite its lack of run-time effect,
25495 the example will be useful in illustrating the basics of
25496 the Inline Assembler facility.
25498 @smallexample @c ada
25499 @group
25500 with System.Machine_Code; use System.Machine_Code;
25501 procedure Nothing is
25502 begin
25503    Asm ("nop");
25504 end Nothing;
25505 @end group
25506 @end smallexample
25508 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
25509 here it takes one parameter, a @emph{template string} that must be a static
25510 expression and that will form the generated instruction.
25511 @code{Asm} may be regarded as a compile-time procedure that parses
25512 the template string and additional parameters (none here),
25513 from which it generates a sequence of assembly language instructions.
25515 The examples in this chapter will illustrate several of the forms
25516 for invoking @code{Asm}; a complete specification of the syntax
25517 is found in the @cite{GNAT Reference Manual}.
25519 Under the standard GNAT conventions, the @code{Nothing} procedure
25520 should be in a file named @file{nothing.adb}.
25521 You can build the executable in the usual way:
25522 @smallexample
25523 gnatmake nothing
25524 @end smallexample
25525 However, the interesting aspect of this example is not its run-time behavior
25526 but rather the generated assembly code.
25527 To see this output, invoke the compiler as follows:
25528 @smallexample
25529    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
25530 @end smallexample
25531 where the options are:
25533 @table @code
25534 @item -c
25535 compile only (no bind or link)
25536 @item -S
25537 generate assembler listing
25538 @item -fomit-frame-pointer
25539 do not set up separate stack frames
25540 @item -gnatp
25541 do not add runtime checks
25542 @end table
25544 This gives a human-readable assembler version of the code. The resulting
25545 file will have the same name as the Ada source file, but with a @code{.s}
25546 extension. In our example, the file @file{nothing.s} has the following
25547 contents:
25549 @smallexample
25550 @group
25551 .file "nothing.adb"
25552 gcc2_compiled.:
25553 ___gnu_compiled_ada:
25554 .text
25555    .align 4
25556 .globl __ada_nothing
25557 __ada_nothing:
25558 #APP
25559    nop
25560 #NO_APP
25561    jmp L1
25562    .align 2,0x90
25564    ret
25565 @end group
25566 @end smallexample
25568 The assembly code you included is clearly indicated by
25569 the compiler, between the @code{#APP} and @code{#NO_APP}
25570 delimiters. The character before the 'APP' and 'NOAPP'
25571 can differ on different targets. For example, GNU/Linux uses '#APP' while
25572 on NT you will see '/APP'.
25574 If you make a mistake in your assembler code (such as using the
25575 wrong size modifier, or using a wrong operand for the instruction) GNAT
25576 will report this error in a temporary file, which will be deleted when
25577 the compilation is finished.  Generating an assembler file will help
25578 in such cases, since you can assemble this file separately using the
25579 @emph{as} assembler that comes with gcc.
25581 Assembling the file using the command
25583 @smallexample
25584 as @file{nothing.s}
25585 @end smallexample
25586 @noindent
25587 will give you error messages whose lines correspond to the assembler
25588 input file, so you can easily find and correct any mistakes you made.
25589 If there are no errors, @emph{as} will generate an object file
25590 @file{nothing.out}.
25592 @c ---------------------------------------------------------------------------
25593 @node Output Variables in Inline Assembler
25594 @section Output Variables in Inline Assembler
25596 @noindent
25597 The examples in this section, showing how to access the processor flags,
25598 illustrate how to specify the destination operands for assembly language
25599 statements.
25601 @smallexample @c ada
25602 @group
25603 with Interfaces; use Interfaces;
25604 with Ada.Text_IO; use Ada.Text_IO;
25605 with System.Machine_Code; use System.Machine_Code;
25606 procedure Get_Flags is
25607    Flags : Unsigned_32;
25608    use ASCII;
25609 begin
25610    Asm ("pushfl"          & LF & HT & -- push flags on stack
25611         "popl %%eax"      & LF & HT & -- load eax with flags
25612         "movl %%eax, %0",             -- store flags in variable
25613         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25614    Put_Line ("Flags register:" & Flags'Img);
25615 end Get_Flags;
25616 @end group
25617 @end smallexample
25619 In order to have a nicely aligned assembly listing, we have separated
25620 multiple assembler statements in the Asm template string with linefeed
25621 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
25622 The resulting section of the assembly output file is:
25624 @smallexample
25625 @group
25626 #APP
25627    pushfl
25628    popl %eax
25629    movl %eax, -40(%ebp)
25630 #NO_APP
25631 @end group
25632 @end smallexample
25634 It would have been legal to write the Asm invocation as:
25636 @smallexample
25637 Asm ("pushfl popl %%eax movl %%eax, %0")
25638 @end smallexample
25640 but in the generated assembler file, this would come out as:
25642 @smallexample
25643 #APP
25644    pushfl popl %eax movl %eax, -40(%ebp)
25645 #NO_APP
25646 @end smallexample
25648 which is not so convenient for the human reader.
25650 We use Ada comments
25651 at the end of each line to explain what the assembler instructions
25652 actually do.  This is a useful convention.
25654 When writing Inline Assembler instructions, you need to precede each register
25655 and variable name with a percent sign.  Since the assembler already requires
25656 a percent sign at the beginning of a register name, you need two consecutive
25657 percent signs for such names in the Asm template string, thus @code{%%eax}.
25658 In the generated assembly code, one of the percent signs will be stripped off.
25660 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
25661 variables: operands you later define using @code{Input} or @code{Output}
25662 parameters to @code{Asm}.
25663 An output variable is illustrated in
25664 the third statement in the Asm template string:
25665 @smallexample
25666 movl %%eax, %0
25667 @end smallexample
25668 The intent is to store the contents of the eax register in a variable that can
25669 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
25670 necessarily work, since the compiler might optimize by using a register
25671 to hold Flags, and the expansion of the @code{movl} instruction would not be
25672 aware of this optimization.  The solution is not to store the result directly
25673 but rather to advise the compiler to choose the correct operand form;
25674 that is the purpose of the @code{%0} output variable.
25676 Information about the output variable is supplied in the @code{Outputs}
25677 parameter to @code{Asm}:
25678 @smallexample
25679 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25680 @end smallexample
25682 The output is defined by the @code{Asm_Output} attribute of the target type;
25683 the general format is
25684 @smallexample
25685 Type'Asm_Output (constraint_string, variable_name)
25686 @end smallexample
25688 The constraint string directs the compiler how
25689 to store/access the associated variable.  In the example
25690 @smallexample
25691 Unsigned_32'Asm_Output ("=m", Flags);
25692 @end smallexample
25693 the @code{"m"} (memory) constraint tells the compiler that the variable
25694 @code{Flags} should be stored in a memory variable, thus preventing
25695 the optimizer from keeping it in a register.  In contrast,
25696 @smallexample
25697 Unsigned_32'Asm_Output ("=r", Flags);
25698 @end smallexample
25699 uses the @code{"r"} (register) constraint, telling the compiler to
25700 store the variable in a register.
25702 If the constraint is preceded by the equal character (@strong{=}), it tells
25703 the compiler that the variable will be used to store data into it.
25705 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
25706 allowing the optimizer to choose whatever it deems best.
25708 There are a fairly large number of constraints, but the ones that are
25709 most useful (for the Intel x86 processor) are the following:
25711 @table @code
25712 @item =
25713 output constraint
25714 @item g
25715 global (i.e. can be stored anywhere)
25716 @item m
25717 in memory
25718 @item I
25719 a constant
25720 @item a
25721 use eax
25722 @item b
25723 use ebx
25724 @item c
25725 use ecx
25726 @item d
25727 use edx
25728 @item S
25729 use esi
25730 @item D
25731 use edi
25732 @item r
25733 use one of eax, ebx, ecx or edx
25734 @item q
25735 use one of eax, ebx, ecx, edx, esi or edi
25736 @end table
25738 The full set of constraints is described in the gcc and @emph{as}
25739 documentation; note that it is possible to combine certain constraints
25740 in one constraint string.
25742 You specify the association of an output variable with an assembler operand
25743 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
25744 integer.  Thus in
25745 @smallexample @c ada
25746 @group
25747 Asm ("pushfl"          & LF & HT & -- push flags on stack
25748      "popl %%eax"      & LF & HT & -- load eax with flags
25749      "movl %%eax, %0",             -- store flags in variable
25750      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25751 @end group
25752 @end smallexample
25753 @noindent
25754 @code{%0} will be replaced in the expanded code by the appropriate operand,
25755 whatever
25756 the compiler decided for the @code{Flags} variable.
25758 In general, you may have any number of output variables:
25759 @itemize @bullet
25760 @item
25761 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
25762 @item
25763 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
25764 of @code{Asm_Output} attributes
25765 @end itemize
25767 For example:
25768 @smallexample @c ada
25769 @group
25770 Asm ("movl %%eax, %0" & LF & HT &
25771      "movl %%ebx, %1" & LF & HT &
25772      "movl %%ecx, %2",
25773      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
25774                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
25775                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
25776 @end group
25777 @end smallexample
25778 @noindent
25779 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
25780 in the Ada program.
25782 As a variation on the @code{Get_Flags} example, we can use the constraints
25783 string to direct the compiler to store the eax register into the @code{Flags}
25784 variable, instead of including the store instruction explicitly in the
25785 @code{Asm} template string:
25787 @smallexample @c ada
25788 @group
25789 with Interfaces; use Interfaces;
25790 with Ada.Text_IO; use Ada.Text_IO;
25791 with System.Machine_Code; use System.Machine_Code;
25792 procedure Get_Flags_2 is
25793    Flags : Unsigned_32;
25794    use ASCII;
25795 begin
25796    Asm ("pushfl"      & LF & HT & -- push flags on stack
25797         "popl %%eax",             -- save flags in eax
25798         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
25799    Put_Line ("Flags register:" & Flags'Img);
25800 end Get_Flags_2;
25801 @end group
25802 @end smallexample
25804 @noindent
25805 The @code{"a"} constraint tells the compiler that the @code{Flags}
25806 variable will come from the eax register. Here is the resulting code:
25808 @smallexample
25809 @group
25810 #APP
25811    pushfl
25812    popl %eax
25813 #NO_APP
25814    movl %eax,-40(%ebp)
25815 @end group
25816 @end smallexample
25818 @noindent
25819 The compiler generated the store of eax into Flags after
25820 expanding the assembler code.
25822 Actually, there was no need to pop the flags into the eax register;
25823 more simply, we could just pop the flags directly into the program variable:
25825 @smallexample @c ada
25826 @group
25827 with Interfaces; use Interfaces;
25828 with Ada.Text_IO; use Ada.Text_IO;
25829 with System.Machine_Code; use System.Machine_Code;
25830 procedure Get_Flags_3 is
25831    Flags : Unsigned_32;
25832    use ASCII;
25833 begin
25834    Asm ("pushfl"  & LF & HT & -- push flags on stack
25835         "pop %0",             -- save flags in Flags
25836         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25837    Put_Line ("Flags register:" & Flags'Img);
25838 end Get_Flags_3;
25839 @end group
25840 @end smallexample
25842 @c ---------------------------------------------------------------------------
25843 @node Input Variables in Inline Assembler
25844 @section Input Variables in Inline Assembler
25846 @noindent
25847 The example in this section illustrates how to specify the source operands
25848 for assembly language statements.
25849 The program simply increments its input value by 1:
25851 @smallexample @c ada
25852 @group
25853 with Interfaces; use Interfaces;
25854 with Ada.Text_IO; use Ada.Text_IO;
25855 with System.Machine_Code; use System.Machine_Code;
25856 procedure Increment is
25858    function Incr (Value : Unsigned_32) return Unsigned_32 is
25859       Result : Unsigned_32;
25860    begin
25861       Asm ("incl %0",
25862            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25863            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25864       return Result;
25865    end Incr;
25867    Value : Unsigned_32;
25869 begin
25870    Value := 5;
25871    Put_Line ("Value before is" & Value'Img);
25872    Value := Incr (Value);
25873    Put_Line ("Value after is" & Value'Img);
25874 end Increment;
25875 @end group
25876 @end smallexample
25878 The @code{Outputs} parameter to @code{Asm} specifies
25879 that the result will be in the eax register and that it is to be stored
25880 in the @code{Result} variable.
25882 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25883 but with an @code{Asm_Input} attribute.
25884 The @code{"="} constraint, indicating an output value, is not present.
25886 You can have multiple input variables, in the same way that you can have more
25887 than one output variable.
25889 The parameter count (%0, %1) etc, now starts at the first input
25890 statement, and continues with the output statements.
25891 When both parameters use the same variable, the
25892 compiler will treat them as the same %n operand, which is the case here.
25894 Just as the @code{Outputs} parameter causes the register to be stored into the
25895 target variable after execution of the assembler statements, so does the
25896 @code{Inputs} parameter cause its variable to be loaded into the register
25897 before execution of the assembler statements.
25899 Thus the effect of the @code{Asm} invocation is:
25900 @enumerate
25901 @item load the 32-bit value of @code{Value} into eax
25902 @item execute the @code{incl %eax} instruction
25903 @item store the contents of eax into the @code{Result} variable
25904 @end enumerate
25906 The resulting assembler file (with @option{-O2} optimization) contains:
25907 @smallexample
25908 @group
25909 _increment__incr.1:
25910    subl $4,%esp
25911    movl 8(%esp),%eax
25912 #APP
25913    incl %eax
25914 #NO_APP
25915    movl %eax,%edx
25916    movl %ecx,(%esp)
25917    addl $4,%esp
25918    ret
25919 @end group
25920 @end smallexample
25922 @c ---------------------------------------------------------------------------
25923 @node Inlining Inline Assembler Code
25924 @section Inlining Inline Assembler Code
25926 @noindent
25927 For a short subprogram such as the @code{Incr} function in the previous
25928 section, the overhead of the call and return (creating / deleting the stack
25929 frame) can be significant, compared to the amount of code in the subprogram
25930 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25931 which directs the compiler to expand invocations of the subprogram at the
25932 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25933 Here is the resulting program:
25935 @smallexample @c ada
25936 @group
25937 with Interfaces; use Interfaces;
25938 with Ada.Text_IO; use Ada.Text_IO;
25939 with System.Machine_Code; use System.Machine_Code;
25940 procedure Increment_2 is
25942    function Incr (Value : Unsigned_32) return Unsigned_32 is
25943       Result : Unsigned_32;
25944    begin
25945       Asm ("incl %0",
25946            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25947            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25948       return Result;
25949    end Incr;
25950    pragma Inline (Increment);
25952    Value : Unsigned_32;
25954 begin
25955    Value := 5;
25956    Put_Line ("Value before is" & Value'Img);
25957    Value := Increment (Value);
25958    Put_Line ("Value after is" & Value'Img);
25959 end Increment_2;
25960 @end group
25961 @end smallexample
25963 Compile the program with both optimization (@option{-O2}) and inlining
25964 enabled (@option{-gnatpn} instead of @option{-gnatp}).
25966 The @code{Incr} function is still compiled as usual, but at the
25967 point in @code{Increment} where our function used to be called:
25969 @smallexample
25970 @group
25971 pushl %edi
25972 call _increment__incr.1
25973 @end group
25974 @end smallexample
25976 @noindent
25977 the code for the function body directly appears:
25979 @smallexample
25980 @group
25981 movl %esi,%eax
25982 #APP
25983    incl %eax
25984 #NO_APP
25985    movl %eax,%edx
25986 @end group
25987 @end smallexample
25989 @noindent
25990 thus saving the overhead of stack frame setup and an out-of-line call.
25992 @c ---------------------------------------------------------------------------
25993 @node Other Asm Functionality
25994 @section Other @code{Asm} Functionality
25996 @noindent
25997 This section describes two important parameters to the @code{Asm}
25998 procedure: @code{Clobber}, which identifies register usage;
25999 and @code{Volatile}, which inhibits unwanted optimizations.
26001 @menu
26002 * The Clobber Parameter::
26003 * The Volatile Parameter::
26004 @end menu
26006 @c ---------------------------------------------------------------------------
26007 @node The Clobber Parameter
26008 @subsection The @code{Clobber} Parameter
26010 @noindent
26011 One of the dangers of intermixing assembly language and a compiled language
26012 such as Ada is that the compiler needs to be aware of which registers are
26013 being used by the assembly code.  In some cases, such as the earlier examples,
26014 the constraint string is sufficient to indicate register usage (e.g.,
26015 @code{"a"} for
26016 the eax register).  But more generally, the compiler needs an explicit
26017 identification of the registers that are used by the Inline Assembly
26018 statements.
26020 Using a register that the compiler doesn't know about
26021 could be a side effect of an instruction (like @code{mull}
26022 storing its result in both eax and edx).
26023 It can also arise from explicit register usage in your
26024 assembly code; for example:
26025 @smallexample
26026 @group
26027 Asm ("movl %0, %%ebx" & LF & HT &
26028      "movl %%ebx, %1",
26029      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26030      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
26031 @end group
26032 @end smallexample
26033 @noindent
26034 where the compiler (since it does not analyze the @code{Asm} template string)
26035 does not know you are using the ebx register.
26037 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
26038 to identify the registers that will be used by your assembly code:
26040 @smallexample
26041 @group
26042 Asm ("movl %0, %%ebx" & LF & HT &
26043      "movl %%ebx, %1",
26044      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
26045      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
26046      Clobber => "ebx");
26047 @end group
26048 @end smallexample
26050 The Clobber parameter is a static string expression specifying the
26051 register(s) you are using.  Note that register names are @emph{not} prefixed
26052 by a percent sign. Also, if more than one register is used then their names
26053 are separated by commas; e.g., @code{"eax, ebx"}
26055 The @code{Clobber} parameter has several additional uses:
26056 @enumerate
26057 @item Use ``register'' name @code{cc} to indicate that flags might have changed
26058 @item Use ``register'' name @code{memory} if you changed a memory location
26059 @end enumerate
26061 @c ---------------------------------------------------------------------------
26062 @node The Volatile Parameter
26063 @subsection The @code{Volatile} Parameter
26064 @cindex Volatile parameter
26066 @noindent
26067 Compiler optimizations in the presence of Inline Assembler may sometimes have
26068 unwanted effects.  For example, when an @code{Asm} invocation with an input
26069 variable is inside a loop, the compiler might move the loading of the input
26070 variable outside the loop, regarding it as a one-time initialization.
26072 If this effect is not desired, you can disable such optimizations by setting
26073 the @code{Volatile} parameter to @code{True}; for example:
26075 @smallexample @c ada
26076 @group
26077 Asm ("movl %0, %%ebx" & LF & HT &
26078      "movl %%ebx, %1",
26079      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
26080      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
26081      Clobber  => "ebx",
26082      Volatile => True);
26083 @end group
26084 @end smallexample
26086 By default, @code{Volatile} is set to @code{False} unless there is no
26087 @code{Outputs} parameter.
26089 Although setting @code{Volatile} to @code{True} prevents unwanted
26090 optimizations, it will also disable other optimizations that might be
26091 important for efficiency. In general, you should set @code{Volatile}
26092 to @code{True} only if the compiler's optimizations have created
26093 problems.
26094 @c END OF INLINE ASSEMBLER CHAPTER
26095 @c ===============================
26097 @c ***********************************
26098 @c * Compatibility and Porting Guide *
26099 @c ***********************************
26100 @node Compatibility and Porting Guide
26101 @appendix Compatibility and Porting Guide
26103 @noindent
26104 This chapter describes the compatibility issues that may arise between
26105 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
26106 can expedite porting
26107 applications developed in other Ada environments.
26109 @menu
26110 * Compatibility with Ada 83::
26111 * Implementation-dependent characteristics::
26112 * Compatibility with Other Ada 95 Systems::
26113 * Representation Clauses::
26114 @ifclear vms
26115 @c Brief section is only in non-VMS version
26116 @c Full chapter is in VMS version
26117 * Compatibility with HP Ada 83::
26118 @end ifclear
26119 @ifset vms
26120 * Transitioning from Alpha to I64 OpenVMS::
26121 @end ifset
26122 @end menu
26124 @node Compatibility with Ada 83
26125 @section Compatibility with Ada 83
26126 @cindex Compatibility (between Ada 83 and Ada 95)
26128 @noindent
26129 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
26130 particular, the design intention is that the difficulties associated
26131 with moving from Ada 83 to Ada 95 should be no greater than those
26132 that occur when moving from one Ada 83 system to another.
26134 However, there are a number of points at which there are minor
26135 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26136 full details of these issues,
26137 and should be consulted for a complete treatment.
26138 In practice the
26139 following subsections treat the most likely issues to be encountered.
26141 @menu
26142 * Legal Ada 83 programs that are illegal in Ada 95::
26143 * More deterministic semantics::
26144 * Changed semantics::
26145 * Other language compatibility issues::
26146 @end menu
26148 @node Legal Ada 83 programs that are illegal in Ada 95
26149 @subsection Legal Ada 83 programs that are illegal in Ada 95
26151 @table @asis
26152 @item Character literals
26153 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26154 @code{Wide_Character} as a new predefined character type, some uses of
26155 character literals that were legal in Ada 83 are illegal in Ada 95.
26156 For example:
26157 @smallexample @c ada
26158    for Char in 'A' .. 'Z' loop ... end loop;
26159 @end smallexample
26160 @noindent
26161 The problem is that @code{'A'} and @code{'Z'} could be from either
26162 @code{Character} or @code{Wide_Character}.  The simplest correction
26163 is to make the type explicit; e.g.:
26164 @smallexample @c ada
26165    for Char in Character range 'A' .. 'Z' loop ... end loop;
26166 @end smallexample
26168 @item New reserved words
26169 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26170 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26171 Existing Ada 83 code using any of these identifiers must be edited to
26172 use some alternative name.
26174 @item Freezing rules
26175 The rules in Ada 95 are slightly different with regard to the point at
26176 which entities are frozen, and representation pragmas and clauses are
26177 not permitted past the freeze point.  This shows up most typically in
26178 the form of an error message complaining that a representation item
26179 appears too late, and the appropriate corrective action is to move
26180 the item nearer to the declaration of the entity to which it refers.
26182 A particular case is that representation pragmas
26183 @ifset vms
26184 (including the
26185 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
26186 @end ifset
26187 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26188 declaration must be introduced to which the pragma can be applied.
26190 @item Optional bodies for library packages
26191 In Ada 83, a package that did not require a package body was nevertheless
26192 allowed to have one.  This lead to certain surprises in compiling large
26193 systems (situations in which the body could be unexpectedly ignored by the
26194 binder).  In Ada 95, if a package does not require a body then it is not
26195 permitted to have a body.  To fix this problem, simply remove a redundant
26196 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26197 into the spec that makes the body required.  One approach is to add a private
26198 part to the package declaration (if necessary), and define a parameterless
26199 procedure called @code{Requires_Body}, which must then be given a dummy
26200 procedure body in the package body, which then becomes required.
26201 Another approach (assuming that this does not introduce elaboration
26202 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26203 since one effect of this pragma is to require the presence of a package body.
26205 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26206 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26207 @code{Constraint_Error}.
26208 This means that it is illegal to have separate exception handlers for
26209 the two exceptions.  The fix is simply to remove the handler for the
26210 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26211 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26213 @item Indefinite subtypes in generics
26214 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26215 as the actual for a generic formal private type, but then the instantiation
26216 would be illegal if there were any instances of declarations of variables
26217 of this type in the generic body.  In Ada 95, to avoid this clear violation
26218 of the methodological principle known as the ``contract model'',
26219 the generic declaration explicitly indicates whether
26220 or not such instantiations are permitted.  If a generic formal parameter
26221 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26222 type name, then it can be instantiated with indefinite types, but no
26223 stand-alone variables can be declared of this type.  Any attempt to declare
26224 such a variable will result in an illegality at the time the generic is
26225 declared.  If the @code{(<>)} notation is not used, then it is illegal
26226 to instantiate the generic with an indefinite type.
26227 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26228 It will show up as a compile time error, and
26229 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26230 @end table
26232 @node More deterministic semantics
26233 @subsection More deterministic semantics
26235 @table @asis
26236 @item Conversions
26237 Conversions from real types to integer types round away from 0.  In Ada 83
26238 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26239 implementation freedom was intended to support unbiased rounding in
26240 statistical applications, but in practice it interfered with portability.
26241 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26242 is required.  Numeric code may be affected by this change in semantics.
26243 Note, though, that this issue is no worse than already existed in Ada 83
26244 when porting code from one vendor to another.
26246 @item Tasking
26247 The Real-Time Annex introduces a set of policies that define the behavior of
26248 features that were implementation dependent in Ada 83, such as the order in
26249 which open select branches are executed.
26250 @end table
26252 @node Changed semantics
26253 @subsection Changed semantics
26255 @noindent
26256 The worst kind of incompatibility is one where a program that is legal in
26257 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26258 possible in Ada 83.  Fortunately this is extremely rare, but the one
26259 situation that you should be alert to is the change in the predefined type
26260 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26262 @table @asis
26263 @item range of @code{Character}
26264 The range of @code{Standard.Character} is now the full 256 characters
26265 of Latin-1, whereas in most Ada 83 implementations it was restricted
26266 to 128 characters. Although some of the effects of
26267 this change will be manifest in compile-time rejection of legal
26268 Ada 83 programs it is possible for a working Ada 83 program to have
26269 a different effect in Ada 95, one that was not permitted in Ada 83.
26270 As an example, the expression
26271 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26272 delivers @code{255} as its value.
26273 In general, you should look at the logic of any
26274 character-processing Ada 83 program and see whether it needs to be adapted
26275 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26276 character handling package that may be relevant if code needs to be adapted
26277 to account for the additional Latin-1 elements.
26278 The desirable fix is to
26279 modify the program to accommodate the full character set, but in some cases
26280 it may be convenient to define a subtype or derived type of Character that
26281 covers only the restricted range.
26282 @cindex Latin-1
26283 @end table
26285 @node Other language compatibility issues
26286 @subsection Other language compatibility issues
26287 @table @asis
26288 @item @option{-gnat83 switch}
26289 All implementations of GNAT provide a switch that causes GNAT to operate
26290 in Ada 83 mode.  In this mode, some but not all compatibility problems
26291 of the type described above are handled automatically.  For example, the
26292 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
26293 However,
26294 in practice, it is usually advisable to make the necessary modifications
26295 to the program to remove the need for using this switch.
26296 See @ref{Compiling Different Versions of Ada}.
26298 @item Support for removed Ada 83 pragmas and attributes
26299 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
26300 generally because they have been replaced by other mechanisms.  Ada 95
26301 compilers are allowed, but not required, to implement these missing
26302 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
26303 such pragmas and attributes, eliminating this compatibility concern.  These
26304 include @code{pragma Interface} and the floating point type attributes
26305 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26306 @end table
26308 @node Implementation-dependent characteristics
26309 @section Implementation-dependent characteristics
26310 @noindent
26311 Although the Ada language defines the semantics of each construct as
26312 precisely as practical, in some situations (for example for reasons of
26313 efficiency, or where the effect is heavily dependent on the host or target
26314 platform) the implementation is allowed some freedom.  In porting Ada 83
26315 code to GNAT, you need to be aware of whether / how the existing code
26316 exercised such implementation dependencies.  Such characteristics fall into
26317 several categories, and GNAT offers specific support in assisting the
26318 transition from certain Ada 83 compilers.
26320 @menu
26321 * Implementation-defined pragmas::
26322 * Implementation-defined attributes::
26323 * Libraries::
26324 * Elaboration order::
26325 * Target-specific aspects::
26326 @end menu
26328 @node Implementation-defined pragmas
26329 @subsection Implementation-defined pragmas
26331 @noindent
26332 Ada compilers are allowed to supplement the language-defined pragmas, and
26333 these are a potential source of non-portability.  All GNAT-defined pragmas
26334 are described in the GNAT Reference Manual, and these include several that
26335 are specifically intended to correspond to other vendors' Ada 83 pragmas.
26336 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26338 compatibility with HP Ada 83, GNAT supplies the pragmas
26339 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26340 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26341 and @code{Volatile}.
26342 Other relevant pragmas include @code{External} and @code{Link_With}.
26343 Some vendor-specific
26344 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26345 recognized, thus
26346 avoiding compiler rejection of units that contain such pragmas; they are not
26347 relevant in a GNAT context and hence are not otherwise implemented.
26349 @node Implementation-defined attributes
26350 @subsection Implementation-defined attributes
26352 Analogous to pragmas, the set of attributes may be extended by an
26353 implementation.  All GNAT-defined attributes are described in the
26354 @cite{GNAT Reference Manual}, and these include several that are specifically
26355 intended
26356 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26357 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
26358 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26359 @code{Type_Class}.
26361 @node Libraries
26362 @subsection Libraries
26363 @noindent
26364 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26365 code uses vendor-specific libraries then there are several ways to manage
26366 this in Ada 95:
26367 @enumerate
26368 @item
26369 If the source code for the libraries (specifications and bodies) are
26370 available, then the libraries can be migrated in the same way as the
26371 application.
26372 @item
26373 If the source code for the specifications but not the bodies are
26374 available, then you can reimplement the bodies.
26375 @item
26376 Some new Ada 95 features obviate the need for library support.  For
26377 example most Ada 83 vendors supplied a package for unsigned integers.  The
26378 Ada 95 modular type feature is the preferred way to handle this need, so
26379 instead of migrating or reimplementing the unsigned integer package it may
26380 be preferable to retrofit the application using modular types.
26381 @end enumerate
26383 @node Elaboration order
26384 @subsection Elaboration order
26385 @noindent
26386 The implementation can choose any elaboration order consistent with the unit
26387 dependency relationship.  This freedom means that some orders can result in
26388 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26389 to invoke a subprogram its body has been elaborated, or to instantiate a
26390 generic before the generic body has been elaborated.  By default GNAT
26391 attempts to choose a safe order (one that will not encounter access before
26392 elaboration problems) by implicitly inserting @code{Elaborate} or
26393 @code{Elaborate_All} pragmas where
26394 needed.  However, this can lead to the creation of elaboration circularities
26395 and a resulting rejection of the program by gnatbind.  This issue is
26396 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26397 In brief, there are several
26398 ways to deal with this situation:
26400 @itemize @bullet
26401 @item
26402 Modify the program to eliminate the circularities, e.g. by moving
26403 elaboration-time code into explicitly-invoked procedures
26404 @item
26405 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26406 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26407 @code{Elaborate_All}
26408 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26409 (by selectively suppressing elaboration checks via pragma
26410 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26411 @end itemize
26413 @node Target-specific aspects
26414 @subsection Target-specific aspects
26415 @noindent
26416 Low-level applications need to deal with machine addresses, data
26417 representations, interfacing with assembler code, and similar issues.  If
26418 such an Ada 83 application is being ported to different target hardware (for
26419 example where the byte endianness has changed) then you will need to
26420 carefully examine the program logic; the porting effort will heavily depend
26421 on the robustness of the original design.  Moreover, Ada 95 is sometimes
26422 incompatible with typical Ada 83 compiler practices regarding implicit
26423 packing, the meaning of the Size attribute, and the size of access values.
26424 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26426 @node Compatibility with Other Ada 95 Systems
26427 @section Compatibility with Other Ada 95 Systems
26429 @noindent
26430 Providing that programs avoid the use of implementation dependent and
26431 implementation defined features of Ada 95, as documented in the Ada 95
26432 reference manual, there should be a high degree of portability between
26433 GNAT and other Ada 95 systems.  The following are specific items which
26434 have proved troublesome in moving GNAT programs to other Ada 95
26435 compilers, but do not affect porting code to GNAT@.
26437 @table @asis
26438 @item Ada 83 Pragmas and Attributes
26439 Ada 95 compilers are allowed, but not required, to implement the missing
26440 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26441 GNAT implements all such pragmas and attributes, eliminating this as
26442 a compatibility concern, but some other Ada 95 compilers reject these
26443 pragmas and attributes.
26445 @item Special-needs Annexes
26446 GNAT implements the full set of special needs annexes.  At the
26447 current time, it is the only Ada 95 compiler to do so.  This means that
26448 programs making use of these features may not be portable to other Ada
26449 95 compilation systems.
26451 @item Representation Clauses
26452 Some other Ada 95 compilers implement only the minimal set of
26453 representation clauses required by the Ada 95 reference manual.  GNAT goes
26454 far beyond this minimal set, as described in the next section.
26455 @end table
26457 @node Representation Clauses
26458 @section Representation Clauses
26460 @noindent
26461 The Ada 83 reference manual was quite vague in describing both the minimal
26462 required implementation of representation clauses, and also their precise
26463 effects.  The Ada 95 reference manual is much more explicit, but the minimal
26464 set of capabilities required in Ada 95 is quite limited.
26466 GNAT implements the full required set of capabilities described in the
26467 Ada 95 reference manual, but also goes much beyond this, and in particular
26468 an effort has been made to be compatible with existing Ada 83 usage to the
26469 greatest extent possible.
26471 A few cases exist in which Ada 83 compiler behavior is incompatible with
26472 requirements in the Ada 95 reference manual.  These are instances of
26473 intentional or accidental dependence on specific implementation dependent
26474 characteristics of these Ada 83 compilers.  The following is a list of
26475 the cases most likely to arise in existing legacy Ada 83 code.
26477 @table @asis
26478 @item Implicit Packing
26479 Some Ada 83 compilers allowed a Size specification to cause implicit
26480 packing of an array or record.  This could cause expensive implicit
26481 conversions for change of representation in the presence of derived
26482 types, and the Ada design intends to avoid this possibility.
26483 Subsequent AI's were issued to make it clear that such implicit
26484 change of representation in response to a Size clause is inadvisable,
26485 and this recommendation is represented explicitly in the Ada 95 RM
26486 as implementation advice that is followed by GNAT@.
26487 The problem will show up as an error
26488 message rejecting the size clause.  The fix is simply to provide
26489 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26490 a Component_Size clause.
26492 @item Meaning of Size Attribute
26493 The Size attribute in Ada 95 for discrete types is defined as being the
26494 minimal number of bits required to hold values of the type.  For example,
26495 on a 32-bit machine, the size of Natural will typically be 31 and not
26496 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26497 some 32 in this situation.  This problem will usually show up as a compile
26498 time error, but not always.  It is a good idea to check all uses of the
26499 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26500 Object_Size can provide a useful way of duplicating the behavior of
26501 some Ada 83 compiler systems.
26503 @item Size of Access Types
26504 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26505 and that therefore it will be the same size as a System.Address value.  This
26506 assumption is true for GNAT in most cases with one exception.  For the case of
26507 a pointer to an unconstrained array type (where the bounds may vary from one
26508 value of the access type to another), the default is to use a ``fat pointer'',
26509 which is represented as two separate pointers, one to the bounds, and one to
26510 the array.  This representation has a number of advantages, including improved
26511 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26512 code which makes the assumption that, for example, pointers fit in 32 bits on
26513 a machine with 32-bit addressing.
26515 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26516 access types in this case (where the designated type is an unconstrained array
26517 type).  These thin pointers are indeed the same size as a System.Address value.
26518 To specify a thin pointer, use a size clause for the type, for example:
26520 @smallexample @c ada
26521 type X is access all String;
26522 for X'Size use Standard'Address_Size;
26523 @end smallexample
26525 @noindent
26526 which will cause the type X to be represented using a single pointer.
26527 When using this representation, the bounds are right behind the array.
26528 This representation is slightly less efficient, and does not allow quite
26529 such flexibility in the use of foreign pointers or in using the
26530 Unrestricted_Access attribute to create pointers to non-aliased objects.
26531 But for any standard portable use of the access type it will work in
26532 a functionally correct manner and allow porting of existing code.
26533 Note that another way of forcing a thin pointer representation
26534 is to use a component size clause for the element size in an array,
26535 or a record representation clause for an access field in a record.
26536 @end table
26538 @ifclear vms
26539 @c This brief section is only in the non-VMS version
26540 @c The complete chapter on HP Ada is in the VMS version
26541 @node Compatibility with HP Ada 83
26542 @section Compatibility with HP Ada 83
26544 @noindent
26545 The VMS version of GNAT fully implements all the pragmas and attributes
26546 provided by HP Ada 83, as well as providing the standard HP Ada 83
26547 libraries, including Starlet.  In addition, data layouts and parameter
26548 passing conventions are highly compatible.  This means that porting
26549 existing HP Ada 83 code to GNAT in VMS systems should be easier than
26550 most other porting efforts.  The following are some of the most
26551 significant differences between GNAT and HP Ada 83.
26553 @table @asis
26554 @item Default floating-point representation
26555 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
26556 it is VMS format.  GNAT does implement the necessary pragmas
26557 (Long_Float, Float_Representation) for changing this default.
26559 @item System
26560 The package System in GNAT exactly corresponds to the definition in the
26561 Ada 95 reference manual, which means that it excludes many of the
26562 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
26563 that contains the additional definitions, and a special pragma,
26564 Extend_System allows this package to be treated transparently as an
26565 extension of package System.
26567 @item To_Address
26568 The definitions provided by Aux_DEC are exactly compatible with those
26569 in the HP Ada 83 version of System, with one exception.
26570 HP Ada provides the following declarations:
26572 @smallexample @c ada
26573 TO_ADDRESS (INTEGER)
26574 TO_ADDRESS (UNSIGNED_LONGWORD)
26575 TO_ADDRESS (universal_integer)
26576 @end smallexample
26578 @noindent
26579 The version of TO_ADDRESS taking a universal integer argument is in fact
26580 an extension to Ada 83 not strictly compatible with the reference manual.
26581 In GNAT, we are constrained to be exactly compatible with the standard,
26582 and this means we cannot provide this capability.  In HP Ada 83, the
26583 point of this definition is to deal with a call like:
26585 @smallexample @c ada
26586 TO_ADDRESS (16#12777#);
26587 @end smallexample
26589 @noindent
26590 Normally, according to the Ada 83 standard, one would expect this to be
26591 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26592 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
26593 definition using universal_integer takes precedence.
26595 In GNAT, since the version with universal_integer cannot be supplied, it is
26596 not possible to be 100% compatible.  Since there are many programs using
26597 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26598 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26599 declarations provided in the GNAT version of AUX_Dec are:
26601 @smallexample @c ada
26602 function To_Address (X : Integer) return Address;
26603 pragma Pure_Function (To_Address);
26605 function To_Address_Long (X : Unsigned_Longword)
26606  return Address;
26607 pragma Pure_Function (To_Address_Long);
26608 @end smallexample
26610 @noindent
26611 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26612 change the name to TO_ADDRESS_LONG@.
26614 @item Task_Id values
26615 The Task_Id values assigned will be different in the two systems, and GNAT
26616 does not provide a specified value for the Task_Id of the environment task,
26617 which in GNAT is treated like any other declared task.
26618 @end table
26620 For full details on these and other less significant compatibility issues,
26621 see appendix E of the HP publication entitled @cite{HP Ada, Technical
26622 Overview and Comparison on HP Platforms}.
26624 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
26625 attributes are recognized, although only a subset of them can sensibly
26626 be implemented.  The description of pragmas in the
26627 @cite{GNAT Reference Manual}
26628 indicates whether or not they are applicable to non-VMS systems.
26629 @end ifclear
26631 @ifset vms
26632 @node Transitioning from Alpha to I64 OpenVMS
26633 @section Transitioning from Alpha to I64 OpenVMS
26635 @menu
26636 * Introduction to transitioning::
26637 * Migration of 32 bit code::
26638 * Taking advantage of 64 bit addressing::
26639 * Technical details::
26640 @end menu
26642 @node Introduction to transitioning
26643 @subsection Introduction to transitioning
26645 @noindent
26646 This section is meant to assist users of @value{EDITION}
26647 for Alpha OpenVMS who are planning to transition to the I64 architecture.
26648 @value{EDITION} for Open VMS I64 has been designed to meet
26649 three main goals:
26651 @enumerate
26652 @item
26653 Providing a full conforming implementation of the Ada 95 language
26655 @item
26656 Allowing maximum backward compatibility, thus easing migration of existing
26657 Ada source code
26659 @item
26660 Supplying a path for exploiting the full I64 address range
26661 @end enumerate
26663 @noindent
26664 Ada's strong typing semantics has made it
26665 impractical to have different 32-bit and 64-bit modes. As soon as
26666 one object could possibly be outside the 32-bit address space, this
26667 would make it necessary for the @code{System.Address} type to be 64 bits.
26668 In particular, this would cause inconsistencies if 32-bit code is
26669 called from 64-bit code that raises an exception.
26671 This issue has been resolved by always using 64-bit addressing
26672 at the system level, but allowing for automatic conversions between
26673 32-bit and 64-bit addresses where required. Thus users who
26674 do not currently require 64-bit addressing capabilities, can
26675 recompile their code with only minimal changes (and indeed
26676 if the code is written in portable Ada, with no assumptions about
26677 the size of the @code{Address} type, then no changes at all are necessary).
26678 At the same time,
26679 this approach provides a simple, gradual upgrade path to future
26680 use of larger memories than available for 32-bit systems.
26681 Also, newly written applications or libraries will by default
26682 be fully compatible with future systems exploiting 64-bit
26683 addressing capabilities present in I64.
26685 @ref{Migration of 32 bit code}, will focus on porting applications
26686 that do not require more than 2 GB of
26687 addressable memory. This code will be referred to as
26688 @emph{32-bit code}.
26689 For applications intending to exploit the full I64 address space,
26690 @ref{Taking advantage of 64 bit addressing},
26691 will consider further changes that may be required.
26692 Such code is called @emph{64-bit code} in the
26693 remainder of this guide.
26696 @node Migration of 32 bit code
26697 @subsection Migration of 32-bit code
26699 @menu
26700 * Address types::
26701 * Access types::
26702 * Unchecked conversions::
26703 * Predefined constants::
26704 * Single source compatibility::
26705 * Experience with source compatibility::
26706 @end menu
26708 @node Address types
26709 @subsubsection Address types
26711 @noindent
26712 To solve the problem of mixing 64-bit and 32-bit addressing,
26713 while maintaining maximum backward compatibility, the following
26714 approach has been taken:
26716 @itemize @bullet
26717 @item
26718 @code{System.Address} always has a size of 64 bits
26720 @item
26721 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26722 @end itemize
26725 @noindent
26726 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26727 a @code{Short_Address}
26728 may be used where an @code{Address} is required, and vice versa, without
26729 needing explicit type conversions.
26730 By virtue of the Open VMS I64 parameter passing conventions,
26731 even imported
26732 and exported subprograms that have 32-bit address parameters are
26733 compatible with those that have 64-bit address parameters.
26734 (See @ref{Making code 64 bit clean} for details.)
26736 The areas that may need attention are those where record types have
26737 been defined that contain components of the type @code{System.Address}, and
26738 where objects of this type are passed to code expecting a record layout with
26739 32-bit addresses.
26741 Different compilers on different platforms cannot be
26742 expected to represent the same type in the same way,
26743 since alignment constraints
26744 and other system-dependent properties affect the compiler's decision.
26745 For that reason, Ada code
26746 generally uses representation clauses to specify the expected
26747 layout where required.
26749 If such a representation clause uses 32 bits for a component having
26750 the type @code{System.Address}, GNAT Pro for OpenVMS I64 will detect
26751 that error and produce a specific diagnostic message.
26752 The developer should then determine whether the representation
26753 should be 64 bits or not and make either of two changes:
26754 change the size to 64 bits and leave the type as @code{System.Address}, or
26755 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26756 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26757 required in any code setting or accessing the field; the compiler will
26758 automatically perform any needed conversions between address
26759 formats.
26761 @node Access types
26762 @subsubsection Access types
26764 @noindent
26765 By default, objects designated by access values are always
26766 allocated in the 32-bit
26767 address space. Thus legacy code will never contain
26768 any objects that are not addressable with 32-bit addresses, and
26769 the compiler will never raise exceptions as result of mixing
26770 32-bit and 64-bit addresses.
26772 However, the access values themselves are represented in 64 bits, for optimum
26773 performance and future compatibility with 64-bit code. As was
26774 the case with @code{System.Address}, the compiler will give an error message
26775 if an object or record component has a representation clause that
26776 requires the access value to fit in 32 bits. In such a situation,
26777 an explicit size clause for the access type, specifying 32 bits,
26778 will have the desired effect.
26780 General access types (declared with @code{access all}) can never be
26781 32 bits, as values of such types must be able to refer to any object
26782 of the  designated type,
26783 including objects residing outside the 32-bit address range.
26784 Existing Ada 83 code will not contain such type definitions,
26785 however, since general access types were introduced in Ada 95.
26787 @node Unchecked conversions
26788 @subsubsection Unchecked conversions
26790 @noindent
26791 In the case of an @code{Unchecked_Conversion} where the source type is a
26792 64-bit access type or the type @code{System.Address}, and the target
26793 type is a 32-bit type, the compiler will generate a warning.
26794 Even though the generated code will still perform the required
26795 conversions, it is highly recommended in these cases to use
26796 respectively a 32-bit access type or @code{System.Short_Address}
26797 as the source type.
26799 @node Predefined constants
26800 @subsubsection Predefined constants
26802 @noindent
26803 The following predefined constants have changed:
26805 @multitable {@code{System.Address_Size}} {2**32} {2**64}
26806 @item   @b{Constant}               @tab @b{Old} @tab @b{New}
26807 @item   @code{System.Word_Size}    @tab 32      @tab 64
26808 @item   @code{System.Memory_Size}  @tab 2**32   @tab 2**64
26809 @item   @code{System.Address_Size} @tab 32      @tab 64
26810 @end multitable
26812 @noindent
26813 If you need to refer to the specific
26814 memory size of a 32-bit implementation, instead of the
26815 actual memory size, use @code{System.Short_Memory_Size}
26816 rather than @code{System.Memory_Size}.
26817 Similarly, references to @code{System.Address_Size} may need
26818 to be replaced by @code{System.Short_Address'Size}.
26819 The program @command{gnatfind} may be useful for locating
26820 references to the above constants, so that you can verify that they
26821 are still correct.
26823 @node Single source compatibility
26824 @subsubsection Single source compatibility
26826 @noindent
26827 In order to allow the same source code to be compiled on
26828 both Alpha and I64 platforms, GNAT Pro for Alpha OpenVMS
26829 defines @code{System.Short_Address} and System.Short_Memory_Size
26830 as aliases of respectively @code{System.Address} and
26831 @code{System.Memory_Size}.
26832 (These aliases also leave the door open for a possible
26833 future ``upgrade'' of OpenVMS Alpha to a 64-bit address space.)
26835 @node Experience with source compatibility
26836 @subsubsection Experience with source compatibility
26838 @noindent
26839 The Security Server and STARLET provide an interesting ``test case''
26840 for source compatibility issues, since it is in such system code
26841 where assumptions about @code{Address} size might be expected to occur.
26842 Indeed, there were a small number of occasions in the Security Server
26843 file @file{jibdef.ads}
26844 where a representation clause for a record type specified
26845 32 bits for a component of type @code{Address}.
26846 All of these errors were detected by the compiler.
26847 The repair was obvious and immediate; to simply replace @code{Address} by
26848 @code{Short_Address}.
26850 In the case of STARLET, there were several record types that should
26851 have had representation clauses but did not.  In these record types
26852 there was an implicit assumption that an @code{Address} value occupied
26853 32 bits.
26854 These compiled without error, but their usage resulted in run-time error
26855 returns from STARLET system calls.
26856 To assist in the compile-time detection of such situations, we
26857 plan to include a switch to generate a warning message when a
26858 record component is of type @code{Address}.
26861 @c ****************************************
26862 @node Taking advantage of 64 bit addressing
26863 @subsection Taking advantage of 64-bit addressing
26865 @menu
26866 * Making code 64 bit clean::
26867 * Allocating memory from the 64 bit storage pool::
26868 * Restrictions on use of 64 bit objects::
26869 * Using 64 bit storage pools by default::
26870 * General access types::
26871 * STARLET and other predefined libraries::
26872 @end menu
26874 @node Making code 64 bit clean
26875 @subsubsection Making code 64-bit clean
26877 @noindent
26878 In order to prevent problems that may occur when (parts of) a
26879 system start using memory outside the 32-bit address range,
26880 we recommend some additional guidelines:
26882 @itemize @bullet
26883 @item
26884 For imported subprograms that take parameters of the
26885 type @code{System.Address}, ensure that these subprograms can
26886 indeed handle 64-bit addresses. If not, or when in doubt,
26887 change the subprogram declaration to specify
26888 @code{System.Short_Address} instead.
26890 @item
26891 Resolve all warnings related to size mismatches in
26892 unchecked conversions. Failing to do so causes
26893 erroneous execution if the source object is outside
26894 the 32-bit address space.
26896 @item
26897 (optional) Explicitly use the 32-bit storage pool
26898 for access types used in a 32-bit context, or use
26899 generic access types where possible
26900 (@pxref{Restrictions on use of 64 bit objects}).
26901 @end itemize
26903 @noindent
26904 If these rules are followed, the compiler will automatically insert
26905 any necessary checks to ensure that no addresses or access values
26906 passed to 32-bit code ever refer to objects outside the 32-bit
26907 address range.
26908 Any attempt to do this will raise @code{Constraint_Error}.
26910 @node Allocating memory from the 64 bit storage pool
26911 @subsubsection Allocating memory from the 64-bit storage pool
26913 @noindent
26914 For any access type @code{T} that potentially requires memory allocations
26915 beyond the 32-bit address space,
26916 use the following representation clause:
26918 @smallexample @c ada
26919    for T'Storage_Pool use System.Pool_64;
26920 @end smallexample
26923 @node Restrictions on use of 64 bit objects
26924 @subsubsection Restrictions on use of 64-bit objects
26926 @noindent
26927 Taking the address of an object allocated from a 64-bit storage pool,
26928 and then passing this address to a subprogram expecting
26929 @code{System.Short_Address},
26930 or assigning it to a variable of type @code{Short_Address}, will cause
26931 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
26932 (@pxref{Making code 64 bit clean}), or checks are suppressed,
26933 no exception is raised and execution
26934 will become erroneous.
26936 @node Using 64 bit storage pools by default
26937 @subsubsection Using 64-bit storage pools by default
26939 @noindent
26940 In some cases it may be desirable to have the compiler allocate
26941 from 64-bit storage pools by default. This may be the case for
26942 libraries that are 64-bit clean, but may be used in both 32-bit
26943 and 64-bit contexts. For these cases the following configuration
26944 pragma may be specified:
26946 @smallexample @c ada
26947   pragma Pool_64_Default;
26948 @end smallexample
26950 @noindent
26951 Any code compiled in the context of this pragma will by default
26952 use the @code{System.Pool_64} storage pool. This default may be overridden
26953 for a specific access type @code{T} by the representation clause:
26955 @smallexample @c ada
26956    for T'Storage_Pool use System.Pool_32;
26957 @end smallexample
26959 @noindent
26960 Any object whose address may be passed to a subprogram with a
26961 @code{Short_Address} argument, or assigned to a variable of type
26962 @code{Short_Address}, needs to be allocated from this pool.
26964 @node General access types
26965 @subsubsection General access types
26967 @noindent
26968 Objects designated by access values from a
26969 general access type (declared with @code{access all}) are never allocated
26970 from a 64-bit storage pool. Code that uses general access types will
26971 accept objects allocated in either 32-bit or 64-bit address spaces,
26972 but never allocate objects outside the 32-bit address space.
26973 Using general access types ensures maximum compatibility with both
26974 32-bit and 64-bit code.
26977 @node STARLET and other predefined libraries
26978 @subsubsection STARLET and other predefined libraries
26980 @noindent
26981 All code that comes as part of GNAT is 64-bit clean, but the
26982 restrictions given in @ref{Restrictions on use of 64 bit objects},
26983 still apply. Look at the package
26984 specifications to see in which contexts objects allocated
26985 in 64-bit address space are acceptable.
26987 @node Technical details
26988 @subsection Technical details
26990 @noindent
26991 GNAT Pro for Open VMS I64 takes advantage of the freedom given in the Ada
26992 standard with respect to the type of @code{System.Address}. Previous versions
26993 of GNAT Pro have defined this type as private and implemented it as
26994 a modular type.
26996 In order to allow defining @code{System.Short_Address} as a proper subtype,
26997 and to match the implicit sign extension in parameter passing,
26998 in GNAT Pro for Open VMS I64, @code{System.Address} is defined as a
26999 visible (i.e., non-private) integer type.
27000 Standard operations on the type, such as the binary operators ``+'', ``-'',
27001 etc., that take @code{Address} operands and return an @code{Address} result,
27002 have been hidden by declaring these
27003 @code{abstract}, an Ada 95 feature that helps avoid the potential ambiguities
27004 that would otherwise result from overloading.
27005 (Note that, although @code{Address} is a visible integer type,
27006 good programming practice dictates against exploiting the type's
27007 integer properties such as literals, since this will compromise
27008 code portability.)
27010 Defining @code{Address} as a visible integer type helps achieve
27011 maximum compatibility for existing Ada code,
27012 without sacrificing the capabilities of the I64 architecture.
27013 @end ifset
27016 @c ************************************************
27017 @ifset unw
27018 @node Microsoft Windows Topics
27019 @appendix Microsoft Windows Topics
27020 @cindex Windows NT
27021 @cindex Windows 95
27022 @cindex Windows 98
27024 @noindent
27025 This chapter describes topics that are specific to the Microsoft Windows
27026 platforms (NT, 2000, and XP Professional).
27028 @menu
27029 * Using GNAT on Windows::
27030 * Using a network installation of GNAT::
27031 * CONSOLE and WINDOWS subsystems::
27032 * Temporary Files::
27033 * Mixed-Language Programming on Windows::
27034 * Windows Calling Conventions::
27035 * Introduction to Dynamic Link Libraries (DLLs)::
27036 * Using DLLs with GNAT::
27037 * Building DLLs with GNAT::
27038 * Building DLLs with GNAT Project files::
27039 * Building DLLs with gnatdll::
27040 * GNAT and Windows Resources::
27041 * Debugging a DLL::
27042 * Setting Stack Size from gnatlink::
27043 * Setting Heap Size from gnatlink::
27044 @end menu
27046 @node Using GNAT on Windows
27047 @section Using GNAT on Windows
27049 @noindent
27050 One of the strengths of the GNAT technology is that its tool set
27051 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27052 @code{gdb} debugger, etc.) is used in the same way regardless of the
27053 platform.
27055 On Windows this tool set is complemented by a number of Microsoft-specific
27056 tools that have been provided to facilitate interoperability with Windows
27057 when this is required. With these tools:
27059 @itemize @bullet
27061 @item
27062 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27063 subsystems.
27065 @item
27066 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27067 relocatable and non-relocatable DLLs are supported).
27069 @item
27070 You can build Ada DLLs for use in other applications. These applications
27071 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27072 relocatable and non-relocatable Ada DLLs are supported.
27074 @item
27075 You can include Windows resources in your Ada application.
27077 @item
27078 You can use or create COM/DCOM objects.
27079 @end itemize
27081 @noindent
27082 Immediately below are listed all known general GNAT-for-Windows restrictions.
27083 Other restrictions about specific features like Windows Resources and DLLs
27084 are listed in separate sections below.
27086 @itemize @bullet
27088 @item
27089 It is not possible to use @code{GetLastError} and @code{SetLastError}
27090 when tasking, protected records, or exceptions are used. In these
27091 cases, in order to implement Ada semantics, the GNAT run-time system
27092 calls certain Win32 routines that set the last error variable to 0 upon
27093 success. It should be possible to use @code{GetLastError} and
27094 @code{SetLastError} when tasking, protected record, and exception
27095 features are not used, but it is not guaranteed to work.
27097 @item
27098 It is not possible to link against Microsoft libraries except for
27099 import libraries. The library must be built to be compatible with
27100 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
27101 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
27102 not be compatible with the GNAT runtime. Even if the library is
27103 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
27105 @item
27106 When the compilation environment is located on FAT32 drives, users may
27107 experience recompilations of the source files that have not changed if
27108 Daylight Saving Time (DST) state has changed since the last time files
27109 were compiled. NTFS drives do not have this problem.
27111 @item
27112 No components of the GNAT toolset use any entries in the Windows
27113 registry. The only entries that can be created are file associations and
27114 PATH settings, provided the user has chosen to create them at installation
27115 time, as well as some minimal book-keeping information needed to correctly
27116 uninstall or integrate different GNAT products.
27117 @end itemize
27119 @node Using a network installation of GNAT
27120 @section Using a network installation of GNAT
27122 @noindent
27123 Make sure the system on which GNAT is installed is accessible from the
27124 current machine, i.e. the install location is shared over the network.
27125 Shared resources are accessed on Windows by means of UNC paths, which
27126 have the format @code{\\server\sharename\path}
27128 In order to use such a network installation, simply add the UNC path of the
27129 @file{bin} directory of your GNAT installation in front of your PATH. For
27130 example, if GNAT is installed in @file{\GNAT} directory of a share location
27131 called @file{c-drive} on a machine @file{LOKI}, the following command will
27132 make it available:
27134 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27136 Be aware that every compilation using the network installation results in the
27137 transfer of large amounts of data across the network and will likely cause
27138 serious performance penalty.
27140 @node CONSOLE and WINDOWS subsystems
27141 @section CONSOLE and WINDOWS subsystems
27142 @cindex CONSOLE Subsystem
27143 @cindex WINDOWS Subsystem
27144 @cindex -mwindows
27146 @noindent
27147 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27148 (which is the default subsystem) will always create a console when
27149 launching the application. This is not something desirable when the
27150 application has a Windows GUI. To get rid of this console the
27151 application must be using the @code{WINDOWS} subsystem. To do so
27152 the @option{-mwindows} linker option must be specified.
27154 @smallexample
27155 $ gnatmake winprog -largs -mwindows
27156 @end smallexample
27158 @node Temporary Files
27159 @section Temporary Files
27160 @cindex Temporary files
27162 @noindent
27163 It is possible to control where temporary files gets created by setting
27164 the TMP environment variable. The file will be created:
27166 @itemize
27167 @item Under the directory pointed to by the TMP environment variable if
27168 this directory exists.
27170 @item Under c:\temp, if the TMP environment variable is not set (or not
27171 pointing to a directory) and if this directory exists.
27173 @item Under the current working directory otherwise.
27174 @end itemize
27176 @noindent
27177 This allows you to determine exactly where the temporary
27178 file will be created. This is particularly useful in networked
27179 environments where you may not have write access to some
27180 directories.
27182 @node Mixed-Language Programming on Windows
27183 @section Mixed-Language Programming on Windows
27185 @noindent
27186 Developing pure Ada applications on Windows is no different than on
27187 other GNAT-supported platforms. However, when developing or porting an
27188 application that contains a mix of Ada and C/C++, the choice of your
27189 Windows C/C++ development environment conditions your overall
27190 interoperability strategy.
27192 If you use @command{gcc} to compile the non-Ada part of your application,
27193 there are no Windows-specific restrictions that affect the overall
27194 interoperability with your Ada code. If you plan to use
27195 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
27196 the following limitations:
27198 @itemize @bullet
27199 @item
27200 You cannot link your Ada code with an object or library generated with
27201 Microsoft tools if these use the @code{.tls} section (Thread Local
27202 Storage section) since the GNAT linker does not yet support this section.
27204 @item
27205 You cannot link your Ada code with an object or library generated with
27206 Microsoft tools if these use I/O routines other than those provided in
27207 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
27208 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
27209 libraries can cause a conflict with @code{msvcrt.dll} services. For
27210 instance Visual C++ I/O stream routines conflict with those in
27211 @code{msvcrt.dll}.
27212 @end itemize
27214 @noindent
27215 If you do want to use the Microsoft tools for your non-Ada code and hit one
27216 of the above limitations, you have two choices:
27218 @enumerate
27219 @item
27220 Encapsulate your non Ada code in a DLL to be linked with your Ada
27221 application. In this case, use the Microsoft or whatever environment to
27222 build the DLL and use GNAT to build your executable
27223 (@pxref{Using DLLs with GNAT}).
27225 @item
27226 Or you can encapsulate your Ada code in a DLL to be linked with the
27227 other part of your application. In this case, use GNAT to build the DLL
27228 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
27229 environment to build your executable.
27230 @end enumerate
27232 @node Windows Calling Conventions
27233 @section Windows Calling Conventions
27234 @findex Stdcall
27235 @findex APIENTRY
27237 @menu
27238 * C Calling Convention::
27239 * Stdcall Calling Convention::
27240 * Win32 Calling Convention::
27241 * DLL Calling Convention::
27242 @end menu
27244 @noindent
27245 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27246 (callee), there are several ways to push @code{G}'s parameters on the
27247 stack and there are several possible scenarios to clean up the stack
27248 upon @code{G}'s return. A calling convention is an agreed upon software
27249 protocol whereby the responsibilities between the caller (@code{F}) and
27250 the callee (@code{G}) are clearly defined. Several calling conventions
27251 are available for Windows:
27253 @itemize @bullet
27254 @item
27255 @code{C} (Microsoft defined)
27257 @item
27258 @code{Stdcall} (Microsoft defined)
27260 @item
27261 @code{Win32} (GNAT specific)
27263 @item
27264 @code{DLL} (GNAT specific)
27265 @end itemize
27267 @node C Calling Convention
27268 @subsection @code{C} Calling Convention
27270 @noindent
27271 This is the default calling convention used when interfacing to C/C++
27272 routines compiled with either @command{gcc} or Microsoft Visual C++.
27274 In the @code{C} calling convention subprogram parameters are pushed on the
27275 stack by the caller from right to left. The caller itself is in charge of
27276 cleaning up the stack after the call. In addition, the name of a routine
27277 with @code{C} calling convention is mangled by adding a leading underscore.
27279 The name to use on the Ada side when importing (or exporting) a routine
27280 with @code{C} calling convention is the name of the routine. For
27281 instance the C function:
27283 @smallexample
27284 int get_val (long);
27285 @end smallexample
27287 @noindent
27288 should be imported from Ada as follows:
27290 @smallexample @c ada
27291 @group
27292 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27293 pragma Import (C, Get_Val, External_Name => "get_val");
27294 @end group
27295 @end smallexample
27297 @noindent
27298 Note that in this particular case the @code{External_Name} parameter could
27299 have been omitted since, when missing, this parameter is taken to be the
27300 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27301 is missing, as in the above example, this parameter is set to be the
27302 @code{External_Name} with a leading underscore.
27304 When importing a variable defined in C, you should always use the @code{C}
27305 calling convention unless the object containing the variable is part of a
27306 DLL (in which case you should use the @code{Stdcall} calling
27307 convention, @pxref{Stdcall Calling Convention}).
27309 @node Stdcall Calling Convention
27310 @subsection @code{Stdcall} Calling Convention
27312 @noindent
27313 This convention, which was the calling convention used for Pascal
27314 programs, is used by Microsoft for all the routines in the Win32 API for
27315 efficiency reasons. It must be used to import any routine for which this
27316 convention was specified.
27318 In the @code{Stdcall} calling convention subprogram parameters are pushed
27319 on the stack by the caller from right to left. The callee (and not the
27320 caller) is in charge of cleaning the stack on routine exit. In addition,
27321 the name of a routine with @code{Stdcall} calling convention is mangled by
27322 adding a leading underscore (as for the @code{C} calling convention) and a
27323 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
27324 bytes) of the parameters passed to the routine.
27326 The name to use on the Ada side when importing a C routine with a
27327 @code{Stdcall} calling convention is the name of the C routine. The leading
27328 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
27329 the compiler. For instance the Win32 function:
27331 @smallexample
27332 @b{APIENTRY} int get_val (long);
27333 @end smallexample
27335 @noindent
27336 should be imported from Ada as follows:
27338 @smallexample @c ada
27339 @group
27340 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27341 pragma Import (Stdcall, Get_Val);
27342 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27343 @end group
27344 @end smallexample
27346 @noindent
27347 As for the @code{C} calling convention, when the @code{External_Name}
27348 parameter is missing, it is taken to be the name of the Ada entity in lower
27349 case. If instead of writing the above import pragma you write:
27351 @smallexample @c ada
27352 @group
27353 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27354 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27355 @end group
27356 @end smallexample
27358 @noindent
27359 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27360 of specifying the @code{External_Name} parameter you specify the
27361 @code{Link_Name} as in the following example:
27363 @smallexample @c ada
27364 @group
27365 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27366 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27367 @end group
27368 @end smallexample
27370 @noindent
27371 then the imported routine is @code{retrieve_val@@4}, that is, there is no
27372 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
27373 added at the end of the @code{Link_Name} by the compiler.
27375 @noindent
27376 Note, that in some special cases a DLL's entry point name lacks a trailing
27377 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
27378 The @code{gnatdll} tool, which creates the import library for the DLL, is able
27379 to handle those cases (@pxref{Using gnatdll} for the description of
27380 the switches).
27382 @noindent
27383 It is also possible to import variables defined in a DLL by using an
27384 import pragma for a variable. As an example, if a DLL contains a
27385 variable defined as:
27387 @smallexample
27388 int my_var;
27389 @end smallexample
27391 @noindent
27392 then, to access this variable from Ada you should write:
27394 @smallexample @c ada
27395 @group
27396 My_Var : Interfaces.C.int;
27397 pragma Import (Stdcall, My_Var);
27398 @end group
27399 @end smallexample
27401 @noindent
27402 Note that to ease building cross-platform bindings this convention
27403 will be handled as a @code{C} calling convention on non Windows platforms.
27405 @node Win32 Calling Convention
27406 @subsection @code{Win32} Calling Convention
27408 @noindent
27409 This convention, which is GNAT-specific is fully equivalent to the
27410 @code{Stdcall} calling convention described above.
27412 @node DLL Calling Convention
27413 @subsection @code{DLL} Calling Convention
27415 @noindent
27416 This convention, which is GNAT-specific is fully equivalent to the
27417 @code{Stdcall} calling convention described above.
27419 @node Introduction to Dynamic Link Libraries (DLLs)
27420 @section Introduction to Dynamic Link Libraries (DLLs)
27421 @findex DLL
27423 @noindent
27424 A Dynamically Linked Library (DLL) is a library that can be shared by
27425 several applications running under Windows. A DLL can contain any number of
27426 routines and variables.
27428 One advantage of DLLs is that you can change and enhance them without
27429 forcing all the applications that depend on them to be relinked or
27430 recompiled. However, you should be aware than all calls to DLL routines are
27431 slower since, as you will understand below, such calls are indirect.
27433 To illustrate the remainder of this section, suppose that an application
27434 wants to use the services of a DLL @file{API.dll}. To use the services
27435 provided by @file{API.dll} you must statically link against the DLL or
27436 an import library which contains a jump table with an entry for each
27437 routine and variable exported by the DLL. In the Microsoft world this
27438 import library is called @file{API.lib}. When using GNAT this import
27439 library is called either @file{libAPI.a} or @file{libapi.a} (names are
27440 case insensitive).
27442 After you have linked your application with the DLL or the import library
27443 and you run your application, here is what happens:
27445 @enumerate
27446 @item
27447 Your application is loaded into memory.
27449 @item
27450 The DLL @file{API.dll} is mapped into the address space of your
27451 application. This means that:
27453 @itemize @bullet
27454 @item
27455 The DLL will use the stack of the calling thread.
27457 @item
27458 The DLL will use the virtual address space of the calling process.
27460 @item
27461 The DLL will allocate memory from the virtual address space of the calling
27462 process.
27464 @item
27465 Handles (pointers) can be safely exchanged between routines in the DLL
27466 routines and routines in the application using the DLL.
27467 @end itemize
27469 @item
27470 The entries in the jump table (from the import library @file{libAPI.a}
27471 or @file{API.lib} or automatically created when linking against a DLL)
27472 which is part of your application are initialized with the addresses
27473 of the routines and variables in @file{API.dll}.
27475 @item
27476 If present in @file{API.dll}, routines @code{DllMain} or
27477 @code{DllMainCRTStartup} are invoked. These routines typically contain
27478 the initialization code needed for the well-being of the routines and
27479 variables exported by the DLL.
27480 @end enumerate
27482 @noindent
27483 There is an additional point which is worth mentioning. In the Windows
27484 world there are two kind of DLLs: relocatable and non-relocatable
27485 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27486 in the target application address space. If the addresses of two
27487 non-relocatable DLLs overlap and these happen to be used by the same
27488 application, a conflict will occur and the application will run
27489 incorrectly. Hence, when possible, it is always preferable to use and
27490 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27491 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27492 User's Guide) removes the debugging symbols from the DLL but the DLL can
27493 still be relocated.
27495 As a side note, an interesting difference between Microsoft DLLs and
27496 Unix shared libraries, is the fact that on most Unix systems all public
27497 routines are exported by default in a Unix shared library, while under
27498 Windows it is possible (but not required) to list exported routines in
27499 a definition file (@pxref{The Definition File}).
27501 @node Using DLLs with GNAT
27502 @section Using DLLs with GNAT
27504 @menu
27505 * Creating an Ada Spec for the DLL Services::
27506 * Creating an Import Library::
27507 @end menu
27509 @noindent
27510 To use the services of a DLL, say @file{API.dll}, in your Ada application
27511 you must have:
27513 @enumerate
27514 @item
27515 The Ada spec for the routines and/or variables you want to access in
27516 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27517 header files provided with the DLL.
27519 @item
27520 The import library (@file{libAPI.a} or @file{API.lib}). As previously
27521 mentioned an import library is a statically linked library containing the
27522 import table which will be filled at load time to point to the actual
27523 @file{API.dll} routines. Sometimes you don't have an import library for the
27524 DLL you want to use. The following sections will explain how to build
27525 one. Note that this is optional.
27527 @item
27528 The actual DLL, @file{API.dll}.
27529 @end enumerate
27531 @noindent
27532 Once you have all the above, to compile an Ada application that uses the
27533 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27534 you simply issue the command
27536 @smallexample
27537 $ gnatmake my_ada_app -largs -lAPI
27538 @end smallexample
27540 @noindent
27541 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27542 tells the GNAT linker to look first for a library named @file{API.lib}
27543 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
27544 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
27545 contains the following pragma
27547 @smallexample @c ada
27548 pragma Linker_Options ("-lAPI");
27549 @end smallexample
27551 @noindent
27552 you do not have to add @option{-largs -lAPI} at the end of the
27553 @command{gnatmake} command.
27555 If any one of the items above is missing you will have to create it
27556 yourself. The following sections explain how to do so using as an
27557 example a fictitious DLL called @file{API.dll}.
27559 @node Creating an Ada Spec for the DLL Services
27560 @subsection Creating an Ada Spec for the DLL Services
27562 @noindent
27563 A DLL typically comes with a C/C++ header file which provides the
27564 definitions of the routines and variables exported by the DLL. The Ada
27565 equivalent of this header file is a package spec that contains definitions
27566 for the imported entities. If the DLL you intend to use does not come with
27567 an Ada spec you have to generate one such spec yourself. For example if
27568 the header file of @file{API.dll} is a file @file{api.h} containing the
27569 following two definitions:
27571 @smallexample
27572 @group
27573 @cartouche
27574 int some_var;
27575 int get (char *);
27576 @end cartouche
27577 @end group
27578 @end smallexample
27580 @noindent
27581 then the equivalent Ada spec could be:
27583 @smallexample @c ada
27584 @group
27585 @cartouche
27586 with Interfaces.C.Strings;
27587 package API is
27588    use Interfaces;
27590    Some_Var : C.int;
27591    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27593 private
27594    pragma Import (C, Get);
27595    pragma Import (DLL, Some_Var);
27596 end API;
27597 @end cartouche
27598 @end group
27599 @end smallexample
27601 @noindent
27602 Note that a variable is
27603 @strong{always imported with a Stdcall convention}. A function
27604 can have @code{C} or @code{Stdcall} convention.
27605 (@pxref{Windows Calling Conventions}).
27607 @node Creating an Import Library
27608 @subsection Creating an Import Library
27609 @cindex Import library
27611 @menu
27612 * The Definition File::
27613 * GNAT-Style Import Library::
27614 * Microsoft-Style Import Library::
27615 @end menu
27617 @noindent
27618 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27619 import library @file{libAPI.a} is available with @file{API.dll} you
27620 can skip this section. You can also skip this section if
27621 @file{API.dll} is built with GNU tools as in this case it is possible
27622 to link directly against the DLL. Otherwise read on.
27624 @node The Definition File
27625 @subsubsection The Definition File
27626 @cindex Definition file
27627 @findex .def
27629 @noindent
27630 As previously mentioned, and unlike Unix systems, the list of symbols
27631 that are exported from a DLL must be provided explicitly in Windows.
27632 The main goal of a definition file is precisely that: list the symbols
27633 exported by a DLL. A definition file (usually a file with a @code{.def}
27634 suffix) has the following structure:
27636 @smallexample
27637 @group
27638 @cartouche
27639 [LIBRARY @i{name}]
27640 [DESCRIPTION @i{string}]
27641 EXPORTS
27642    @i{symbol1}
27643    @i{symbol2}
27644    ...
27645 @end cartouche
27646 @end group
27647 @end smallexample
27649 @table @code
27650 @item LIBRARY @i{name}
27651 This section, which is optional, gives the name of the DLL.
27653 @item DESCRIPTION @i{string}
27654 This section, which is optional, gives a description string that will be
27655 embedded in the import library.
27657 @item EXPORTS
27658 This section gives the list of exported symbols (procedures, functions or
27659 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27660 section of @file{API.def} looks like:
27662 @smallexample
27663 @group
27664 @cartouche
27665 EXPORTS
27666    some_var
27667    get
27668 @end cartouche
27669 @end group
27670 @end smallexample
27671 @end table
27673 @noindent
27674 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
27675 (@pxref{Windows Calling Conventions}) for a Stdcall
27676 calling convention function in the exported symbols list.
27678 @noindent
27679 There can actually be other sections in a definition file, but these
27680 sections are not relevant to the discussion at hand.
27682 @node GNAT-Style Import Library
27683 @subsubsection GNAT-Style Import Library
27685 @noindent
27686 To create a static import library from @file{API.dll} with the GNAT tools
27687 you should proceed as follows:
27689 @enumerate
27690 @item
27691 Create the definition file @file{API.def} (@pxref{The Definition File}).
27692 For that use the @code{dll2def} tool as follows:
27694 @smallexample
27695 $ dll2def API.dll > API.def
27696 @end smallexample
27698 @noindent
27699 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27700 to standard output the list of entry points in the DLL. Note that if
27701 some routines in the DLL have the @code{Stdcall} convention
27702 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
27703 suffix then you'll have to edit @file{api.def} to add it, and specify
27704 @code{-k} to @code{gnatdll} when creating the import library.
27706 @noindent
27707 Here are some hints to find the right @code{@@}@i{nn} suffix.
27709 @enumerate
27710 @item
27711 If you have the Microsoft import library (.lib), it is possible to get
27712 the right symbols by using Microsoft @code{dumpbin} tool (see the
27713 corresponding Microsoft documentation for further details).
27715 @smallexample
27716 $ dumpbin /exports api.lib
27717 @end smallexample
27719 @item
27720 If you have a message about a missing symbol at link time the compiler
27721 tells you what symbol is expected. You just have to go back to the
27722 definition file and add the right suffix.
27723 @end enumerate
27725 @item
27726 Build the import library @code{libAPI.a}, using @code{gnatdll}
27727 (@pxref{Using gnatdll}) as follows:
27729 @smallexample
27730 $ gnatdll -e API.def -d API.dll
27731 @end smallexample
27733 @noindent
27734 @code{gnatdll} takes as input a definition file @file{API.def} and the
27735 name of the DLL containing the services listed in the definition file
27736 @file{API.dll}. The name of the static import library generated is
27737 computed from the name of the definition file as follows: if the
27738 definition file name is @i{xyz}@code{.def}, the import library name will
27739 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
27740 @option{-e} could have been removed because the name of the definition
27741 file (before the ``@code{.def}'' suffix) is the same as the name of the
27742 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27743 @end enumerate
27745 @node Microsoft-Style Import Library
27746 @subsubsection Microsoft-Style Import Library
27748 @noindent
27749 With GNAT you can either use a GNAT-style or Microsoft-style import
27750 library. A Microsoft import library is needed only if you plan to make an
27751 Ada DLL available to applications developed with Microsoft
27752 tools (@pxref{Mixed-Language Programming on Windows}).
27754 To create a Microsoft-style import library for @file{API.dll} you
27755 should proceed as follows:
27757 @enumerate
27758 @item
27759 Create the definition file @file{API.def} from the DLL. For this use either
27760 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27761 tool (see the corresponding Microsoft documentation for further details).
27763 @item
27764 Build the actual import library using Microsoft's @code{lib} utility:
27766 @smallexample
27767 $ lib -machine:IX86 -def:API.def -out:API.lib
27768 @end smallexample
27770 @noindent
27771 If you use the above command the definition file @file{API.def} must
27772 contain a line giving the name of the DLL:
27774 @smallexample
27775 LIBRARY      "API"
27776 @end smallexample
27778 @noindent
27779 See the Microsoft documentation for further details about the usage of
27780 @code{lib}.
27781 @end enumerate
27783 @node Building DLLs with GNAT
27784 @section Building DLLs with GNAT
27785 @cindex DLLs, building
27787 @noindent
27788 This section explain how to build DLLs using the GNAT built-in DLL
27789 support. With the following procedure it is straight forward to build
27790 and use DLLs with GNAT.
27792 @enumerate
27794 @item building object files
27796 The first step is to build all objects files that are to be included
27797 into the DLL. This is done by using the standard @command{gnatmake} tool.
27799 @item building the DLL
27801 To build the DLL you must use @command{gcc}'s @code{-shared}
27802 option. It is quite simple to use this method:
27804 @smallexample
27805 $ gcc -shared -o api.dll obj1.o obj2.o ...
27806 @end smallexample
27808 It is important to note that in this case all symbols found in the
27809 object files are automatically exported. It is possible to restrict
27810 the set of symbols to export by passing to @command{gcc} a definition
27811 file, @pxref{The Definition File}. For example:
27813 @smallexample
27814 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
27815 @end smallexample
27817 If you use a definition file you must export the elaboration procedures
27818 for every package that required one. Elaboration procedures are named
27819 using the package name followed by "_E".
27821 @item preparing DLL to be used
27823 For the DLL to be used by client programs the bodies must be hidden
27824 from it and the .ali set with read-only attribute. This is very important
27825 otherwise GNAT will recompile all packages and will not actually use
27826 the code in the DLL. For example:
27828 @smallexample
27829 $ mkdir apilib
27830 $ copy *.ads *.ali api.dll apilib
27831 $ attrib +R apilib\*.ali
27832 @end smallexample
27834 @end enumerate
27836 At this point it is possible to use the DLL by directly linking
27837 against it. Note that you must use the GNAT shared runtime when using
27838 GNAT shared libraries. This is achieved by using @code{-shared} binder's
27839 option.
27841 @smallexample
27842 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27843 @end smallexample
27845 @node Building DLLs with GNAT Project files
27846 @section Building DLLs with GNAT Project files
27847 @cindex DLLs, building
27849 @noindent
27850 There is nothing specific to Windows in this area. @pxref{Library Projects}.
27852 @node Building DLLs with gnatdll
27853 @section Building DLLs with gnatdll
27854 @cindex DLLs, building
27856 @menu
27857 * Limitations When Using Ada DLLs from Ada::
27858 * Exporting Ada Entities::
27859 * Ada DLLs and Elaboration::
27860 * Ada DLLs and Finalization::
27861 * Creating a Spec for Ada DLLs::
27862 * Creating the Definition File::
27863 * Using gnatdll::
27864 @end menu
27866 @noindent
27867 Note that it is preferred to use the built-in GNAT DLL support
27868 (@pxref{Building DLLs with GNAT}) or GNAT Project files
27869 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
27871 This section explains how to build DLLs containing Ada code using
27872 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27873 remainder of this section.
27875 The steps required to build an Ada DLL that is to be used by Ada as well as
27876 non-Ada applications are as follows:
27878 @enumerate
27879 @item
27880 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27881 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27882 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27883 skip this step if you plan to use the Ada DLL only from Ada applications.
27885 @item
27886 Your Ada code must export an initialization routine which calls the routine
27887 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27888 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27889 routine exported by the Ada DLL must be invoked by the clients of the DLL
27890 to initialize the DLL.
27892 @item
27893 When useful, the DLL should also export a finalization routine which calls
27894 routine @code{adafinal} generated by @command{gnatbind} to perform the
27895 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27896 The finalization routine exported by the Ada DLL must be invoked by the
27897 clients of the DLL when the DLL services are no further needed.
27899 @item
27900 You must provide a spec for the services exported by the Ada DLL in each
27901 of the programming languages to which you plan to make the DLL available.
27903 @item
27904 You must provide a definition file listing the exported entities
27905 (@pxref{The Definition File}).
27907 @item
27908 Finally you must use @code{gnatdll} to produce the DLL and the import
27909 library (@pxref{Using gnatdll}).
27910 @end enumerate
27912 @noindent
27913 Note that a relocatable DLL stripped using the @code{strip}
27914 binutils tool will not be relocatable anymore. To build a DLL without
27915 debug information pass @code{-largs -s} to @code{gnatdll}. This
27916 restriction does not apply to a DLL built using a Library Project.
27917 @pxref{Library Projects}.
27919 @node Limitations When Using Ada DLLs from Ada
27920 @subsection Limitations When Using Ada DLLs from Ada
27922 @noindent
27923 When using Ada DLLs from Ada applications there is a limitation users
27924 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27925 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27926 each Ada DLL includes the services of the GNAT run time that are necessary
27927 to the Ada code inside the DLL. As a result, when an Ada program uses an
27928 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27929 one in the main program.
27931 It is therefore not possible to exchange GNAT run-time objects between the
27932 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27933 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
27934 types, etc.
27936 It is completely safe to exchange plain elementary, array or record types,
27937 Windows object handles, etc.
27939 @node Exporting Ada Entities
27940 @subsection Exporting Ada Entities
27941 @cindex Export table
27943 @noindent
27944 Building a DLL is a way to encapsulate a set of services usable from any
27945 application. As a result, the Ada entities exported by a DLL should be
27946 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27947 any Ada name mangling. As an example here is an Ada package
27948 @code{API}, spec and body, exporting two procedures, a function, and a
27949 variable:
27951 @smallexample @c ada
27952 @group
27953 @cartouche
27954 with Interfaces.C; use Interfaces;
27955 package API is
27956    Count : C.int := 0;
27957    function Factorial (Val : C.int) return C.int;
27959    procedure Initialize_API;
27960    procedure Finalize_API;
27961    --  Initialization & Finalization routines. More in the next section.
27962 private
27963    pragma Export (C, Initialize_API);
27964    pragma Export (C, Finalize_API);
27965    pragma Export (C, Count);
27966    pragma Export (C, Factorial);
27967 end API;
27968 @end cartouche
27969 @end group
27970 @end smallexample
27972 @smallexample @c ada
27973 @group
27974 @cartouche
27975 package body API is
27976    function Factorial (Val : C.int) return C.int is
27977       Fact : C.int := 1;
27978    begin
27979       Count := Count + 1;
27980       for K in 1 .. Val loop
27981          Fact := Fact * K;
27982       end loop;
27983       return Fact;
27984    end Factorial;
27986    procedure Initialize_API is
27987       procedure Adainit;
27988       pragma Import (C, Adainit);
27989    begin
27990       Adainit;
27991    end Initialize_API;
27993    procedure Finalize_API is
27994       procedure Adafinal;
27995       pragma Import (C, Adafinal);
27996    begin
27997       Adafinal;
27998    end Finalize_API;
27999 end API;
28000 @end cartouche
28001 @end group
28002 @end smallexample
28004 @noindent
28005 If the Ada DLL you are building will only be used by Ada applications
28006 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28007 convention. As an example, the previous package could be written as
28008 follows:
28010 @smallexample @c ada
28011 @group
28012 @cartouche
28013 package API is
28014    Count : Integer := 0;
28015    function Factorial (Val : Integer) return Integer;
28017    procedure Initialize_API;
28018    procedure Finalize_API;
28019    --  Initialization and Finalization routines.
28020 end API;
28021 @end cartouche
28022 @end group
28023 @end smallexample
28025 @smallexample @c ada
28026 @group
28027 @cartouche
28028 package body API is
28029    function Factorial (Val : Integer) return Integer is
28030       Fact : Integer := 1;
28031    begin
28032       Count := Count + 1;
28033       for K in 1 .. Val loop
28034          Fact := Fact * K;
28035       end loop;
28036       return Fact;
28037    end Factorial;
28039    ...
28040    --  The remainder of this package body is unchanged.
28041 end API;
28042 @end cartouche
28043 @end group
28044 @end smallexample
28046 @noindent
28047 Note that if you do not export the Ada entities with a @code{C} or
28048 @code{Stdcall} convention you will have to provide the mangled Ada names
28049 in the definition file of the Ada DLL
28050 (@pxref{Creating the Definition File}).
28052 @node Ada DLLs and Elaboration
28053 @subsection Ada DLLs and Elaboration
28054 @cindex DLLs and elaboration
28056 @noindent
28057 The DLL that you are building contains your Ada code as well as all the
28058 routines in the Ada library that are needed by it. The first thing a
28059 user of your DLL must do is elaborate the Ada code
28060 (@pxref{Elaboration Order Handling in GNAT}).
28062 To achieve this you must export an initialization routine
28063 (@code{Initialize_API} in the previous example), which must be invoked
28064 before using any of the DLL services. This elaboration routine must call
28065 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28066 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28067 @code{Initialize_Api} for an example. Note that the GNAT binder is
28068 automatically invoked during the DLL build process by the @code{gnatdll}
28069 tool (@pxref{Using gnatdll}).
28071 When a DLL is loaded, Windows systematically invokes a routine called
28072 @code{DllMain}. It would therefore be possible to call @code{adainit}
28073 directly from @code{DllMain} without having to provide an explicit
28074 initialization routine. Unfortunately, it is not possible to call
28075 @code{adainit} from the @code{DllMain} if your program has library level
28076 tasks because access to the @code{DllMain} entry point is serialized by
28077 the system (that is, only a single thread can execute ``through'' it at a
28078 time), which means that the GNAT run time will deadlock waiting for the
28079 newly created task to complete its initialization.
28081 @node Ada DLLs and Finalization
28082 @subsection Ada DLLs and Finalization
28083 @cindex DLLs and finalization
28085 @noindent
28086 When the services of an Ada DLL are no longer needed, the client code should
28087 invoke the DLL finalization routine, if available. The DLL finalization
28088 routine is in charge of releasing all resources acquired by the DLL. In the
28089 case of the Ada code contained in the DLL, this is achieved by calling
28090 routine @code{adafinal} generated by the GNAT binder
28091 (@pxref{Binding with Non-Ada Main Programs}).
28092 See the body of @code{Finalize_Api} for an
28093 example. As already pointed out the GNAT binder is automatically invoked
28094 during the DLL build process by the @code{gnatdll} tool
28095 (@pxref{Using gnatdll}).
28097 @node Creating a Spec for Ada DLLs
28098 @subsection Creating a Spec for Ada DLLs
28100 @noindent
28101 To use the services exported by the Ada DLL from another programming
28102 language (e.g. C), you have to translate the specs of the exported Ada
28103 entities in that language. For instance in the case of @code{API.dll},
28104 the corresponding C header file could look like:
28106 @smallexample
28107 @group
28108 @cartouche
28109 extern int *_imp__count;
28110 #define count (*_imp__count)
28111 int factorial (int);
28112 @end cartouche
28113 @end group
28114 @end smallexample
28116 @noindent
28117 It is important to understand that when building an Ada DLL to be used by
28118 other Ada applications, you need two different specs for the packages
28119 contained in the DLL: one for building the DLL and the other for using
28120 the DLL. This is because the @code{DLL} calling convention is needed to
28121 use a variable defined in a DLL, but when building the DLL, the variable
28122 must have either the @code{Ada} or @code{C} calling convention. As an
28123 example consider a DLL comprising the following package @code{API}:
28125 @smallexample @c ada
28126 @group
28127 @cartouche
28128 package API is
28129    Count : Integer := 0;
28130    ...
28131    --  Remainder of the package omitted.
28132 end API;
28133 @end cartouche
28134 @end group
28135 @end smallexample
28137 @noindent
28138 After producing a DLL containing package @code{API}, the spec that
28139 must be used to import @code{API.Count} from Ada code outside of the
28140 DLL is:
28142 @smallexample @c ada
28143 @group
28144 @cartouche
28145 package API is
28146    Count : Integer;
28147    pragma Import (DLL, Count);
28148 end API;
28149 @end cartouche
28150 @end group
28151 @end smallexample
28153 @node Creating the Definition File
28154 @subsection Creating the Definition File
28156 @noindent
28157 The definition file is the last file needed to build the DLL. It lists
28158 the exported symbols. As an example, the definition file for a DLL
28159 containing only package @code{API} (where all the entities are exported
28160 with a @code{C} calling convention) is:
28162 @smallexample
28163 @group
28164 @cartouche
28165 EXPORTS
28166     count
28167     factorial
28168     finalize_api
28169     initialize_api
28170 @end cartouche
28171 @end group
28172 @end smallexample
28174 @noindent
28175 If the @code{C} calling convention is missing from package @code{API},
28176 then the definition file contains the mangled Ada names of the above
28177 entities, which in this case are:
28179 @smallexample
28180 @group
28181 @cartouche
28182 EXPORTS
28183     api__count
28184     api__factorial
28185     api__finalize_api
28186     api__initialize_api
28187 @end cartouche
28188 @end group
28189 @end smallexample
28191 @node Using gnatdll
28192 @subsection Using @code{gnatdll}
28193 @findex gnatdll
28195 @menu
28196 * gnatdll Example::
28197 * gnatdll behind the Scenes::
28198 * Using dlltool::
28199 @end menu
28201 @noindent
28202 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28203 and non-Ada sources that make up your DLL have been compiled.
28204 @code{gnatdll} is actually in charge of two distinct tasks: build the
28205 static import library for the DLL and the actual DLL. The form of the
28206 @code{gnatdll} command is
28208 @smallexample
28209 @cartouche
28210 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
28211 @end cartouche
28212 @end smallexample
28214 @noindent
28215 where @i{list-of-files} is a list of ALI and object files. The object
28216 file list must be the exact list of objects corresponding to the non-Ada
28217 sources whose services are to be included in the DLL. The ALI file list
28218 must be the exact list of ALI files for the corresponding Ada sources
28219 whose services are to be included in the DLL. If @i{list-of-files} is
28220 missing, only the static import library is generated.
28222 @noindent
28223 You may specify any of the following switches to @code{gnatdll}:
28225 @table @code
28226 @item -a[@var{address}]
28227 @cindex @option{-a} (@code{gnatdll})
28228 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28229 specified the default address @var{0x11000000} will be used. By default,
28230 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28231 advise the reader to build relocatable DLL.
28233 @item -b @var{address}
28234 @cindex @option{-b} (@code{gnatdll})
28235 Set the relocatable DLL base address. By default the address is
28236 @var{0x11000000}.
28238 @item -bargs @var{opts}
28239 @cindex @option{-bargs} (@code{gnatdll})
28240 Binder options. Pass @var{opts} to the binder.
28242 @item -d @var{dllfile}
28243 @cindex @option{-d} (@code{gnatdll})
28244 @var{dllfile} is the name of the DLL. This switch must be present for
28245 @code{gnatdll} to do anything. The name of the generated import library is
28246 obtained algorithmically from @var{dllfile} as shown in the following
28247 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28248 @code{libxyz.a}. The name of the definition file to use (if not specified
28249 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28250 as shown in the following example:
28251 if @var{dllfile} is @code{xyz.dll}, the definition
28252 file used is @code{xyz.def}.
28254 @item -e @var{deffile}
28255 @cindex @option{-e} (@code{gnatdll})
28256 @var{deffile} is the name of the definition file.
28258 @item -g
28259 @cindex @option{-g} (@code{gnatdll})
28260 Generate debugging information. This information is stored in the object
28261 file and copied from there to the final DLL file by the linker,
28262 where it can be read by the debugger. You must use the
28263 @option{-g} switch if you plan on using the debugger or the symbolic
28264 stack traceback.
28266 @item -h
28267 @cindex @option{-h} (@code{gnatdll})
28268 Help mode. Displays @code{gnatdll} switch usage information.
28270 @item -Idir
28271 @cindex @option{-I} (@code{gnatdll})
28272 Direct @code{gnatdll} to search the @var{dir} directory for source and
28273 object files needed to build the DLL.
28274 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28276 @item -k
28277 @cindex @option{-k} (@code{gnatdll})
28278 Removes the @code{@@}@i{nn} suffix from the import library's exported
28279 names, but keeps them for the link names. You must specify this
28280 option if you want to use a @code{Stdcall} function in a DLL for which
28281 the @code{@@}@i{nn} suffix has been removed. This is the case for most
28282 of the Windows NT DLL for example. This option has no effect when
28283 @option{-n} option is specified.
28285 @item -l @var{file}
28286 @cindex @option{-l} (@code{gnatdll})
28287 The list of ALI and object files used to build the DLL are listed in
28288 @var{file}, instead of being given in the command line. Each line in
28289 @var{file} contains the name of an ALI or object file.
28291 @item -n
28292 @cindex @option{-n} (@code{gnatdll})
28293 No Import. Do not create the import library.
28295 @item -q
28296 @cindex @option{-q} (@code{gnatdll})
28297 Quiet mode. Do not display unnecessary messages.
28299 @item -v
28300 @cindex @option{-v} (@code{gnatdll})
28301 Verbose mode. Display extra information.
28303 @item -largs @var{opts}
28304 @cindex @option{-largs} (@code{gnatdll})
28305 Linker options. Pass @var{opts} to the linker.
28306 @end table
28308 @node gnatdll Example
28309 @subsubsection @code{gnatdll} Example
28311 @noindent
28312 As an example the command to build a relocatable DLL from @file{api.adb}
28313 once @file{api.adb} has been compiled and @file{api.def} created is
28315 @smallexample
28316 $ gnatdll -d api.dll api.ali
28317 @end smallexample
28319 @noindent
28320 The above command creates two files: @file{libapi.a} (the import
28321 library) and @file{api.dll} (the actual DLL). If you want to create
28322 only the DLL, just type:
28324 @smallexample
28325 $ gnatdll -d api.dll -n api.ali
28326 @end smallexample
28328 @noindent
28329 Alternatively if you want to create just the import library, type:
28331 @smallexample
28332 $ gnatdll -d api.dll
28333 @end smallexample
28335 @node gnatdll behind the Scenes
28336 @subsubsection @code{gnatdll} behind the Scenes
28338 @noindent
28339 This section details the steps involved in creating a DLL. @code{gnatdll}
28340 does these steps for you. Unless you are interested in understanding what
28341 goes on behind the scenes, you should skip this section.
28343 We use the previous example of a DLL containing the Ada package @code{API},
28344 to illustrate the steps necessary to build a DLL. The starting point is a
28345 set of objects that will make up the DLL and the corresponding ALI
28346 files. In the case of this example this means that @file{api.o} and
28347 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28348 the following:
28350 @enumerate
28351 @item
28352 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28353 the information necessary to generate relocation information for the
28354 DLL.
28356 @smallexample
28357 @group
28358 $ gnatbind -n api
28359 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28360 @end group
28361 @end smallexample
28363 @noindent
28364 In addition to the base file, the @command{gnatlink} command generates an
28365 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28366 asks @command{gnatlink} to generate the routines @code{DllMain} and
28367 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28368 is loaded into memory.
28370 @item
28371 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28372 export table (@file{api.exp}). The export table contains the relocation
28373 information in a form which can be used during the final link to ensure
28374 that the Windows loader is able to place the DLL anywhere in memory.
28376 @smallexample
28377 @group
28378 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28379           --output-exp api.exp
28380 @end group
28381 @end smallexample
28383 @item
28384 @code{gnatdll} builds the base file using the new export table. Note that
28385 @command{gnatbind} must be called once again since the binder generated file
28386 has been deleted during the previous call to @command{gnatlink}.
28388 @smallexample
28389 @group
28390 $ gnatbind -n api
28391 $ gnatlink api -o api.jnk api.exp -mdll
28392       -Wl,--base-file,api.base
28393 @end group
28394 @end smallexample
28396 @item
28397 @code{gnatdll} builds the new export table using the new base file and
28398 generates the DLL import library @file{libAPI.a}.
28400 @smallexample
28401 @group
28402 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28403           --output-exp api.exp --output-lib libAPI.a
28404 @end group
28405 @end smallexample
28407 @item
28408 Finally @code{gnatdll} builds the relocatable DLL using the final export
28409 table.
28411 @smallexample
28412 @group
28413 $ gnatbind -n api
28414 $ gnatlink api api.exp -o api.dll -mdll
28415 @end group
28416 @end smallexample
28417 @end enumerate
28419 @node Using dlltool
28420 @subsubsection Using @code{dlltool}
28422 @noindent
28423 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28424 DLLs and static import libraries. This section summarizes the most
28425 common @code{dlltool} switches. The form of the @code{dlltool} command
28428 @smallexample
28429 $ dlltool [@var{switches}]
28430 @end smallexample
28432 @noindent
28433 @code{dlltool} switches include:
28435 @table @option
28436 @item --base-file @var{basefile}
28437 @cindex @option{--base-file} (@command{dlltool})
28438 Read the base file @var{basefile} generated by the linker. This switch
28439 is used to create a relocatable DLL.
28441 @item --def @var{deffile}
28442 @cindex @option{--def} (@command{dlltool})
28443 Read the definition file.
28445 @item --dllname @var{name}
28446 @cindex @option{--dllname} (@command{dlltool})
28447 Gives the name of the DLL. This switch is used to embed the name of the
28448 DLL in the static import library generated by @code{dlltool} with switch
28449 @option{--output-lib}.
28451 @item -k
28452 @cindex @option{-k} (@command{dlltool})
28453 Kill @code{@@}@i{nn} from exported names
28454 (@pxref{Windows Calling Conventions}
28455 for a discussion about @code{Stdcall}-style symbols.
28457 @item --help
28458 @cindex @option{--help} (@command{dlltool})
28459 Prints the @code{dlltool} switches with a concise description.
28461 @item --output-exp @var{exportfile}
28462 @cindex @option{--output-exp} (@command{dlltool})
28463 Generate an export file @var{exportfile}. The export file contains the
28464 export table (list of symbols in the DLL) and is used to create the DLL.
28466 @item --output-lib @i{libfile}
28467 @cindex @option{--output-lib} (@command{dlltool})
28468 Generate a static import library @var{libfile}.
28470 @item -v
28471 @cindex @option{-v} (@command{dlltool})
28472 Verbose mode.
28474 @item --as @i{assembler-name}
28475 @cindex @option{--as} (@command{dlltool})
28476 Use @i{assembler-name} as the assembler. The default is @code{as}.
28477 @end table
28479 @node GNAT and Windows Resources
28480 @section GNAT and Windows Resources
28481 @cindex Resources, windows
28483 @menu
28484 * Building Resources::
28485 * Compiling Resources::
28486 * Using Resources::
28487 @end menu
28489 @noindent
28490 Resources are an easy way to add Windows specific objects to your
28491 application. The objects that can be added as resources include:
28493 @itemize @bullet
28494 @item
28495 menus
28497 @item
28498 accelerators
28500 @item
28501 dialog boxes
28503 @item
28504 string tables
28506 @item
28507 bitmaps
28509 @item
28510 cursors
28512 @item
28513 icons
28515 @item
28516 fonts
28517 @end itemize
28519 @noindent
28520 This section explains how to build, compile and use resources.
28522 @node Building Resources
28523 @subsection Building Resources
28524 @cindex Resources, building
28526 @noindent
28527 A resource file is an ASCII file. By convention resource files have an
28528 @file{.rc} extension.
28529 The easiest way to build a resource file is to use Microsoft tools
28530 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28531 @code{dlgedit.exe} to build dialogs.
28532 It is always possible to build an @file{.rc} file yourself by writing a
28533 resource script.
28535 It is not our objective to explain how to write a resource file. A
28536 complete description of the resource script language can be found in the
28537 Microsoft documentation.
28539 @node Compiling Resources
28540 @subsection Compiling Resources
28541 @findex rc
28542 @findex windres
28543 @cindex Resources, compiling
28545 @noindent
28546 This section describes how to build a GNAT-compatible (COFF) object file
28547 containing the resources. This is done using the Resource Compiler
28548 @code{windres} as follows:
28550 @smallexample
28551 $ windres -i myres.rc -o myres.o
28552 @end smallexample
28554 @noindent
28555 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28556 file. You can specify an alternate preprocessor (usually named
28557 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28558 parameter. A list of all possible options may be obtained by entering
28559 the command @code{windres} @option{--help}.
28561 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28562 to produce a @file{.res} file (binary resource file). See the
28563 corresponding Microsoft documentation for further details. In this case
28564 you need to use @code{windres} to translate the @file{.res} file to a
28565 GNAT-compatible object file as follows:
28567 @smallexample
28568 $ windres -i myres.res -o myres.o
28569 @end smallexample
28571 @node Using Resources
28572 @subsection Using Resources
28573 @cindex Resources, using
28575 @noindent
28576 To include the resource file in your program just add the
28577 GNAT-compatible object file for the resource(s) to the linker
28578 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28579 option:
28581 @smallexample
28582 $ gnatmake myprog -largs myres.o
28583 @end smallexample
28585 @node Debugging a DLL
28586 @section Debugging a DLL
28587 @cindex DLL debugging
28589 @menu
28590 * Program and DLL Both Built with GCC/GNAT::
28591 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28592 @end menu
28594 @noindent
28595 Debugging a DLL is similar to debugging a standard program. But
28596 we have to deal with two different executable parts: the DLL and the
28597 program that uses it. We have the following four possibilities:
28599 @enumerate 1
28600 @item
28601 The program and the DLL are built with @code{GCC/GNAT}.
28602 @item
28603 The program is built with foreign tools and the DLL is built with
28604 @code{GCC/GNAT}.
28605 @item
28606 The program is built with @code{GCC/GNAT} and the DLL is built with
28607 foreign tools.
28608 @item
28609 @end enumerate
28611 @noindent
28612 In this section we address only cases one and two above.
28613 There is no point in trying to debug
28614 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28615 information in it. To do so you must use a debugger compatible with the
28616 tools suite used to build the DLL.
28618 @node Program and DLL Both Built with GCC/GNAT
28619 @subsection Program and DLL Both Built with GCC/GNAT
28621 @noindent
28622 This is the simplest case. Both the DLL and the program have @code{GDB}
28623 compatible debugging information. It is then possible to break anywhere in
28624 the process. Let's suppose here that the main procedure is named
28625 @code{ada_main} and that in the DLL there is an entry point named
28626 @code{ada_dll}.
28628 @noindent
28629 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28630 program must have been built with the debugging information (see GNAT -g
28631 switch). Here are the step-by-step instructions for debugging it:
28633 @enumerate 1
28634 @item Launch @code{GDB} on the main program.
28636 @smallexample
28637 $ gdb -nw ada_main
28638 @end smallexample
28640 @item Start the program and stop at the beginning of the main procedure
28642 @smallexample
28643 (gdb) start
28644 @end smallexample
28646 @noindent
28647 This step is required to be able to set a breakpoint inside the DLL. As long
28648 as the program is not run, the DLL is not loaded. This has the
28649 consequence that the DLL debugging information is also not loaded, so it is not
28650 possible to set a breakpoint in the DLL.
28652 @item Set a breakpoint inside the DLL
28654 @smallexample
28655 (gdb) break ada_dll
28656 (gdb) cont
28657 @end smallexample
28659 @end enumerate
28661 @noindent
28662 At this stage a breakpoint is set inside the DLL. From there on
28663 you can use the standard approach to debug the whole program
28664 (@pxref{Running and Debugging Ada Programs}).
28666 @ignore
28667 @c This used to work, probably because the DLLs were non-relocatable
28668 @c keep this section around until the problem is sorted out.
28670 To break on the @code{DllMain} routine it is not possible to follow
28671 the procedure above. At the time the program stop on @code{ada_main}
28672 the @code{DllMain} routine as already been called. Either you can use
28673 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28675 @enumerate 1
28676 @item Launch @code{GDB} on the main program.
28678 @smallexample
28679 $ gdb ada_main
28680 @end smallexample
28682 @item Load DLL symbols
28684 @smallexample
28685 (gdb) add-sym api.dll
28686 @end smallexample
28688 @item Set a breakpoint inside the DLL
28690 @smallexample
28691 (gdb) break ada_dll.adb:45
28692 @end smallexample
28694 Note that at this point it is not possible to break using the routine symbol
28695 directly as the program is not yet running. The solution is to break
28696 on the proper line (break in @file{ada_dll.adb} line 45).
28698 @item Start the program
28700 @smallexample
28701 (gdb) run
28702 @end smallexample
28704 @end enumerate
28705 @end ignore
28707 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28708 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28710 @menu
28711 * Debugging the DLL Directly::
28712 * Attaching to a Running Process::
28713 @end menu
28715 @noindent
28716 In this case things are slightly more complex because it is not possible to
28717 start the main program and then break at the beginning to load the DLL and the
28718 associated DLL debugging information. It is not possible to break at the
28719 beginning of the program because there is no @code{GDB} debugging information,
28720 and therefore there is no direct way of getting initial control. This
28721 section addresses this issue by describing some methods that can be used
28722 to break somewhere in the DLL to debug it.
28724 @noindent
28725 First suppose that the main procedure is named @code{main} (this is for
28726 example some C code built with Microsoft Visual C) and that there is a
28727 DLL named @code{test.dll} containing an Ada entry point named
28728 @code{ada_dll}.
28730 @noindent
28731 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28732 been built with debugging information (see GNAT -g option).
28734 @node Debugging the DLL Directly
28735 @subsubsection Debugging the DLL Directly
28737 @enumerate 1
28738 @item
28739 Find out the executable starting address
28741 @smallexample
28742 $ objdump --file-header main.exe
28743 @end smallexample
28745 The starting address is reported on the last line. For example:
28747 @smallexample
28748 main.exe:     file format pei-i386
28749 architecture: i386, flags 0x0000010a:
28750 EXEC_P, HAS_DEBUG, D_PAGED
28751 start address 0x00401010
28752 @end smallexample
28754 @item
28755 Launch the debugger on the executable.
28757 @smallexample
28758 $ gdb main.exe
28759 @end smallexample
28761 @item
28762 Set a breakpoint at the starting address, and launch the program.
28764 @smallexample
28765 $ (gdb) break *0x00401010
28766 $ (gdb) run
28767 @end smallexample
28769 The program will stop at the given address.
28771 @item
28772 Set a breakpoint on a DLL subroutine.
28774 @smallexample
28775 (gdb) break ada_dll.adb:45
28776 @end smallexample
28778 Or if you want to break using a symbol on the DLL, you need first to
28779 select the Ada language (language used by the DLL).
28781 @smallexample
28782 (gdb) set language ada
28783 (gdb) break ada_dll
28784 @end smallexample
28786 @item
28787 Continue the program.
28789 @smallexample
28790 (gdb) cont
28791 @end smallexample
28793 @noindent
28794 This will run the program until it reaches the breakpoint that has been
28795 set. From that point you can use the standard way to debug a program
28796 as described in (@pxref{Running and Debugging Ada Programs}).
28798 @end enumerate
28800 @noindent
28801 It is also possible to debug the DLL by attaching to a running process.
28803 @node Attaching to a Running Process
28804 @subsubsection Attaching to a Running Process
28805 @cindex DLL debugging, attach to process
28807 @noindent
28808 With @code{GDB} it is always possible to debug a running process by
28809 attaching to it. It is possible to debug a DLL this way. The limitation
28810 of this approach is that the DLL must run long enough to perform the
28811 attach operation. It may be useful for instance to insert a time wasting
28812 loop in the code of the DLL to meet this criterion.
28814 @enumerate 1
28816 @item Launch the main program @file{main.exe}.
28818 @smallexample
28819 $ main
28820 @end smallexample
28822 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28823 that the process PID for @file{main.exe} is 208.
28825 @item Launch gdb.
28827 @smallexample
28828 $ gdb
28829 @end smallexample
28831 @item Attach to the running process to be debugged.
28833 @smallexample
28834 (gdb) attach 208
28835 @end smallexample
28837 @item Load the process debugging information.
28839 @smallexample
28840 (gdb) symbol-file main.exe
28841 @end smallexample
28843 @item Break somewhere in the DLL.
28845 @smallexample
28846 (gdb) break ada_dll
28847 @end smallexample
28849 @item Continue process execution.
28851 @smallexample
28852 (gdb) cont
28853 @end smallexample
28855 @end enumerate
28857 @noindent
28858 This last step will resume the process execution, and stop at
28859 the breakpoint we have set. From there you can use the standard
28860 approach to debug a program as described in
28861 (@pxref{Running and Debugging Ada Programs}).
28863 @node Setting Stack Size from gnatlink
28864 @section Setting Stack Size from @command{gnatlink}
28866 @noindent
28867 It is possible to specify the program stack size at link time. On modern
28868 versions of Windows, starting with XP, this is mostly useful to set the size of
28869 the main stack (environment task). The other task stacks are set with pragma
28870 Linker_Options or with gnatbind -d. On older versions of Windows (2000, NT4,
28871 etc.), it is not possible to set the reserve size of individual tasks and thus
28872 the link-time stack size applies to all tasks.
28874 This setting can be done with
28875 @command{gnatlink} using either:
28877 @itemize @bullet
28879 @item using @option{-Xlinker} linker option
28881 @smallexample
28882 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
28883 @end smallexample
28885 This sets the stack reserve size to 0x10000 bytes and the stack commit
28886 size to 0x1000 bytes.
28888 @item using @option{-Wl} linker option
28890 @smallexample
28891 $ gnatlink hello -Wl,--stack=0x1000000
28892 @end smallexample
28894 This sets the stack reserve size to 0x1000000 bytes. Note that with
28895 @option{-Wl} option it is not possible to set the stack commit size
28896 because the coma is a separator for this option.
28898 @end itemize
28900 @node Setting Heap Size from gnatlink
28901 @section Setting Heap Size from @command{gnatlink}
28903 @noindent
28904 Under Windows systems, it is possible to specify the program heap size from
28905 @command{gnatlink} using either:
28907 @itemize @bullet
28909 @item using @option{-Xlinker} linker option
28911 @smallexample
28912 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
28913 @end smallexample
28915 This sets the heap reserve size to 0x10000 bytes and the heap commit
28916 size to 0x1000 bytes.
28918 @item using @option{-Wl} linker option
28920 @smallexample
28921 $ gnatlink hello -Wl,--heap=0x1000000
28922 @end smallexample
28924 This sets the heap reserve size to 0x1000000 bytes. Note that with
28925 @option{-Wl} option it is not possible to set the heap commit size
28926 because the coma is a separator for this option.
28928 @end itemize
28931 @end ifset
28933 @c **********************************
28934 @c * GNU Free Documentation License *
28935 @c **********************************
28936 @include fdl.texi
28937 @c GNU Free Documentation License
28939 @node Index,,GNU Free Documentation License, Top
28940 @unnumbered Index
28942 @printindex cp
28944 @contents
28945 @c Put table of contents at end, otherwise it precedes the "title page" in
28946 @c the .txt version
28947 @c Edit the pdf file to move the contents to the beginning, after the title
28948 @c page
28950 @bye