PR target/16201
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob93f221345d4c2706c7064038877fbb08f2a4150e
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c          Copyright (C) 1992-2005 Ada Core Technologies, Inc.               o
11 @c                                                                            o
12 @c  GNAT is free software;  you can  redistribute it  and/or modify it under  o
13 @c  terms of the  GNU General Public License as published  by the Free Soft-  o
14 @c  ware  Foundation;  either version 2,  or (at your option) any later ver-  o
15 @c  sion.  GNAT is distributed in the hope that it will be useful, but WITH-  o
16 @c  OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY  o
17 @c  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License  o
18 @c  for  more details.  You should have  received  a copy of the GNU General  o
19 @c  Public License  distributed with GNAT;  see file COPYING.  If not, write  o
20 @c  to  the Free Software Foundation,  59 Temple Place - Suite 330,  Boston,  o
21 @c  MA 02111-1307, USA.                                                       o
22 @c                                                                            o
23 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
25 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
27 @c                           GNAT_UGN Style Guide
29 @c  1. Always put a @noindent on the line before the first paragraph
30 @c     after any of these commands:
32 @c          @chapter
33 @c          @section
34 @c          @subsection
35 @c          @subsubsection
36 @c          @subsubsubsection
38 @c          @end smallexample
39 @c          @end itemize
40 @c          @end enumerate
42 @c  2. DO NOT use @example. Use @smallexample instead.
43 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
44 @c        context.  These can interfere with the readability of the texi
45 @c        source file.  Instead, use one of the following annotated
46 @c        @smallexample commands, and preprocess the texi file with the
47 @c        ada2texi tool (which generates appropriate highlighting):
48 @c        @smallexample @c ada
49 @c        @smallexample @c adanocomment
50 @c        @smallexample @c projectfile
51 @c     b) The "@c ada" markup will result in boldface for reserved words
52 @c        and italics for comments
53 @c     c) The "@c adanocomment" markup will result only in boldface for
54 @c        reserved words (comments are left alone)
55 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
56 @c        of reserved words include the new reserved words for project files
58 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
59 @c     command must be preceded by two empty lines
61 @c  4. The @item command should be on a line of its own if it is in an
62 @c     @itemize or @enumerate command.
64 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
65 @c     or "ali".
67 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
68 @c     cause the document build to fail.
70 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
71 @c     This command inhibits page breaks, so long examples in a @cartouche can
72 @c     lead to large, ugly patches of empty space on a page.
74 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
75 @c        or the unw flag set.  The unw flag covers topics for both Unix and
76 @c        Windows.
78 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
80 @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 * Creating Sample Bodies Using gnatstub::
195 * Other Utility Programs::
196 * Running and Debugging Ada Programs::
197 @ifset vms
198 * Compatibility with DEC Ada::
199 @end ifset
200 * Platform-Specific Information for the Run-Time Libraries::
201 * Example of Binder Output File::
202 * Elaboration Order Handling in GNAT::
203 * Inline Assembler::
204 * Compatibility and Porting Guide::
205 @ifset unw
206 * Microsoft Windows Topics::
207 @end ifset
208 * GNU Free Documentation License::
209 * Index::
211  --- The Detailed Node Listing ---
213 About This Guide
215 * What This Guide Contains::
216 * What You Should Know before Reading This Guide::
217 * Related Information::
218 * Conventions::
220 Getting Started with GNAT
222 * Running GNAT::
223 * Running a Simple Ada Program::
224 * Running a Program with Multiple Units::
225 * Using the gnatmake Utility::
226 @ifset vms
227 * Editing with Emacs::
228 @end ifset
229 @ifclear vms
230 * Introduction to GPS::
231 * Introduction to Glide and GVD::
232 @end ifclear
234 The GNAT Compilation Model
236 * Source Representation::
237 * Foreign Language Representation::
238 * File Naming Rules::
239 * Using Other File Names::
240 * Alternative File Naming Schemes::
241 * Generating Object Files::
242 * Source Dependencies::
243 * The Ada Library Information Files::
244 * Binding an Ada Program::
245 * Mixed Language Programming::
246 * Building Mixed Ada & C++ Programs::
247 * Comparison between GNAT and C/C++ Compilation Models::
248 * Comparison between GNAT and Conventional Ada Library Models::
249 @ifset vms
250 * Placement of temporary files::
251 @end ifset
253 Foreign Language Representation
255 * Latin-1::
256 * Other 8-Bit Codes::
257 * Wide Character Encodings::
259 Compiling Ada Programs With gcc
261 * Compiling Programs::
262 * Switches for gcc::
263 * Search Paths and the Run-Time Library (RTL)::
264 * Order of Compilation Issues::
265 * Examples::
267 Switches for gcc
269 * Output and Error Message Control::
270 * Warning Message Control::
271 * Debugging and Assertion Control::
272 * Validity Checking::
273 * Style Checking::
274 * Run-Time Checks::
275 * Stack Overflow Checking::
276 * Using gcc for Syntax Checking::
277 * Using gcc for Semantic Checking::
278 * Compiling Ada 83 Programs::
279 * Character Set Control::
280 * File Naming Control::
281 * Subprogram Inlining Control::
282 * Auxiliary Output Control::
283 * Debugging Control::
284 * Exception Handling Control::
285 * Units to Sources Mapping Files::
286 * Integrated Preprocessing::
287 @ifset vms
288 * Return Codes::
289 @end ifset
291 Binding Ada Programs With gnatbind
293 * Running gnatbind::
294 * Switches for gnatbind::
295 * Command-Line Access::
296 * Search Paths for gnatbind::
297 * Examples of gnatbind Usage::
299 Switches for gnatbind
301 * Consistency-Checking Modes::
302 * Binder Error Message Control::
303 * Elaboration Control::
304 * Output Control::
305 * Binding with Non-Ada Main Programs::
306 * Binding Programs with No Main Subprogram::
308 Linking Using gnatlink
310 * Running gnatlink::
311 * Switches for gnatlink::
312 * Setting Stack Size from gnatlink::
313 * Setting Heap Size from gnatlink::
315 The GNAT Make Program gnatmake
317 * Running gnatmake::
318 * Switches for gnatmake::
319 * Mode Switches for gnatmake::
320 * Notes on the Command Line::
321 * How gnatmake Works::
322 * Examples of gnatmake Usage::
324 Improving Performance
325 * Performance Considerations::
326 * Reducing the Size of Ada Executables with gnatelim::
328 Performance Considerations
329 * Controlling Run-Time Checks::
330 * Use of Restrictions::
331 * Optimization Levels::
332 * Debugging Optimized Code::
333 * Inlining of Subprograms::
334 * Optimization and Strict Aliasing::
335 @ifset vms
336 * Coverage Analysis::
337 @end ifset
339 Reducing the Size of Ada Executables with gnatelim
340 * About gnatelim::
341 * Running gnatelim::
342 * Correcting the List of Eliminate Pragmas::
343 * Making Your Executables Smaller::
344 * Summary of the gnatelim Usage Cycle::
346 Renaming Files Using gnatchop
348 * Handling Files with Multiple Units::
349 * Operating gnatchop in Compilation Mode::
350 * Command Line for gnatchop::
351 * Switches for gnatchop::
352 * Examples of gnatchop Usage::
354 Configuration Pragmas
356 * Handling of Configuration Pragmas::
357 * The Configuration Pragmas Files::
359 Handling Arbitrary File Naming Conventions Using gnatname
361 * Arbitrary File Naming Conventions::
362 * Running gnatname::
363 * Switches for gnatname::
364 * Examples of gnatname Usage::
366 GNAT Project Manager
368 * Introduction::
369 * Examples of Project Files::
370 * Project File Syntax::
371 * Objects and Sources in Project Files::
372 * Importing Projects::
373 * Project Extension::
374 * Project Hierarchy Extension::
375 * External References in Project Files::
376 * Packages in Project Files::
377 * Variables from Imported Projects::
378 * Naming Schemes::
379 * Library Projects::
380 * Using Third-Party Libraries through Projects::
381 * Stand-alone Library Projects::
382 * Switches Related to Project Files::
383 * Tools Supporting Project Files::
384 * An Extended Example::
385 * Project File Complete Syntax::
387 The Cross-Referencing Tools gnatxref and gnatfind
389 * gnatxref Switches::
390 * gnatfind Switches::
391 * Project Files for gnatxref and gnatfind::
392 * Regular Expressions in gnatfind and gnatxref::
393 * Examples of gnatxref Usage::
394 * Examples of gnatfind Usage::
396 The GNAT Pretty-Printer gnatpp
398 * Switches for gnatpp::
399 * Formatting Rules::
401 The GNAT Metrics Tool gnatmetric
403 * Switches for gnatmetric::
405 File Name Krunching Using gnatkr
407 * About gnatkr::
408 * Using gnatkr::
409 * Krunching Method::
410 * Examples of gnatkr Usage::
412 Preprocessing Using gnatprep
414 * Using gnatprep::
415 * Switches for gnatprep::
416 * Form of Definitions File::
417 * Form of Input Text for gnatprep::
419 @ifset vms
420 The GNAT Run-Time Library Builder gnatlbr
422 * Running gnatlbr::
423 * Switches for gnatlbr::
424 * Examples of gnatlbr Usage::
425 @end ifset
427 The GNAT Library Browser gnatls
429 * Running gnatls::
430 * Switches for gnatls::
431 * Examples of gnatls Usage::
433 Cleaning Up Using gnatclean
435 * Running gnatclean::
436 * Switches for gnatclean::
437 * Examples of gnatclean Usage::
439 @ifclear vms
441 GNAT and Libraries
443 * Introduction to Libraries in GNAT::
444 * General Ada Libraries::
445 * Stand-alone Ada Libraries::
446 * Rebuilding the GNAT Run-Time Library::
448 Using the GNU make Utility
450 * Using gnatmake in a Makefile::
451 * Automatically Creating a List of Directories::
452 * Generating the Command Line Switches::
453 * Overcoming Command Line Length Limits::
454 @end ifclear
456 Memory Management Issues
458 * Some Useful Memory Pools::
459 * The GNAT Debug Pool Facility::
460 @ifclear vms
461 * The gnatmem Tool::
462 @end ifclear
464 Some Useful Memory Pools
466 The GNAT Debug Pool Facility
468 @ifclear vms
469 The gnatmem Tool
471 * Running gnatmem::
472 * Switches for gnatmem::
473 * Example of gnatmem Usage::
474 @end ifclear
476  Sample Bodies Using gnatstub
478 * Running gnatstub::
479 * Switches for gnatstub::
481 Other Utility Programs
483 * Using Other Utility Programs with GNAT::
484 * The External Symbol Naming Scheme of GNAT::
485 @ifclear vms
486 * Ada Mode for Glide::
487 @end ifclear
488 * Converting Ada Files to html with gnathtml::
490 Running and Debugging Ada Programs
492 * The GNAT Debugger GDB::
493 * Running GDB::
494 * Introduction to GDB Commands::
495 * Using Ada Expressions::
496 * Calling User-Defined Subprograms::
497 * Using the Next Command in a Function::
498 * Ada Exceptions::
499 * Ada Tasks::
500 * Debugging Generic Units::
501 * GNAT Abnormal Termination or Failure to Terminate::
502 * Naming Conventions for GNAT Source Files::
503 * Getting Internal Debugging Information::
504 * Stack Traceback::
506 @ifset vms
507 * LSE::
508 @end ifset
510 @ifset vms
511 Compatibility with DEC Ada
513 * Ada 95 Compatibility::
514 * Differences in the Definition of Package System::
515 * Language-Related Features::
516 * The Package STANDARD::
517 * The Package SYSTEM::
518 * Tasking and Task-Related Features::
519 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
520 * Pragmas and Pragma-Related Features::
521 * Library of Predefined Units::
522 * Bindings::
523 * Main Program Definition::
524 * Implementation-Defined Attributes::
525 * Compiler and Run-Time Interfacing::
526 * Program Compilation and Library Management::
527 * Input-Output::
528 * Implementation Limits::
529 * Tools::
531 Language-Related Features
533 * Integer Types and Representations::
534 * Floating-Point Types and Representations::
535 * Pragmas Float_Representation and Long_Float::
536 * Fixed-Point Types and Representations::
537 * Record and Array Component Alignment::
538 * Address Clauses::
539 * Other Representation Clauses::
541 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
543 * Assigning Task IDs::
544 * Task IDs and Delays::
545 * Task-Related Pragmas::
546 * Scheduling and Task Priority::
547 * The Task Stack::
548 * External Interrupts::
550 Pragmas and Pragma-Related Features
552 * Restrictions on the Pragma INLINE::
553 * Restrictions on the Pragma INTERFACE::
554 * Restrictions on the Pragma SYSTEM_NAME::
556 Library of Predefined Units
558 * Changes to DECLIB::
560 Bindings
562 * Shared Libraries and Options Files::
563 * Interfaces to C::
564 @end ifset
566 Platform-Specific Information for the Run-Time Libraries
568 * Summary of Run-Time Configurations::
569 * Specifying a Run-Time Library::
570 * Choosing between Native and FSU Threads Libraries::
571 * Choosing the Scheduling Policy::
572 * Solaris-Specific Considerations::
573 * IRIX-Specific Considerations::
574 * Linux-Specific Considerations::
575 * AIX-Specific Considerations::
577 Example of Binder Output File
579 Elaboration Order Handling in GNAT
581 * Elaboration Code in Ada 95::
582 * Checking the Elaboration Order in Ada 95::
583 * Controlling the Elaboration Order in Ada 95::
584 * Controlling Elaboration in GNAT - Internal Calls::
585 * Controlling Elaboration in GNAT - External Calls::
586 * Default Behavior in GNAT - Ensuring Safety::
587 * Treatment of Pragma Elaborate::
588 * Elaboration Issues for Library Tasks::
589 * Mixing Elaboration Models::
590 * What to Do If the Default Elaboration Behavior Fails::
591 * Elaboration for Access-to-Subprogram Values::
592 * Summary of Procedures for Elaboration Control::
593 * Other Elaboration Order Considerations::
595 Inline Assembler
597 * Basic Assembler Syntax::
598 * A Simple Example of Inline Assembler::
599 * Output Variables in Inline Assembler::
600 * Input Variables in Inline Assembler::
601 * Inlining Inline Assembler Code::
602 * Other Asm Functionality::
603 * A Complete Example::
605 Compatibility and Porting Guide
607 * Compatibility with Ada 83::
608 * Implementation-dependent characteristics::
609 * Compatibility with DEC Ada 83::
610 * Compatibility with Other Ada 95 Systems::
611 * Representation Clauses::
612 @ifset vms
613 * Transitioning from Alpha to Integrity OpenVMS::
614 @end ifset
616 @ifset unw
617 Microsoft Windows Topics
619 * Using GNAT on Windows::
620 * CONSOLE and WINDOWS subsystems::
621 * Temporary Files::
622 * Mixed-Language Programming on Windows::
623 * Windows Calling Conventions::
624 * Introduction to Dynamic Link Libraries (DLLs)::
625 * Using DLLs with GNAT::
626 * Building DLLs with GNAT::
627 * GNAT and Windows Resources::
628 * Debugging a DLL::
629 * GNAT and COM/DCOM Objects::
630 @end ifset
632 * Index::
633 @end menu
634 @end ifnottex
636 @node About This Guide
637 @unnumbered About This Guide
639 @noindent
640 @ifset vms
641 This guide describes the use of @value{EDITION},
642 a full language compiler for the Ada
643 95 programming language, implemented on HP's Alpha and
644 Integrity (ia64) OpenVMS platforms.
645 @end ifset
646 @ifclear vms
647 This guide describes the use of @value{EDITION},
648 a compiler and software development
649 toolset for the full Ada 95 programming language.
650 @end ifclear
651 It describes the features of the compiler and tools, and details
652 how to use them to build Ada 95 applications.
654 @ifset PROEDITION
655 For ease of exposition, ``GNAT Pro'' will be referred to simply as
656 ``GNAT'' in the remainder of this document.
657 @end ifset
659 @menu
660 * What This Guide Contains::
661 * What You Should Know before Reading This Guide::
662 * Related Information::
663 * Conventions::
664 @end menu
666 @node What This Guide Contains
667 @unnumberedsec What This Guide Contains
669 @noindent
670 This guide contains the following chapters:
671 @itemize @bullet
673 @item
674 @ref{Getting Started with GNAT}, describes how to get started compiling
675 and running Ada programs with the GNAT Ada programming environment.
676 @item
677 @ref{The GNAT Compilation Model}, describes the compilation model used
678 by GNAT.
680 @item
681 @ref{Compiling Using gcc}, describes how to compile
682 Ada programs with @code{gcc}, the Ada compiler.
684 @item
685 @ref{Binding Using gnatbind}, describes how to
686 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
687 utility.
689 @item
690 @ref{Linking Using gnatlink},
691 describes @code{gnatlink}, a
692 program that provides for linking using the GNAT run-time library to
693 construct a program. @code{gnatlink} can also incorporate foreign language
694 object units into the executable.
696 @item
697 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
698 utility that automatically determines the set of sources
699 needed by an Ada compilation unit, and executes the necessary compilations
700 binding and link.
702 @item
703 @ref{Improving Performance}, shows various techniques for making your
704 Ada program run faster or take less space.
705 It discusses the effect of the compiler's optimization switch and
706 also describes the @command{gnatelim} tool.
708 @item
709 @ref{Renaming Files Using gnatchop}, describes
710 @code{gnatchop}, a utility that allows you to preprocess a file that
711 contains Ada source code, and split it into one or more new files, one
712 for each compilation unit.
714 @item
715 @ref{Configuration Pragmas}, describes the configuration pragmas
716 handled by GNAT.
718 @item
719 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
720 shows how to override the default GNAT file naming conventions,
721 either for an individual unit or globally.
723 @item
724 @ref{GNAT Project Manager}, describes how to use project files
725 to organize large projects.
727 @item
728 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
729 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
730 way to navigate through sources.
732 @item
733 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
734 version of an Ada source file with control over casing, indentation,
735 comment placement, and other elements of program presentation style.
737 @item
738 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
739 metrics for an Ada source file, such as the number of types and subprograms,
740 and assorted complexity measures.
742 @item
743 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
744 file name krunching utility, used to handle shortened
745 file names on operating systems with a limit on the length of names.
747 @item
748 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
749 preprocessor utility that allows a single source file to be used to
750 generate multiple or parameterized source files, by means of macro
751 substitution.
753 @ifset vms
754 @item
755 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
756 a tool for rebuilding the GNAT run time with user-supplied
757 configuration pragmas.
758 @end ifset
760 @item
761 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
762 utility that displays information about compiled units, including dependences
763 on the corresponding sources files, and consistency of compilations.
765 @item
766 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
767 to delete files that are produced by the compiler, binder and linker.
769 @ifclear vms
770 @item
771 @ref{GNAT and Libraries}, describes the process of creating and using
772 Libraries with GNAT. It also describes how to recompile the GNAT run-time
773 library.
775 @item
776 @ref{Using the GNU make Utility}, describes some techniques for using
777 the GNAT toolset in Makefiles.
778 @end ifclear
780 @item
781 @ref{Memory Management Issues}, describes some useful predefined storage pools
782 and in particular the GNAT Debug Pool facility, which helps detect incorrect
783 memory references.
784 @ifclear vms
785 It also describes @command{gnatmem}, a utility that monitors dynamic
786 allocation and deallocation and helps detect ``memory leaks''.
787 @end ifclear
789 @item
790 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
791 a utility that generates empty but compilable bodies for library units.
793 @item
794 @ref{Other Utility Programs}, discusses several other GNAT utilities,
795 including @code{gnathtml}.
797 @item
798 @ref{Running and Debugging Ada Programs}, describes how to run and debug
799 Ada programs.
801 @ifset vms
802 @item
803 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
804 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
805 developed by Digital Equipment Corporation and currently supported by HP.}
806 for OpenVMS Alpha.
807 @end ifset
809 @item
810 @ref{Platform-Specific Information for the Run-Time Libraries},
811 describes the various run-time
812 libraries supported by GNAT on various platforms and explains how to
813 choose a particular library.
815 @item
816 @ref{Example of Binder Output File}, shows the source code for the binder
817 output file for a sample program.
819 @item
820 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
821 you deal with elaboration order issues.
823 @item
824 @ref{Inline Assembler}, shows how to use the inline assembly facility
825 in an Ada program.
827 @item
828 @ref{Compatibility and Porting Guide}, includes sections on compatibility
829 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
830 in porting code from other environments.
832 @ifset unw
833 @item
834 @ref{Microsoft Windows Topics}, presents information relevant to the
835 Microsoft Windows platform.
836 @end ifset
837 @end itemize
839 @c *************************************************
840 @node What You Should Know before Reading This Guide
841 @c *************************************************
842 @unnumberedsec What You Should Know before Reading This Guide
844 @cindex Ada 95 Language Reference Manual
845 @noindent
846 This user's guide assumes that you are familiar with Ada 95 language, as
847 described in the International Standard ANSI/ISO/IEC-8652:1995, January
848 1995.
850 @node Related Information
851 @unnumberedsec Related Information
853 @noindent
854 For further information about related tools, refer to the following
855 documents:
857 @itemize @bullet
858 @item
859 @cite{GNAT Reference Manual}, which contains all reference
860 material for the GNAT implementation of Ada 95.
862 @ifset unw
863 @item
864 @cite{Using the GNAT Programming System}, which describes the GPS
865 integrated development environment.
867 @item
868 @cite{GNAT Programming System Tutorial}, which introduces the
869 main GPS features through examples.
870 @end ifset
872 @item
873 @cite{Ada 95 Language Reference Manual}, which contains all reference
874 material for the Ada 95 programming language.
876 @item
877 @cite{Debugging with GDB}
878 @ifset vms
879 , located in the GNU:[DOCS] directory,
880 @end ifset
881 contains all details on the use of the GNU source-level debugger.
883 @item
884 @cite{GNU Emacs Manual}
885 @ifset vms
886 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
887 @end ifset
888 contains full information on the extensible editor and programming
889 environment Emacs.
891 @end itemize
893 @c **************
894 @node Conventions
895 @unnumberedsec Conventions
896 @cindex Conventions
897 @cindex Typographical conventions
899 @noindent
900 Following are examples of the typographical and graphic conventions used
901 in this guide:
903 @itemize @bullet
904 @item
905 @code{Functions}, @code{utility program names}, @code{standard names},
906 and @code{classes}.
908 @item
909 @samp{Option flags}
911 @item
912 @file{File Names}, @file{button names}, and @file{field names}.
914 @item
915 @var{Variables}.
917 @item
918 @emph{Emphasis}.
920 @item
921 [optional information or parameters]
923 @item
924 Examples are described by text
925 @smallexample
926 and then shown this way.
927 @end smallexample
928 @end itemize
930 @noindent
931 Commands that are entered by the user are preceded in this manual by the
932 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
933 uses this sequence as a prompt, then the commands will appear exactly as
934 you see them in the manual. If your system uses some other prompt, then
935 the command will appear with the @code{$} replaced by whatever prompt
936 character you are using.
938 @ifset unw
939 Full file names are shown with the ``@code{/}'' character
940 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
941 If you are using GNAT on a Windows platform, please note that
942 the ``@code{\}'' character should be used instead.
943 @end ifset
945 @c ****************************
946 @node Getting Started with GNAT
947 @chapter Getting Started with GNAT
949 @noindent
950 This chapter describes some simple ways of using GNAT to build
951 executable Ada programs.
952 @ifset unw
953 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
954 show how to use the command line environment.
955 @ref{Introduction to Glide and GVD}, provides a brief
956 introduction to the visually-oriented IDE for GNAT.
957 Supplementing Glide on some platforms is GPS, the
958 GNAT Programming System, which offers a richer graphical
959 ``look and feel'', enhanced configurability, support for
960 development in other programming language, comprehensive
961 browsing features, and many other capabilities.
962 For information on GPS please refer to
963 @cite{Using the GNAT Programming System}.
964 @end ifset
966 @menu
967 * Running GNAT::
968 * Running a Simple Ada Program::
969 * Running a Program with Multiple Units::
970 * Using the gnatmake Utility::
971 @ifset vms
972 * Editing with Emacs::
973 @end ifset
974 @ifclear vms
975 * Introduction to GPS::
976 * Introduction to Glide and GVD::
977 @end ifclear
978 @end menu
980 @node Running GNAT
981 @section Running GNAT
983 @noindent
984 Three steps are needed to create an executable file from an Ada source
985 file:
987 @enumerate
988 @item
989 The source file(s) must be compiled.
990 @item
991 The file(s) must be bound using the GNAT binder.
992 @item
993 All appropriate object files must be linked to produce an executable.
994 @end enumerate
996 @noindent
997 All three steps are most commonly handled by using the @code{gnatmake}
998 utility program that, given the name of the main program, automatically
999 performs the necessary compilation, binding and linking steps.
1001 @node Running a Simple Ada Program
1002 @section Running a Simple Ada Program
1004 @noindent
1005 Any text editor may be used to prepare an Ada program.
1006 @ifclear vms
1007 If @code{Glide} is
1008 used, the optional Ada mode may be helpful in laying out the program.
1009 @end ifclear
1011 program text is a normal text file. We will suppose in our initial
1012 example that you have used your editor to prepare the following
1013 standard format text file:
1015 @smallexample @c ada
1016 @cartouche
1017 with Ada.Text_IO; use Ada.Text_IO;
1018 procedure Hello is
1019 begin
1020    Put_Line ("Hello WORLD!");
1021 end Hello;
1022 @end cartouche
1023 @end smallexample
1025 @noindent
1026 This file should be named @file{hello.adb}.
1027 With the normal default file naming conventions, GNAT requires
1028 that each file
1029 contain a single compilation unit whose file name is the
1030 unit name,
1031 with periods replaced by hyphens; the
1032 extension is @file{ads} for a
1033 spec and @file{adb} for a body.
1034 You can override this default file naming convention by use of the
1035 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1036 Alternatively, if you want to rename your files according to this default
1037 convention, which is probably more convenient if you will be using GNAT
1038 for all your compilations, then the @code{gnatchop} utility
1039 can be used to generate correctly-named source files
1040 (@pxref{Renaming Files Using gnatchop}).
1042 You can compile the program using the following command (@code{$} is used
1043 as the command prompt in the examples in this document):
1045 @smallexample
1046 $ gcc -c hello.adb
1047 @end smallexample
1049 @noindent
1050 @code{gcc} is the command used to run the compiler. This compiler is
1051 capable of compiling programs in several languages, including Ada 95 and
1052 C. It assumes that you have given it an Ada program if the file extension is
1053 either @file{.ads} or @file{.adb}, and it will then call
1054 the GNAT compiler to compile the specified file.
1056 @ifclear vms
1057 The @option{-c} switch is required. It tells @command{gcc} to only do a
1058 compilation. (For C programs, @command{gcc} can also do linking, but this
1059 capability is not used directly for Ada programs, so the @option{-c}
1060 switch must always be present.)
1061 @end ifclear
1063 This compile command generates a file
1064 @file{hello.o}, which is the object
1065 file corresponding to your Ada program. It also generates
1066 an ``Ada Library Information'' file @file{hello.ali},
1067 which contains additional information used to check
1068 that an Ada program is consistent.
1069 To build an executable file,
1070 use @code{gnatbind} to bind the program
1071 and @code{gnatlink} to link it. The
1072 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1073 @file{ALI} file, but the default extension of @file{.ali} can
1074 be omitted. This means that in the most common case, the argument
1075 is simply the name of the main program:
1077 @smallexample
1078 $ gnatbind hello
1079 $ gnatlink hello
1080 @end smallexample
1082 @noindent
1083 A simpler method of carrying out these steps is to use
1084 @command{gnatmake},
1085 a master program that invokes all the required
1086 compilation, binding and linking tools in the correct order. In particular,
1087 @command{gnatmake} automatically recompiles any sources that have been
1088 modified since they were last compiled, or sources that depend
1089 on such modified sources, so that ``version skew'' is avoided.
1090 @cindex Version skew (avoided by @command{gnatmake})
1092 @smallexample
1093 $ gnatmake hello.adb
1094 @end smallexample
1096 @noindent
1097 The result is an executable program called @file{hello}, which can be
1098 run by entering:
1100 @c The following should be removed (BMB 2001-01-23)
1101 @c @smallexample
1102 @c $ ^./hello^$ RUN HELLO^
1103 @c @end smallexample
1105 @smallexample
1106 $ hello
1107 @end smallexample
1109 @noindent
1110 assuming that the current directory is on the search path
1111 for executable programs.
1113 @noindent
1114 and, if all has gone well, you will see
1116 @smallexample
1117 Hello WORLD!
1118 @end smallexample
1120 @noindent
1121 appear in response to this command.
1123 @c ****************************************
1124 @node Running a Program with Multiple Units
1125 @section Running a Program with Multiple Units
1127 @noindent
1128 Consider a slightly more complicated example that has three files: a
1129 main program, and the spec and body of a package:
1131 @smallexample @c ada
1132 @cartouche
1133 @group
1134 package Greetings is
1135    procedure Hello;
1136    procedure Goodbye;
1137 end Greetings;
1139 with Ada.Text_IO; use Ada.Text_IO;
1140 package body Greetings is
1141    procedure Hello is
1142    begin
1143       Put_Line ("Hello WORLD!");
1144    end Hello;
1146    procedure Goodbye is
1147    begin
1148       Put_Line ("Goodbye WORLD!");
1149    end Goodbye;
1150 end Greetings;
1151 @end group
1153 @group
1154 with Greetings;
1155 procedure Gmain is
1156 begin
1157    Greetings.Hello;
1158    Greetings.Goodbye;
1159 end Gmain;
1160 @end group
1161 @end cartouche
1162 @end smallexample
1164 @noindent
1165 Following the one-unit-per-file rule, place this program in the
1166 following three separate files:
1168 @table @file
1169 @item greetings.ads
1170 spec of package @code{Greetings}
1172 @item greetings.adb
1173 body of package @code{Greetings}
1175 @item gmain.adb
1176 body of main program
1177 @end table
1179 @noindent
1180 To build an executable version of
1181 this program, we could use four separate steps to compile, bind, and link
1182 the program, as follows:
1184 @smallexample
1185 $ gcc -c gmain.adb
1186 $ gcc -c greetings.adb
1187 $ gnatbind gmain
1188 $ gnatlink gmain
1189 @end smallexample
1191 @noindent
1192 Note that there is no required order of compilation when using GNAT.
1193 In particular it is perfectly fine to compile the main program first.
1194 Also, it is not necessary to compile package specs in the case where
1195 there is an accompanying body; you only need to compile the body. If you want
1196 to submit these files to the compiler for semantic checking and not code
1197 generation, then use the
1198 @option{-gnatc} switch:
1200 @smallexample
1201 $ gcc -c greetings.ads -gnatc
1202 @end smallexample
1204 @noindent
1205 Although the compilation can be done in separate steps as in the
1206 above example, in practice it is almost always more convenient
1207 to use the @code{gnatmake} tool. All you need to know in this case
1208 is the name of the main program's source file. The effect of the above four
1209 commands can be achieved with a single one:
1211 @smallexample
1212 $ gnatmake gmain.adb
1213 @end smallexample
1215 @noindent
1216 In the next section we discuss the advantages of using @code{gnatmake} in
1217 more detail.
1219 @c *****************************
1220 @node Using the gnatmake Utility
1221 @section Using the @command{gnatmake} Utility
1223 @noindent
1224 If you work on a program by compiling single components at a time using
1225 @code{gcc}, you typically keep track of the units you modify. In order to
1226 build a consistent system, you compile not only these units, but also any
1227 units that depend on the units you have modified.
1228 For example, in the preceding case,
1229 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1230 you edit @file{greetings.ads}, you must recompile both
1231 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1232 units that depend on @file{greetings.ads}.
1234 @code{gnatbind} will warn you if you forget one of these compilation
1235 steps, so that it is impossible to generate an inconsistent program as a
1236 result of forgetting to do a compilation. Nevertheless it is tedious and
1237 error-prone to keep track of dependencies among units.
1238 One approach to handle the dependency-bookkeeping is to use a
1239 makefile. However, makefiles present maintenance problems of their own:
1240 if the dependencies change as you change the program, you must make
1241 sure that the makefile is kept up-to-date manually, which is also an
1242 error-prone process.
1244 The @code{gnatmake} utility takes care of these details automatically.
1245 Invoke it using either one of the following forms:
1247 @smallexample
1248 $ gnatmake gmain.adb
1249 $ gnatmake ^gmain^GMAIN^
1250 @end smallexample
1252 @noindent
1253 The argument is the name of the file containing the main program;
1254 you may omit the extension. @code{gnatmake}
1255 examines the environment, automatically recompiles any files that need
1256 recompiling, and binds and links the resulting set of object files,
1257 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1258 In a large program, it
1259 can be extremely helpful to use @code{gnatmake}, because working out by hand
1260 what needs to be recompiled can be difficult.
1262 Note that @code{gnatmake}
1263 takes into account all the Ada 95 rules that
1264 establish dependencies among units. These include dependencies that result
1265 from inlining subprogram bodies, and from
1266 generic instantiation. Unlike some other
1267 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1268 found by the compiler on a previous compilation, which may possibly
1269 be wrong when sources change. @code{gnatmake} determines the exact set of
1270 dependencies from scratch each time it is run.
1272 @ifset vms
1273 @node Editing with Emacs
1274 @section Editing with Emacs
1275 @cindex Emacs
1277 @noindent
1278 Emacs is an extensible self-documenting text editor that is available in a
1279 separate VMSINSTAL kit.
1281 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1282 click on the Emacs Help menu and run the Emacs Tutorial.
1283 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1284 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1286 Documentation on Emacs and other tools is available in Emacs under the
1287 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1288 use the middle mouse button to select a topic (e.g. Emacs).
1290 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1291 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1292 get to the Emacs manual.
1293 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1294 prompt.
1296 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1297 which is sufficiently extensible to provide for a complete programming
1298 environment and shell for the sophisticated user.
1299 @end ifset
1301 @ifclear vms
1302 @node Introduction to GPS
1303 @section Introduction to GPS
1304 @cindex GPS (GNAT Programming System)
1305 @cindex GNAT Programming System (GPS)
1306 @noindent
1307 Although the command line interface (@command{gnatmake}, etc.) alone
1308 is sufficient, a graphical Interactive Development
1309 Environment can make it easier for you to compose, navigate, and debug
1310 programs.  This section describes the main features of GPS
1311 (``GNAT Programming System''), the GNAT graphical IDE.
1312 You will see how to use GPS to build and debug an executable, and
1313 you will also learn some of the basics of the GNAT ``project'' facility.
1315 GPS enables you to do much more than is presented here;
1316 e.g., you can produce a call graph, interface to a third-party
1317 Version Control System, and inspect the generated assembly language
1318 for a program.
1319 Indeed, GPS also supports languages other than Ada.
1320 Such additional information, and an explanation of all of the GPS menu
1321 items. may be found in the on-line help, which includes
1322 a user's guide and a tutorial (these are also accessible from the GNAT
1323 startup menu).
1325 @menu
1326 * Building a New Program with GPS::
1327 * Simple Debugging with GPS::
1328 @end menu
1330 @node Building a New Program with GPS
1331 @subsection Building a New Program with GPS
1332 @noindent
1333 GPS invokes the GNAT compilation tools using information
1334 contained in a @emph{project} (also known as a @emph{project file}):
1335 a collection of properties such
1336 as source directories, identities of main subprograms, tool switches, etc.,
1337 and their associated values.
1338 (See @ref{GNAT Project Manager}, for details.)
1339 In order to run GPS, you will need to either create a new project
1340 or else open an existing one.
1342 This section will explain how you can use GPS to create a project,
1343 to associate Ada source files with a project, and to build and run
1344 programs.
1346 @enumerate
1347 @item @emph{Creating a project}
1349 Invoke GPS, either from the command line or the platform's IDE.
1350 After it starts, GPS will display a ``Welcome'' screen with three
1351 radio buttons:
1353 @itemize @bullet
1354 @item
1355 @code{Start with default project in directory}
1357 @item
1358 @code{Create new project with wizard}
1360 @item
1361 @code{Open existing project}
1362 @end itemize
1364 @noindent
1365 Select @code{Create new project with wizard} and press @code{OK}.
1366 A new window will appear.  In the text box labeled with
1367 @code{Enter the name of the project to create}, type @file{sample}
1368 as the project name.
1369 In the next box, browse to choose the directory in which you
1370 would like to create the project file.
1371 After selecting an appropriate directory, press @code{Forward}.
1373 A window will appear with the title
1374 @code{Version Control System Configuration}.
1375 Simply press @code{Forward}.
1377 A window will appear with the title
1378 @code{Please select the source directories for this project}.
1379 The directory that you specified for the project file will be selected
1380 by default as the one to use for sources; simply press @code{Forward}.
1382 A window will appear with the title
1383 @code{Please select the build directory for this project}.
1384 The directory that you specified for the project file will be selected
1385 by default for object files and executables;
1386 simply press @code{Forward}.
1388 A window will appear with the title
1389 @code{Please select the main units for this project}.
1390 You will supply this information later, after creating the source file.
1391 Simply press @code{Forward} for now.
1393 A window will appear with the title
1394 @code{Please select the switches to build the project}.
1395 Press @code{Apply}.  This will create a project file named
1396 @file{sample.prj} in the directory that you had specified.
1398 @item @emph{Creating and saving the source file}
1400 After you create the new project, a GPS window will appear, which is
1401 partitioned into two main sections:
1403 @itemize @bullet
1404 @item
1405 A @emph{Workspace area}, initially greyed out, which you will use for
1406 creating and editing source files
1408 @item
1409 Directly below, a @emph{Messages area}, which initially displays a
1410 ``Welcome'' message.
1411 (If the Messages area is not visible, drag its border upward to expand it.)
1412 @end itemize
1414 @noindent
1415 Select @code{File} on the menu bar, and then the @code{New} command.
1416 The Workspace area will become white, and you can now
1417 enter the source program explicitly.
1418 Type the following text
1420 @smallexample @c ada
1421 @group
1422 with Ada.Text_IO; use Ada.Text_IO;
1423 procedure Hello is
1424 begin
1425   Put_Line("Hello from GPS!");
1426 end Hello;
1427 @end group
1428 @end smallexample
1430 @noindent
1431 Select @code{File}, then @code{Save As}, and enter the source file name
1432 @file{hello.adb}.
1433 The file will be saved in the same directory you specified as the
1434 location of the default project file.
1436 @item @emph{Updating the project file}
1438 You need to add the new source file to the project.
1439 To do this, select
1440 the @code{Project} menu and then @code{Edit project properties}.
1441 Click the @code{Main files} tab on the left, and then the
1442 @code{Add} button.
1443 Choose @file{hello.adb} from the list, and press @code{Open}.
1444 The project settings window will reflect this action.
1445 Click @code{OK}.
1447 @item @emph{Building and running the program}
1449 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1450 and select @file{hello.adb}.
1451 The Messages window will display the resulting invocations of @command{gcc},
1452 @command{gnatbind}, and @command{gnatlink}
1453 (reflecting the default switch settings from the
1454 project file that you created) and then a ``successful compilation/build''
1455 message.
1457 To run the program, choose the @code{Build} menu, then @code{Run}, and
1458 select @command{hello}.
1459 An @emph{Arguments Selection} window will appear.
1460 There are no command line arguments, so just click @code{OK}.
1462 The Messages window will now display the program's output (the string
1463 @code{Hello from GPS}), and at the bottom of the GPS window a status
1464 update is displayed (@code{Run: hello}).
1465 Close the GPS window (or select @code{File}, then @code{Exit}) to
1466 terminate this GPS session.
1467 @end enumerate
1469 @node Simple Debugging with GPS
1470 @subsection Simple Debugging with GPS
1471 @noindent
1472 This section illustrates basic debugging techniques (setting breakpoints,
1473 examining/modifying variables, single stepping).
1475 @enumerate
1476 @item @emph{Opening a project}
1478 Start GPS and select @code{Open existing project}; browse to
1479 specify the project file @file{sample.prj} that you had created in the
1480 earlier example.
1482 @item @emph{Creating a source file}
1484 Select @code{File}, then @code{New}, and type in the following program:
1486 @smallexample @c ada
1487 @group
1488 with Ada.Text_IO; use Ada.Text_IO;
1489 procedure Example is
1490    Line : String (1..80);
1491    N    : Natural;
1492 begin
1493    Put_Line("Type a line of text at each prompt; an empty line to exit");
1494    loop
1495       Put(": ");
1496       Get_Line (Line, N);
1497       Put_Line (Line (1..N) );
1498       exit when N=0;
1499    end loop;
1500 end Example;
1501 @end group
1502 @end smallexample
1504 @noindent
1505 Select @code{File}, then @code{Save as}, and enter the file name
1506 @file{example.adb}.
1508 @item @emph{Updating the project file}
1510 Add @code{Example} as a new main unit for the project:
1511 @enumerate a
1512 @item
1513 Select @code{Project}, then @code{Edit Project Properties}.
1515 @item
1516 Select the @code{Main files} tab, click @code{Add}, then
1517 select the file @file{example.adb} from the list, and
1518 click @code{Open}.
1519 You will see the file name appear in the list of main units
1521 @item
1522 Click @code{OK}
1523 @end enumerate
1525 @item @emph{Building/running the executable}
1527 To build the executable
1528 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1530 Run the program to see its effect (in the Messages area).
1531 Each line that you enter is displayed; an empty line will
1532 cause the loop to exit and the program to terminate.
1534 @item @emph{Debugging the program}
1536 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1537 which are required for debugging, are on by default when you create
1538 a new project.
1539 Thus unless you intentionally remove these settings, you will be able
1540 to debug any program that you develop using GPS.
1542 @enumerate a
1543 @item @emph{Initializing}
1545 Select @code{Debug}, then @code{Initialize}, then @file{example}
1547 @item @emph{Setting a breakpoint}
1549 After performing the initialization step, you will observe a small
1550 icon to the right of each line number.
1551 This serves as a toggle for breakpoints; clicking the icon will
1552 set a breakpoint at the corresponding line (the icon will change to
1553 a red circle with an ``x''), and clicking it again
1554 will remove the breakpoint / reset the icon.
1556 For purposes of this example, set a breakpoint at line 10 (the
1557 statement @code{Put_Line@ (Line@ (1..N));}
1559 @item @emph{Starting program execution}
1561 Select @code{Debug}, then @code{Run}.  When the
1562 @code{Program Arguments} window appears, click @code{OK}.
1563 A console window will appear; enter some line of text,
1564 e.g. @code{abcde}, at the prompt.
1565 The program will pause execution when it gets to the
1566 breakpoint, and the corresponding line is highlighted.
1568 @item @emph{Examining a variable}
1570 Move the mouse over one of the occurrences of the variable @code{N}.
1571 You will see the value (5) displayed, in ``tool tip'' fashion.
1572 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1573 You will see information about @code{N} appear in the @code{Debugger Data}
1574 pane, showing the value as 5.
1576 @item @emph{Assigning a new value to a variable}
1578 Right click on the @code{N} in the @code{Debugger Data} pane, and
1579 select @code{Set value of N}.
1580 When the input window appears, enter the value @code{4} and click
1581 @code{OK}.
1582 This value does not automatically appear in the @code{Debugger Data}
1583 pane; to see it, right click again on the @code{N} in the
1584 @code{Debugger Data} pane and select @code{Update value}.
1585 The new value, 4, will appear in red.
1587 @item @emph{Single stepping}
1589 Select @code{Debug}, then @code{Next}.
1590 This will cause the next statement to be executed, in this case the
1591 call of @code{Put_Line} with the string slice.
1592 Notice in the console window that the displayed string is simply
1593 @code{abcd} and not @code{abcde} which you had entered.
1594 This is because the upper bound of the slice is now 4 rather than 5.
1596 @item @emph{Removing a breakpoint}
1598 Toggle the breakpoint icon at line 10.
1600 @item @emph{Resuming execution from a breakpoint}
1602 Select @code{Debug}, then @code{Continue}.
1603 The program will reach the next iteration of the loop, and
1604 wait for input after displaying the prompt.
1605 This time, just hit the @kbd{Enter} key.
1606 The value of @code{N} will be 0, and the program will terminate.
1607 The console window will disappear.
1608 @end enumerate
1609 @end enumerate
1611 @node Introduction to Glide and GVD
1612 @section Introduction to Glide and GVD
1613 @cindex Glide
1614 @cindex GVD
1615 @noindent
1616 This section describes the main features of Glide,
1617 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1618 the GNU Visual Debugger.
1619 These tools may be present in addition to, or in place of, GPS on some
1620 platforms.
1621 Additional information on Glide and GVD may be found
1622 in the on-line help for these tools.
1624 @menu
1625 * Building a New Program with Glide::
1626 * Simple Debugging with GVD::
1627 * Other Glide Features::
1628 @end menu
1630 @node Building a New Program with Glide
1631 @subsection Building a New Program with Glide
1632 @noindent
1633 The simplest way to invoke Glide is to enter @command{glide}
1634 at the command prompt.  It will generally be useful to issue this
1635 as a background command, thus allowing you to continue using
1636 your command window for other purposes while Glide is running:
1638 @smallexample
1639 $ glide&
1640 @end smallexample
1642 @noindent
1643 Glide will start up with an initial screen displaying the top-level menu items
1644 as well as some other information.  The menu selections are as follows
1645 @itemize @bullet
1646 @item @code{Buffers}
1647 @item @code{Files}
1648 @item @code{Tools}
1649 @item @code{Edit}
1650 @item @code{Search}
1651 @item @code{Mule}
1652 @item @code{Glide}
1653 @item @code{Help}
1654 @end itemize
1656 @noindent
1657 For this introductory example, you will need to create a new Ada source file.
1658 First, select the @code{Files} menu.  This will pop open a menu with around
1659 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1660 Depending on the platform, you may see a pop-up window where you can browse
1661 to an appropriate directory and then enter the file name, or else simply
1662 see a line at the bottom of the Glide window where you can likewise enter
1663 the file name.  Note that in Glide, when you attempt to open a non-existent
1664 file, the effect is to create a file with that name.  For this example enter
1665 @file{hello.adb} as the name of the file.
1667 A new buffer will now appear, occupying the entire Glide window,
1668 with the file name at the top.  The menu selections are slightly different
1669 from the ones you saw on the opening screen; there is an @code{Entities} item,
1670 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1671 the file extension to identify the source language, so @file{adb} indicates
1672 an Ada source file.
1674 You will enter some of the source program lines explicitly,
1675 and use the syntax-oriented template mechanism to enter other lines.
1676 First, type the following text:
1677 @smallexample
1678 with Ada.Text_IO; use Ada.Text_IO;
1679 procedure Hello is
1680 begin
1681 @end smallexample
1683 @noindent
1684 Observe that Glide uses different colors to distinguish reserved words from
1685 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1686 automatically indented in anticipation of declarations.  When you enter
1687 @code{begin}, Glide recognizes that there are no declarations and thus places
1688 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1689 indented, where the statement(s) will be placed.
1691 The main part of the program will be a @code{for} loop.  Instead of entering
1692 the text explicitly, however, use a statement template.  Select the @code{Ada}
1693 item on the top menu bar, move the mouse to the @code{Statements} item,
1694 and you will see a large selection of alternatives.  Choose @code{for loop}.
1695 You will be prompted (at the bottom of the buffer) for a loop name;
1696 simply press the @key{Enter} key since a loop name is not needed.
1697 You should see the beginning of a @code{for} loop appear in the source
1698 program window.  You will now be prompted for the name of the loop variable;
1699 enter a line with the identifier @code{ind} (lower case).  Note that,
1700 by default, Glide capitalizes the name (you can override such behavior
1701 if you wish, although this is outside the scope of this introduction).
1702 Next, Glide prompts you for the loop range; enter a line containing
1703 @code{1..5} and you will see this also appear in the source program,
1704 together with the remaining elements of the @code{for} loop syntax.
1706 Next enter the statement (with an intentional error, a missing semicolon)
1707 that will form the body of the loop:
1708 @smallexample
1709 Put_Line("Hello, World" & Integer'Image(I))
1710 @end smallexample
1712 @noindent
1713 Finally, type @code{end Hello;} as the last line in the program.
1714 Now save the file: choose the @code{File} menu item, and then the
1715 @code{Save buffer} selection.  You will see a message at the bottom
1716 of the buffer confirming that the file has been saved.
1718 You are now ready to attempt to build the program.  Select the @code{Ada}
1719 item from the top menu bar.  Although we could choose simply to compile
1720 the file, we will instead attempt to do a build (which invokes
1721 @command{gnatmake}) since, if the compile is successful, we want to build
1722 an executable.  Thus select @code{Ada build}.  This will fail because of the
1723 compilation error, and you will notice that the Glide window has been split:
1724 the top window contains the source file, and the bottom window contains the
1725 output from the GNAT tools. Glide allows you to navigate from a compilation
1726 error to the source file position corresponding to the error: click the
1727 middle mouse button (or simultaneously press the left and right buttons,
1728 on a two-button mouse) on the diagnostic line in the tool window.  The
1729 focus will shift to the source window, and the cursor will be positioned
1730 on the character at which the error was detected.
1732 Correct the error: type in a semicolon to terminate the statement.
1733 Although you can again save the file explicitly, you can also simply invoke
1734 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1735 This time the build will succeed; the tool output window shows you the
1736 options that are supplied by default.  The GNAT tools' output (e.g.
1737 object and ALI files, executable) will go in the directory from which
1738 Glide was launched.
1740 To execute the program, choose @code{Ada} and then @code{Run}.
1741 You should see the program's output displayed in the bottom window:
1743 @smallexample
1744 Hello, world 1
1745 Hello, world 2
1746 Hello, world 3
1747 Hello, world 4
1748 Hello, world 5
1749 @end smallexample
1751 @node Simple Debugging with GVD
1752 @subsection Simple Debugging with GVD
1754 @noindent
1755 This section describes how to set breakpoints, examine/modify variables,
1756 and step through execution.
1758 In order to enable debugging, you need to pass the @option{-g} switch
1759 to both the compiler and to @command{gnatlink}.  If you are using
1760 the command line, passing @option{-g} to @command{gnatmake} will have
1761 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1762 by issuing the command:
1764 @smallexample
1765 $ gvd hello
1766 @end smallexample
1768 @noindent
1769 If you are using Glide, then @option{-g} is passed to the relevant tools
1770 by default when you do a build.  Start the debugger by selecting the
1771 @code{Ada} menu item, and then @code{Debug}.
1773 GVD comes up in a multi-part window.  One pane shows the names of files
1774 comprising your executable; another pane shows the source code of the current
1775 unit (initially your main subprogram), another pane shows the debugger output
1776 and user interactions, and the fourth pane (the data canvas at the top
1777 of the window) displays data objects that you have selected.
1779 To the left of the source file pane, you will notice green dots adjacent
1780 to some lines.  These are lines for which object code exists and where
1781 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1782 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1783 in a red circle.  Clicking the circle toggles the breakpoint off,
1784 and the red circle is replaced by the green dot.
1786 For this example, set a breakpoint at the statement where @code{Put_Line}
1787 is invoked.
1789 Start program execution by selecting the @code{Run} button on the top menu bar.
1790 (The @code{Start} button will also start your program, but it will
1791 cause program execution to break at the entry to your main subprogram.)
1792 Evidence of reaching the breakpoint will appear: the source file line will be
1793 highlighted, and the debugger interactions pane will display
1794 a relevant message.
1796 You can examine the values of variables in several ways.  Move the mouse
1797 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1798 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1799 and select @code{Display Ind}; a box showing the variable's name and value
1800 will appear in the data canvas.
1802 Although a loop index is a constant with respect to Ada semantics,
1803 you can change its value in the debugger.  Right-click in the box
1804 for @code{Ind}, and select the @code{Set Value of Ind} item.
1805 Enter @code{2} as the new value, and press @command{OK}.
1806 The box for @code{Ind} shows the update.
1808 Press the @code{Step} button on the top menu bar; this will step through
1809 one line of program text (the invocation of @code{Put_Line}), and you can
1810 observe the effect of having modified @code{Ind} since the value displayed
1811 is @code{2}.
1813 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1814 button.  You will see the remaining output lines displayed in the debugger
1815 interaction window, along with a message confirming normal program
1816 termination.
1818 @node Other Glide Features
1819 @subsection Other Glide Features
1821 @noindent
1822 You may have observed that some of the menu selections contain abbreviations;
1823 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1824 These are @emph{shortcut keys} that you can use instead of selecting
1825 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1826 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1827 of selecting @code{Files} and then @code{Open file...}.
1829 To abort a Glide command, type @key{Ctrl-g}.
1831 If you want Glide to start with an existing source file, you can either
1832 launch Glide as above and then open the file via @code{Files} @result{}
1833 @code{Open file...}, or else simply pass the name of the source file
1834 on the command line:
1836 @smallexample
1837 $ glide hello.adb&
1838 @end smallexample
1840 @noindent
1841 While you are using Glide, a number of @emph{buffers} exist.
1842 You create some explicitly; e.g., when you open/create a file.
1843 Others arise as an effect of the commands that you issue; e.g., the buffer
1844 containing the output of the tools invoked during a build.  If a buffer
1845 is hidden, you can bring it into a visible window by first opening
1846 the @code{Buffers} menu and then selecting the desired entry.
1848 If a buffer occupies only part of the Glide screen and you want to expand it
1849 to fill the entire screen, then click in the buffer and then select
1850 @code{Files} @result{} @code{One Window}.
1852 If a window is occupied by one buffer and you want to split the window
1853 to bring up a second buffer, perform the following steps:
1854 @itemize @bullet
1855 @item Select @code{Files} @result{} @code{Split Window};
1856 this will produce two windows each of which holds the original buffer
1857 (these are not copies, but rather different views of the same buffer contents)
1859 @item With the focus in one of the windows,
1860 select the desired buffer from the @code{Buffers} menu
1861 @end itemize
1863 @noindent
1864 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1865 @end ifclear
1867 @node The GNAT Compilation Model
1868 @chapter The GNAT Compilation Model
1869 @cindex GNAT compilation model
1870 @cindex Compilation model
1872 @menu
1873 * Source Representation::
1874 * Foreign Language Representation::
1875 * File Naming Rules::
1876 * Using Other File Names::
1877 * Alternative File Naming Schemes::
1878 * Generating Object Files::
1879 * Source Dependencies::
1880 * The Ada Library Information Files::
1881 * Binding an Ada Program::
1882 * Mixed Language Programming::
1883 * Building Mixed Ada & C++ Programs::
1884 * Comparison between GNAT and C/C++ Compilation Models::
1885 * Comparison between GNAT and Conventional Ada Library Models::
1886 @ifset vms
1887 * Placement of temporary files::
1888 @end ifset
1889 @end menu
1891 @noindent
1892 This chapter describes the compilation model used by GNAT. Although
1893 similar to that used by other languages, such as C and C++, this model
1894 is substantially different from the traditional Ada compilation models,
1895 which are based on a library. The model is initially described without
1896 reference to the library-based model. If you have not previously used an
1897 Ada compiler, you need only read the first part of this chapter. The
1898 last section describes and discusses the differences between the GNAT
1899 model and the traditional Ada compiler models. If you have used other
1900 Ada compilers, this section will help you to understand those
1901 differences, and the advantages of the GNAT model.
1903 @node Source Representation
1904 @section Source Representation
1905 @cindex Latin-1
1907 @noindent
1908 Ada source programs are represented in standard text files, using
1909 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1910 7-bit ASCII set, plus additional characters used for
1911 representing foreign languages (@pxref{Foreign Language Representation}
1912 for support of non-USA character sets). The format effector characters
1913 are represented using their standard ASCII encodings, as follows:
1915 @table @code
1916 @item VT
1917 @findex VT
1918 Vertical tab, @code{16#0B#}
1920 @item HT
1921 @findex HT
1922 Horizontal tab, @code{16#09#}
1924 @item CR
1925 @findex CR
1926 Carriage return, @code{16#0D#}
1928 @item LF
1929 @findex LF
1930 Line feed, @code{16#0A#}
1932 @item FF
1933 @findex FF
1934 Form feed, @code{16#0C#}
1935 @end table
1937 @noindent
1938 Source files are in standard text file format. In addition, GNAT will
1939 recognize a wide variety of stream formats, in which the end of physical
1940 physical lines is marked by any of the following sequences:
1941 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1942 in accommodating files that are imported from other operating systems.
1944 @cindex End of source file
1945 @cindex Source file, end
1946 @findex SUB
1947 The end of a source file is normally represented by the physical end of
1948 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1949 recognized as signalling the end of the source file. Again, this is
1950 provided for compatibility with other operating systems where this
1951 code is used to represent the end of file.
1953 Each file contains a single Ada compilation unit, including any pragmas
1954 associated with the unit. For example, this means you must place a
1955 package declaration (a package @dfn{spec}) and the corresponding body in
1956 separate files. An Ada @dfn{compilation} (which is a sequence of
1957 compilation units) is represented using a sequence of files. Similarly,
1958 you will place each subunit or child unit in a separate file.
1960 @node Foreign Language Representation
1961 @section Foreign Language Representation
1963 @noindent
1964 GNAT supports the standard character sets defined in Ada 95 as well as
1965 several other non-standard character sets for use in localized versions
1966 of the compiler (@pxref{Character Set Control}).
1967 @menu
1968 * Latin-1::
1969 * Other 8-Bit Codes::
1970 * Wide Character Encodings::
1971 @end menu
1973 @node Latin-1
1974 @subsection Latin-1
1975 @cindex Latin-1
1977 @noindent
1978 The basic character set is Latin-1. This character set is defined by ISO
1979 standard 8859, part 1. The lower half (character codes @code{16#00#}
1980 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1981 is used to represent additional characters. These include extended letters
1982 used by European languages, such as French accents, the vowels with umlauts
1983 used in German, and the extra letter A-ring used in Swedish.
1985 @findex Ada.Characters.Latin_1
1986 For a complete list of Latin-1 codes and their encodings, see the source
1987 file of library unit @code{Ada.Characters.Latin_1} in file
1988 @file{a-chlat1.ads}.
1989 You may use any of these extended characters freely in character or
1990 string literals. In addition, the extended characters that represent
1991 letters can be used in identifiers.
1993 @node Other 8-Bit Codes
1994 @subsection Other 8-Bit Codes
1996 @noindent
1997 GNAT also supports several other 8-bit coding schemes:
1999 @table @asis
2000 @item ISO 8859-2 (Latin-2)
2001 @cindex Latin-2
2002 @cindex ISO 8859-2
2003 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2004 equivalence.
2006 @item ISO 8859-3 (Latin-3)
2007 @cindex Latin-3
2008 @cindex ISO 8859-3
2009 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2010 equivalence.
2012 @item ISO 8859-4 (Latin-4)
2013 @cindex Latin-4
2014 @cindex ISO 8859-4
2015 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2016 equivalence.
2018 @item ISO 8859-5 (Cyrillic)
2019 @cindex ISO 8859-5
2020 @cindex Cyrillic
2021 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2022 lowercase equivalence.
2024 @item ISO 8859-15 (Latin-9)
2025 @cindex ISO 8859-15
2026 @cindex Latin-9
2027 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2028 lowercase equivalence
2030 @item IBM PC (code page 437)
2031 @cindex code page 437
2032 This code page is the normal default for PCs in the U.S. It corresponds
2033 to the original IBM PC character set. This set has some, but not all, of
2034 the extended Latin-1 letters, but these letters do not have the same
2035 encoding as Latin-1. In this mode, these letters are allowed in
2036 identifiers with uppercase and lowercase equivalence.
2038 @item IBM PC (code page 850)
2039 @cindex code page 850
2040 This code page is a modification of 437 extended to include all the
2041 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2042 mode, all these letters are allowed in identifiers with uppercase and
2043 lowercase equivalence.
2045 @item Full Upper 8-bit
2046 Any character in the range 80-FF allowed in identifiers, and all are
2047 considered distinct. In other words, there are no uppercase and lowercase
2048 equivalences in this range. This is useful in conjunction with
2049 certain encoding schemes used for some foreign character sets (e.g.
2050 the typical method of representing Chinese characters on the PC).
2052 @item No Upper-Half
2053 No upper-half characters in the range 80-FF are allowed in identifiers.
2054 This gives Ada 83 compatibility for identifier names.
2055 @end table
2057 @noindent
2058 For precise data on the encodings permitted, and the uppercase and lowercase
2059 equivalences that are recognized, see the file @file{csets.adb} in
2060 the GNAT compiler sources. You will need to obtain a full source release
2061 of GNAT to obtain this file.
2063 @node Wide Character Encodings
2064 @subsection Wide Character Encodings
2066 @noindent
2067 GNAT allows wide character codes to appear in character and string
2068 literals, and also optionally in identifiers, by means of the following
2069 possible encoding schemes:
2071 @table @asis
2073 @item Hex Coding
2074 In this encoding, a wide character is represented by the following five
2075 character sequence:
2077 @smallexample
2078 ESC a b c d
2079 @end smallexample
2081 @noindent
2082 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2083 characters (using uppercase letters) of the wide character code. For
2084 example, ESC A345 is used to represent the wide character with code
2085 @code{16#A345#}.
2086 This scheme is compatible with use of the full Wide_Character set.
2088 @item Upper-Half Coding
2089 @cindex Upper-Half Coding
2090 The wide character with encoding @code{16#abcd#} where the upper bit is on
2091 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2092 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2093 character, but is not required to be in the upper half. This method can
2094 be also used for shift-JIS or EUC, where the internal coding matches the
2095 external coding.
2097 @item Shift JIS Coding
2098 @cindex Shift JIS Coding
2099 A wide character is represented by a two-character sequence,
2100 @code{16#ab#} and
2101 @code{16#cd#}, with the restrictions described for upper-half encoding as
2102 described above. The internal character code is the corresponding JIS
2103 character according to the standard algorithm for Shift-JIS
2104 conversion. Only characters defined in the JIS code set table can be
2105 used with this encoding method.
2107 @item EUC Coding
2108 @cindex EUC Coding
2109 A wide character is represented by a two-character sequence
2110 @code{16#ab#} and
2111 @code{16#cd#}, with both characters being in the upper half. The internal
2112 character code is the corresponding JIS character according to the EUC
2113 encoding algorithm. Only characters defined in the JIS code set table
2114 can be used with this encoding method.
2116 @item UTF-8 Coding
2117 A wide character is represented using
2118 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2119 10646-1/Am.2. Depending on the character value, the representation
2120 is a one, two, or three byte sequence:
2121 @smallexample
2122 @iftex
2123 @leftskip=.7cm
2124 @end iftex
2125 16#0000#-16#007f#: 2#0xxxxxxx#
2126 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2127 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2129 @end smallexample
2131 @noindent
2132 where the xxx bits correspond to the left-padded bits of the
2133 16-bit character value. Note that all lower half ASCII characters
2134 are represented as ASCII bytes and all upper half characters and
2135 other wide characters are represented as sequences of upper-half
2136 (The full UTF-8 scheme allows for encoding 31-bit characters as
2137 6-byte sequences, but in this implementation, all UTF-8 sequences
2138 of four or more bytes length will be treated as illegal).
2139 @item Brackets Coding
2140 In this encoding, a wide character is represented by the following eight
2141 character sequence:
2143 @smallexample
2144 [ " a b c d " ]
2145 @end smallexample
2147 @noindent
2148 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2149 characters (using uppercase letters) of the wide character code. For
2150 example, [``A345''] is used to represent the wide character with code
2151 @code{16#A345#}. It is also possible (though not required) to use the
2152 Brackets coding for upper half characters. For example, the code
2153 @code{16#A3#} can be represented as @code{[``A3'']}.
2155 This scheme is compatible with use of the full Wide_Character set,
2156 and is also the method used for wide character encoding in the standard
2157 ACVC (Ada Compiler Validation Capability) test suite distributions.
2159 @end table
2161 @noindent
2162 Note: Some of these coding schemes do not permit the full use of the
2163 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2164 use of the upper half of the Latin-1 set.
2166 @node File Naming Rules
2167 @section File Naming Rules
2169 @noindent
2170 The default file name is determined by the name of the unit that the
2171 file contains. The name is formed by taking the full expanded name of
2172 the unit and replacing the separating dots with hyphens and using
2173 ^lowercase^uppercase^ for all letters.
2175 An exception arises if the file name generated by the above rules starts
2176 with one of the characters
2177 @ifset vms
2178 A,G,I, or S,
2179 @end ifset
2180 @ifclear vms
2181 a,g,i, or s,
2182 @end ifclear
2183 and the second character is a
2184 minus. In this case, the character ^tilde^dollar sign^ is used in place
2185 of the minus. The reason for this special rule is to avoid clashes with
2186 the standard names for child units of the packages System, Ada,
2187 Interfaces, and GNAT, which use the prefixes
2188 @ifset vms
2189 S- A- I- and G-
2190 @end ifset
2191 @ifclear vms
2192 s- a- i- and g-
2193 @end ifclear
2194 respectively.
2196 The file extension is @file{.ads} for a spec and
2197 @file{.adb} for a body. The following list shows some
2198 examples of these rules.
2200 @table @file
2201 @item main.ads
2202 Main (spec)
2203 @item main.adb
2204 Main (body)
2205 @item arith_functions.ads
2206 Arith_Functions (package spec)
2207 @item arith_functions.adb
2208 Arith_Functions (package body)
2209 @item func-spec.ads
2210 Func.Spec (child package spec)
2211 @item func-spec.adb
2212 Func.Spec (child package body)
2213 @item main-sub.adb
2214 Sub (subunit of Main)
2215 @item ^a~bad.adb^A$BAD.ADB^
2216 A.Bad (child package body)
2217 @end table
2219 @noindent
2220 Following these rules can result in excessively long
2221 file names if corresponding
2222 unit names are long (for example, if child units or subunits are
2223 heavily nested). An option is available to shorten such long file names
2224 (called file name ``krunching''). This may be particularly useful when
2225 programs being developed with GNAT are to be used on operating systems
2226 with limited file name lengths. @xref{Using gnatkr}.
2228 Of course, no file shortening algorithm can guarantee uniqueness over
2229 all possible unit names; if file name krunching is used, it is your
2230 responsibility to ensure no name clashes occur. Alternatively you
2231 can specify the exact file names that you want used, as described
2232 in the next section. Finally, if your Ada programs are migrating from a
2233 compiler with a different naming convention, you can use the gnatchop
2234 utility to produce source files that follow the GNAT naming conventions.
2235 (For details @pxref{Renaming Files Using gnatchop}.)
2237 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2238 systems, case is not significant. So for example on @code{Windows XP}
2239 if the canonical name is @code{main-sub.adb}, you can use the file name
2240 @code{Main-Sub.adb} instead. However, case is significant for other
2241 operating systems, so for example, if you want to use other than
2242 canonically cased file names on a Unix system, you need to follow
2243 the procedures described in the next section.
2245 @node Using Other File Names
2246 @section Using Other File Names
2247 @cindex File names
2249 @noindent
2250 In the previous section, we have described the default rules used by
2251 GNAT to determine the file name in which a given unit resides. It is
2252 often convenient to follow these default rules, and if you follow them,
2253 the compiler knows without being explicitly told where to find all
2254 the files it needs.
2256 However, in some cases, particularly when a program is imported from
2257 another Ada compiler environment, it may be more convenient for the
2258 programmer to specify which file names contain which units. GNAT allows
2259 arbitrary file names to be used by means of the Source_File_Name pragma.
2260 The form of this pragma is as shown in the following examples:
2261 @cindex Source_File_Name pragma
2263 @smallexample @c ada
2264 @cartouche
2265 pragma Source_File_Name (My_Utilities.Stacks,
2266   Spec_File_Name => "myutilst_a.ada");
2267 pragma Source_File_name (My_Utilities.Stacks,
2268   Body_File_Name => "myutilst.ada");
2269 @end cartouche
2270 @end smallexample
2272 @noindent
2273 As shown in this example, the first argument for the pragma is the unit
2274 name (in this example a child unit). The second argument has the form
2275 of a named association. The identifier
2276 indicates whether the file name is for a spec or a body;
2277 the file name itself is given by a string literal.
2279 The source file name pragma is a configuration pragma, which means that
2280 normally it will be placed in the @file{gnat.adc}
2281 file used to hold configuration
2282 pragmas that apply to a complete compilation environment.
2283 For more details on how the @file{gnat.adc} file is created and used
2284 @pxref{Handling of Configuration Pragmas}
2285 @cindex @file{gnat.adc}
2287 @ifclear vms
2288 GNAT allows completely arbitrary file names to be specified using the
2289 source file name pragma. However, if the file name specified has an
2290 extension other than @file{.ads} or @file{.adb} it is necessary to use
2291 a special syntax when compiling the file. The name in this case must be
2292 preceded by the special sequence @code{-x} followed by a space and the name
2293 of the language, here @code{ada}, as in:
2295 @smallexample
2296 $ gcc -c -x ada peculiar_file_name.sim
2297 @end smallexample
2298 @end ifclear
2300 @noindent
2301 @code{gnatmake} handles non-standard file names in the usual manner (the
2302 non-standard file name for the main program is simply used as the
2303 argument to gnatmake). Note that if the extension is also non-standard,
2304 then it must be included in the gnatmake command, it may not be omitted.
2306 @node Alternative File Naming Schemes
2307 @section Alternative File Naming Schemes
2308 @cindex File naming schemes, alternative
2309 @cindex File names
2311 In the previous section, we described the use of the @code{Source_File_Name}
2312 pragma to allow arbitrary names to be assigned to individual source files.
2313 However, this approach requires one pragma for each file, and especially in
2314 large systems can result in very long @file{gnat.adc} files, and also create
2315 a maintenance problem.
2317 GNAT also provides a facility for specifying systematic file naming schemes
2318 other than the standard default naming scheme previously described. An
2319 alternative scheme for naming is specified by the use of
2320 @code{Source_File_Name} pragmas having the following format:
2321 @cindex Source_File_Name pragma
2323 @smallexample @c ada
2324 pragma Source_File_Name (
2325    Spec_File_Name  => FILE_NAME_PATTERN
2326  [,Casing          => CASING_SPEC]
2327  [,Dot_Replacement => STRING_LITERAL]);
2329 pragma Source_File_Name (
2330    Body_File_Name  => FILE_NAME_PATTERN
2331  [,Casing          => CASING_SPEC]
2332  [,Dot_Replacement => STRING_LITERAL]);
2334 pragma Source_File_Name (
2335    Subunit_File_Name  => FILE_NAME_PATTERN
2336  [,Casing             => CASING_SPEC]
2337  [,Dot_Replacement    => STRING_LITERAL]);
2339 FILE_NAME_PATTERN ::= STRING_LITERAL
2340 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2341 @end smallexample
2343 @noindent
2344 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2345 It contains a single asterisk character, and the unit name is substituted
2346 systematically for this asterisk. The optional parameter
2347 @code{Casing} indicates
2348 whether the unit name is to be all upper-case letters, all lower-case letters,
2349 or mixed-case. If no
2350 @code{Casing} parameter is used, then the default is all
2351 ^lower-case^upper-case^.
2353 The optional @code{Dot_Replacement} string is used to replace any periods
2354 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2355 argument is used then separating dots appear unchanged in the resulting
2356 file name.
2357 Although the above syntax indicates that the
2358 @code{Casing} argument must appear
2359 before the @code{Dot_Replacement} argument, but it
2360 is also permissible to write these arguments in the opposite order.
2362 As indicated, it is possible to specify different naming schemes for
2363 bodies, specs, and subunits. Quite often the rule for subunits is the
2364 same as the rule for bodies, in which case, there is no need to give
2365 a separate @code{Subunit_File_Name} rule, and in this case the
2366 @code{Body_File_name} rule is used for subunits as well.
2368 The separate rule for subunits can also be used to implement the rather
2369 unusual case of a compilation environment (e.g. a single directory) which
2370 contains a subunit and a child unit with the same unit name. Although
2371 both units cannot appear in the same partition, the Ada Reference Manual
2372 allows (but does not require) the possibility of the two units coexisting
2373 in the same environment.
2375 The file name translation works in the following steps:
2377 @itemize @bullet
2379 @item
2380 If there is a specific @code{Source_File_Name} pragma for the given unit,
2381 then this is always used, and any general pattern rules are ignored.
2383 @item
2384 If there is a pattern type @code{Source_File_Name} pragma that applies to
2385 the unit, then the resulting file name will be used if the file exists. If
2386 more than one pattern matches, the latest one will be tried first, and the
2387 first attempt resulting in a reference to a file that exists will be used.
2389 @item
2390 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2391 for which the corresponding file exists, then the standard GNAT default
2392 naming rules are used.
2394 @end itemize
2396 @noindent
2397 As an example of the use of this mechanism, consider a commonly used scheme
2398 in which file names are all lower case, with separating periods copied
2399 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2400 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2401 two pragmas appear:
2403 @smallexample @c ada
2404 pragma Source_File_Name
2405   (Spec_File_Name => "*.1.ada");
2406 pragma Source_File_Name
2407   (Body_File_Name => "*.2.ada");
2408 @end smallexample
2410 @noindent
2411 The default GNAT scheme is actually implemented by providing the following
2412 default pragmas internally:
2414 @smallexample @c ada
2415 pragma Source_File_Name
2416   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2417 pragma Source_File_Name
2418   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2419 @end smallexample
2421 @noindent
2422 Our final example implements a scheme typically used with one of the
2423 Ada 83 compilers, where the separator character for subunits was ``__''
2424 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2425 by adding @file{.ADA}, and subunits by
2426 adding @file{.SEP}. All file names were
2427 upper case. Child units were not present of course since this was an
2428 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2429 the same double underscore separator for child units.
2431 @smallexample @c ada
2432 pragma Source_File_Name
2433   (Spec_File_Name => "*_.ADA",
2434    Dot_Replacement => "__",
2435    Casing = Uppercase);
2436 pragma Source_File_Name
2437   (Body_File_Name => "*.ADA",
2438    Dot_Replacement => "__",
2439    Casing = Uppercase);
2440 pragma Source_File_Name
2441   (Subunit_File_Name => "*.SEP",
2442    Dot_Replacement => "__",
2443    Casing = Uppercase);
2444 @end smallexample
2446 @node Generating Object Files
2447 @section Generating Object Files
2449 @noindent
2450 An Ada program consists of a set of source files, and the first step in
2451 compiling the program is to generate the corresponding object files.
2452 These are generated by compiling a subset of these source files.
2453 The files you need to compile are the following:
2455 @itemize @bullet
2456 @item
2457 If a package spec has no body, compile the package spec to produce the
2458 object file for the package.
2460 @item
2461 If a package has both a spec and a body, compile the body to produce the
2462 object file for the package. The source file for the package spec need
2463 not be compiled in this case because there is only one object file, which
2464 contains the code for both the spec and body of the package.
2466 @item
2467 For a subprogram, compile the subprogram body to produce the object file
2468 for the subprogram. The spec, if one is present, is as usual in a
2469 separate file, and need not be compiled.
2471 @item
2472 @cindex Subunits
2473 In the case of subunits, only compile the parent unit. A single object
2474 file is generated for the entire subunit tree, which includes all the
2475 subunits.
2477 @item
2478 Compile child units independently of their parent units
2479 (though, of course, the spec of all the ancestor unit must be present in order
2480 to compile a child unit).
2482 @item
2483 @cindex Generics
2484 Compile generic units in the same manner as any other units. The object
2485 files in this case are small dummy files that contain at most the
2486 flag used for elaboration checking. This is because GNAT always handles generic
2487 instantiation by means of macro expansion. However, it is still necessary to
2488 compile generic units, for dependency checking and elaboration purposes.
2489 @end itemize
2491 @noindent
2492 The preceding rules describe the set of files that must be compiled to
2493 generate the object files for a program. Each object file has the same
2494 name as the corresponding source file, except that the extension is
2495 @file{.o} as usual.
2497 You may wish to compile other files for the purpose of checking their
2498 syntactic and semantic correctness. For example, in the case where a
2499 package has a separate spec and body, you would not normally compile the
2500 spec. However, it is convenient in practice to compile the spec to make
2501 sure it is error-free before compiling clients of this spec, because such
2502 compilations will fail if there is an error in the spec.
2504 GNAT provides an option for compiling such files purely for the
2505 purposes of checking correctness; such compilations are not required as
2506 part of the process of building a program. To compile a file in this
2507 checking mode, use the @option{-gnatc} switch.
2509 @node Source Dependencies
2510 @section Source Dependencies
2512 @noindent
2513 A given object file clearly depends on the source file which is compiled
2514 to produce it. Here we are using @dfn{depends} in the sense of a typical
2515 @code{make} utility; in other words, an object file depends on a source
2516 file if changes to the source file require the object file to be
2517 recompiled.
2518 In addition to this basic dependency, a given object may depend on
2519 additional source files as follows:
2521 @itemize @bullet
2522 @item
2523 If a file being compiled @code{with}'s a unit @var{X}, the object file
2524 depends on the file containing the spec of unit @var{X}. This includes
2525 files that are @code{with}'ed implicitly either because they are parents
2526 of @code{with}'ed child units or they are run-time units required by the
2527 language constructs used in a particular unit.
2529 @item
2530 If a file being compiled instantiates a library level generic unit, the
2531 object file depends on both the spec and body files for this generic
2532 unit.
2534 @item
2535 If a file being compiled instantiates a generic unit defined within a
2536 package, the object file depends on the body file for the package as
2537 well as the spec file.
2539 @item
2540 @findex Inline
2541 @cindex @option{-gnatn} switch
2542 If a file being compiled contains a call to a subprogram for which
2543 pragma @code{Inline} applies and inlining is activated with the
2544 @option{-gnatn} switch, the object file depends on the file containing the
2545 body of this subprogram as well as on the file containing the spec. Note
2546 that for inlining to actually occur as a result of the use of this switch,
2547 it is necessary to compile in optimizing mode.
2549 @cindex @option{-gnatN} switch
2550 The use of @option{-gnatN} activates a more extensive inlining optimization
2551 that is performed by the front end of the compiler. This inlining does
2552 not require that the code generation be optimized. Like @option{-gnatn},
2553 the use of this switch generates additional dependencies.
2554 Note that
2555 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2556 to specify both options.
2558 @item
2559 If an object file O  depends on the proper body of a subunit through inlining
2560 or instantiation, it depends on the parent unit of the subunit. This means that
2561 any modification of the parent unit or one of its subunits affects the
2562 compilation of O.
2564 @item
2565 The object file for a parent unit depends on all its subunit body files.
2567 @item
2568 The previous two rules meant that for purposes of computing dependencies and
2569 recompilation, a body and all its subunits are treated as an indivisible whole.
2571 @noindent
2572 These rules are applied transitively: if unit @code{A} @code{with}'s
2573 unit @code{B}, whose elaboration calls an inlined procedure in package
2574 @code{C}, the object file for unit @code{A} will depend on the body of
2575 @code{C}, in file @file{c.adb}.
2577 The set of dependent files described by these rules includes all the
2578 files on which the unit is semantically dependent, as described in the
2579 Ada 95 Language Reference Manual. However, it is a superset of what the
2580 ARM describes, because it includes generic, inline, and subunit dependencies.
2582 An object file must be recreated by recompiling the corresponding source
2583 file if any of the source files on which it depends are modified. For
2584 example, if the @code{make} utility is used to control compilation,
2585 the rule for an Ada object file must mention all the source files on
2586 which the object file depends, according to the above definition.
2587 The determination of the necessary
2588 recompilations is done automatically when one uses @code{gnatmake}.
2589 @end itemize
2591 @node The Ada Library Information Files
2592 @section The Ada Library Information Files
2593 @cindex Ada Library Information files
2594 @cindex @file{ALI} files
2596 @noindent
2597 Each compilation actually generates two output files. The first of these
2598 is the normal object file that has a @file{.o} extension. The second is a
2599 text file containing full dependency information. It has the same
2600 name as the source file, but an @file{.ali} extension.
2601 This file is known as the Ada Library Information (@file{ALI}) file.
2602 The following information is contained in the @file{ALI} file.
2604 @itemize @bullet
2605 @item
2606 Version information (indicates which version of GNAT was used to compile
2607 the unit(s) in question)
2609 @item
2610 Main program information (including priority and time slice settings,
2611 as well as the wide character encoding used during compilation).
2613 @item
2614 List of arguments used in the @code{gcc} command for the compilation
2616 @item
2617 Attributes of the unit, including configuration pragmas used, an indication
2618 of whether the compilation was successful, exception model used etc.
2620 @item
2621 A list of relevant restrictions applying to the unit (used for consistency)
2622 checking.
2624 @item
2625 Categorization information (e.g. use of pragma @code{Pure}).
2627 @item
2628 Information on all @code{with}'ed units, including presence of
2629 @code{Elaborate} or @code{Elaborate_All} pragmas.
2631 @item
2632 Information from any @code{Linker_Options} pragmas used in the unit
2634 @item
2635 Information on the use of @code{Body_Version} or @code{Version}
2636 attributes in the unit.
2638 @item
2639 Dependency information. This is a list of files, together with
2640 time stamp and checksum information. These are files on which
2641 the unit depends in the sense that recompilation is required
2642 if any of these units are modified.
2644 @item
2645 Cross-reference data. Contains information on all entities referenced
2646 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2647 provide cross-reference information.
2649 @end itemize
2651 @noindent
2652 For a full detailed description of the format of the @file{ALI} file,
2653 see the source of the body of unit @code{Lib.Writ}, contained in file
2654 @file{lib-writ.adb} in the GNAT compiler sources.
2656 @node Binding an Ada Program
2657 @section Binding an Ada Program
2659 @noindent
2660 When using languages such as C and C++, once the source files have been
2661 compiled the only remaining step in building an executable program
2662 is linking the object modules together. This means that it is possible to
2663 link an inconsistent version of a program, in which two units have
2664 included different versions of the same header.
2666 The rules of Ada do not permit such an inconsistent program to be built.
2667 For example, if two clients have different versions of the same package,
2668 it is illegal to build a program containing these two clients.
2669 These rules are enforced by the GNAT binder, which also determines an
2670 elaboration order consistent with the Ada rules.
2672 The GNAT binder is run after all the object files for a program have
2673 been created. It is given the name of the main program unit, and from
2674 this it determines the set of units required by the program, by reading the
2675 corresponding ALI files. It generates error messages if the program is
2676 inconsistent or if no valid order of elaboration exists.
2678 If no errors are detected, the binder produces a main program, in Ada by
2679 default, that contains calls to the elaboration procedures of those
2680 compilation unit that require them, followed by
2681 a call to the main program. This Ada program is compiled to generate the
2682 object file for the main program. The name of
2683 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2684 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2685 main program unit.
2687 Finally, the linker is used to build the resulting executable program,
2688 using the object from the main program from the bind step as well as the
2689 object files for the Ada units of the program.
2691 @node Mixed Language Programming
2692 @section Mixed Language Programming
2693 @cindex Mixed Language Programming
2695 @noindent
2696 This section describes how to develop a mixed-language program,
2697 specifically one that comprises units in both Ada and C.
2699 @menu
2700 * Interfacing to C::
2701 * Calling Conventions::
2702 @end menu
2704 @node Interfacing to C
2705 @subsection Interfacing to C
2706 @noindent
2707 Interfacing Ada with a foreign language such as C involves using
2708 compiler directives to import and/or export entity definitions in each
2709 language---using @code{extern} statements in C, for instance, and the
2710 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2711 a full treatment of these topics, read Appendix B, section 1 of the Ada
2712 95 Language Reference Manual.
2714 There are two ways to build a program using GNAT that contains some Ada
2715 sources and some foreign language sources, depending on whether or not
2716 the main subprogram is written in Ada.  Here is a source example with
2717 the main subprogram in Ada:
2719 @smallexample
2720 /* file1.c */
2721 #include <stdio.h>
2723 void print_num (int num)
2725   printf ("num is %d.\n", num);
2726   return;
2729 /* file2.c */
2731 /* num_from_Ada is declared in my_main.adb */
2732 extern int num_from_Ada;
2734 int get_num (void)
2736   return num_from_Ada;
2738 @end smallexample
2740 @smallexample @c ada
2741 --  my_main.adb
2742 procedure My_Main is
2744    --  Declare then export an Integer entity called num_from_Ada
2745    My_Num : Integer := 10;
2746    pragma Export (C, My_Num, "num_from_Ada");
2748    --  Declare an Ada function spec for Get_Num, then use
2749    --  C function get_num for the implementation.
2750    function Get_Num return Integer;
2751    pragma Import (C, Get_Num, "get_num");
2753    --  Declare an Ada procedure spec for Print_Num, then use
2754    --  C function print_num for the implementation.
2755    procedure Print_Num (Num : Integer);
2756    pragma Import (C, Print_Num, "print_num");
2758 begin
2759    Print_Num (Get_Num);
2760 end My_Main;
2761 @end smallexample
2763 @enumerate
2764 @item
2765 To build this example, first compile the foreign language files to
2766 generate object files:
2767 @smallexample
2768 gcc -c file1.c
2769 gcc -c file2.c
2770 @end smallexample
2772 @item
2773 Then, compile the Ada units to produce a set of object files and ALI
2774 files:
2775 @smallexample
2776 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2777 @end smallexample
2779 @item
2780 Run the Ada binder on the Ada main program:
2781 @smallexample
2782 gnatbind my_main.ali
2783 @end smallexample
2785 @item
2786 Link the Ada main program, the Ada objects and the other language
2787 objects:
2788 @smallexample
2789 gnatlink my_main.ali file1.o file2.o
2790 @end smallexample
2791 @end enumerate
2793 The last three steps can be grouped in a single command:
2794 @smallexample
2795 gnatmake my_main.adb -largs file1.o file2.o
2796 @end smallexample
2798 @cindex Binder output file
2799 @noindent
2800 If the main program is in a language other than Ada, then you may have
2801 more than one entry point into the Ada subsystem. You must use a special
2802 binder option to generate callable routines that initialize and
2803 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2804 Calls to the initialization and finalization routines must be inserted
2805 in the main program, or some other appropriate point in the code. The
2806 call to initialize the Ada units must occur before the first Ada
2807 subprogram is called, and the call to finalize the Ada units must occur
2808 after the last Ada subprogram returns. The binder will place the
2809 initialization and finalization subprograms into the
2810 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2811 sources.  To illustrate, we have the following example:
2813 @smallexample
2814 /* main.c */
2815 extern void adainit (void);
2816 extern void adafinal (void);
2817 extern int add (int, int);
2818 extern int sub (int, int);
2820 int main (int argc, char *argv[])
2822   int a = 21, b = 7;
2824   adainit();
2826   /* Should print "21 + 7 = 28" */
2827   printf ("%d + %d = %d\n", a, b, add (a, b));
2828   /* Should print "21 - 7 = 14" */
2829   printf ("%d - %d = %d\n", a, b, sub (a, b));
2831   adafinal();
2833 @end smallexample
2835 @smallexample @c ada
2836 --  unit1.ads
2837 package Unit1 is
2838    function Add (A, B : Integer) return Integer;
2839    pragma Export (C, Add, "add");
2840 end Unit1;
2842 --  unit1.adb
2843 package body Unit1 is
2844    function Add (A, B : Integer) return Integer is
2845    begin
2846       return A + B;
2847    end Add;
2848 end Unit1;
2850 --  unit2.ads
2851 package Unit2 is
2852    function Sub (A, B : Integer) return Integer;
2853    pragma Export (C, Sub, "sub");
2854 end Unit2;
2856 --  unit2.adb
2857 package body Unit2 is
2858    function Sub (A, B : Integer) return Integer is
2859    begin
2860       return A - B;
2861    end Sub;
2862 end Unit2;
2863 @end smallexample
2865 @enumerate
2866 @item
2867 The build procedure for this application is similar to the last
2868 example's.  First, compile the foreign language files to generate object
2869 files:
2870 @smallexample
2871 gcc -c main.c
2872 @end smallexample
2874 @item
2875 Next, compile the Ada units to produce a set of object files and ALI
2876 files:
2877 @smallexample
2878 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2879 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2880 @end smallexample
2882 @item
2883 Run the Ada binder on every generated ALI file.  Make sure to use the
2884 @option{-n} option to specify a foreign main program:
2885 @smallexample
2886 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2887 @end smallexample
2889 @item
2890 Link the Ada main program, the Ada objects and the foreign language
2891 objects. You need only list the last ALI file here:
2892 @smallexample
2893 gnatlink unit2.ali main.o -o exec_file
2894 @end smallexample
2896 This procedure yields a binary executable called @file{exec_file}.
2897 @end enumerate
2899 @node Calling Conventions
2900 @subsection Calling Conventions
2901 @cindex Foreign Languages
2902 @cindex Calling Conventions
2903 GNAT follows standard calling sequence conventions and will thus interface
2904 to any other language that also follows these conventions. The following
2905 Convention identifiers are recognized by GNAT:
2907 @table @code
2908 @cindex Interfacing to Ada
2909 @cindex Other Ada compilers
2910 @cindex Convention Ada
2911 @item Ada
2912 This indicates that the standard Ada calling sequence will be
2913 used and all Ada data items may be passed without any limitations in the
2914 case where GNAT is used to generate both the caller and callee. It is also
2915 possible to mix GNAT generated code and code generated by another Ada
2916 compiler. In this case, the data types should be restricted to simple
2917 cases, including primitive types. Whether complex data types can be passed
2918 depends on the situation. Probably it is safe to pass simple arrays, such
2919 as arrays of integers or floats. Records may or may not work, depending
2920 on whether both compilers lay them out identically. Complex structures
2921 involving variant records, access parameters, tasks, or protected types,
2922 are unlikely to be able to be passed.
2924 Note that in the case of GNAT running
2925 on a platform that supports DEC Ada 83, a higher degree of compatibility
2926 can be guaranteed, and in particular records are layed out in an identical
2927 manner in the two compilers. Note also that if output from two different
2928 compilers is mixed, the program is responsible for dealing with elaboration
2929 issues. Probably the safest approach is to write the main program in the
2930 version of Ada other than GNAT, so that it takes care of its own elaboration
2931 requirements, and then call the GNAT-generated adainit procedure to ensure
2932 elaboration of the GNAT components. Consult the documentation of the other
2933 Ada compiler for further details on elaboration.
2935 However, it is not possible to mix the tasking run time of GNAT and
2936 DEC Ada 83, All the tasking operations must either be entirely within
2937 GNAT compiled sections of the program, or entirely within DEC Ada 83
2938 compiled sections of the program.
2940 @cindex Interfacing to Assembly
2941 @cindex Convention Assembler
2942 @item Assembler
2943 Specifies assembler as the convention. In practice this has the
2944 same effect as convention Ada (but is not equivalent in the sense of being
2945 considered the same convention).
2947 @cindex Convention Asm
2948 @findex Asm
2949 @item Asm
2950 Equivalent to Assembler.
2952 @cindex Interfacing to COBOL
2953 @cindex Convention COBOL
2954 @findex COBOL
2955 @item COBOL
2956 Data will be passed according to the conventions described
2957 in section B.4 of the Ada 95 Reference Manual.
2959 @findex C
2960 @cindex Interfacing to C
2961 @cindex Convention C
2962 @item C
2963 Data will be passed according to the conventions described
2964 in section B.3 of the Ada 95 Reference Manual.
2966 @findex C varargs function
2967 @cindex Intefacing to C varargs function
2968 @cindex varargs function intefacs
2969 @item C varargs function
2970 In C, @code{varargs} allows a function to take a variable number of
2971 arguments. There is no direct equivalent in this to Ada. One
2972 approach that can be used is to create a C wrapper for each
2973 different profile and then interface to this C wrapper. For
2974 example, to print an @code{int} value using @code{printf},
2975 create a C function @code{printfi} that takes two arguments, a
2976 pointer to a string and an int, and calls @code{printf}.
2977 Then in the Ada program, use pragma @code{Import} to
2978 interface to printfi.
2980 It may work on some platforms to directly interface to
2981 a @code{varargs} function by providing a specific Ada profile
2982 for a a particular call. However, this does not work on
2983 all platforms, since there is no guarantee that the
2984 calling sequence for a two argument normal C function
2985 is the same as for calling a @code{varargs} C function with
2986 the same two arguments.
2988 @cindex Convention Default
2989 @findex Default
2990 @item Default
2991 Equivalent to C.
2993 @cindex Convention External
2994 @findex External
2995 @item External
2996 Equivalent to C.
2998 @findex C++
2999 @cindex Interfacing to C++
3000 @cindex Convention C++
3001 @item CPP
3002 This stands for C++. For most purposes this is identical to C.
3003 See the separate description of the specialized GNAT pragmas relating to
3004 C++ interfacing for further details.
3006 @findex Fortran
3007 @cindex Interfacing to Fortran
3008 @cindex Convention Fortran
3009 @item Fortran
3010 Data will be passed according to the conventions described
3011 in section B.5 of the Ada 95 Reference Manual.
3013 @item Intrinsic
3014 This applies to an intrinsic operation, as defined in the Ada 95
3015 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3016 this means that the body of the subprogram is provided by the compiler itself,
3017 usually by means of an efficient code sequence, and that the user does not
3018 supply an explicit body for it. In an application program, the pragma can
3019 only be applied to the following two sets of names, which the GNAT compiler
3020 recognizes.
3022 @itemize @bullet
3023 @item
3024 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3025 Arithmetic.  The corresponding subprogram declaration must have
3026 two formal parameters. The
3027 first one must be a signed integer type or a modular type with a binary
3028 modulus, and the second parameter must be of type Natural.
3029 The return type must be the same as the type of the first argument. The size
3030 of this type can only be 8, 16, 32, or 64.
3031 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3032 The corresponding operator declaration must have parameters and result type
3033 that have the same root numeric type (for example, all three are long_float
3034 types). This simplifies the definition of operations that use type checking
3035 to perform dimensional checks:
3037 @smallexample @c ada
3038 type Distance is new Long_Float;
3039 type Time     is new Long_Float;
3040 type Velocity is new Long_Float;
3041 function "/" (D : Distance; T : Time)
3042   return Velocity;
3043 pragma Import (Intrinsic, "/");
3044 @end smallexample
3046 @noindent
3047 This common idiom is often programmed with a generic definition and an
3048 explicit body. The pragma makes it simpler to introduce such declarations.
3049 It incurs no overhead in compilation time or code size, because it is
3050 implemented as a single machine instruction.
3051 @end itemize
3052 @noindent
3054 @ifset unw
3055 @findex Stdcall
3056 @cindex Convention Stdcall
3057 @item Stdcall
3058 This is relevant only to NT/Win95 implementations of GNAT,
3059 and specifies that the Stdcall calling sequence will be used, as defined
3060 by the NT API.
3062 @findex DLL
3063 @cindex Convention DLL
3064 @item DLL
3065 This is equivalent to Stdcall.
3067 @findex Win32
3068 @cindex Convention Win32
3069 @item Win32
3070 This is equivalent to Stdcall.
3071 @end ifset
3073 @findex Stubbed
3074 @cindex Convention Stubbed
3075 @item Stubbed
3076 This is a special convention that indicates that the compiler
3077 should provide a stub body that raises @code{Program_Error}.
3078 @end table
3080 @noindent
3081 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3082 that can be used to parametrize conventions and allow additional synonyms
3083 to be specified. For example if you have legacy code in which the convention
3084 identifier Fortran77 was used for Fortran, you can use the configuration
3085 pragma:
3087 @smallexample @c ada
3088 pragma Convention_Identifier (Fortran77, Fortran);
3089 @end smallexample
3091 @noindent
3092 And from now on the identifier Fortran77 may be used as a convention
3093 identifier (for example in an @code{Import} pragma) with the same
3094 meaning as Fortran.
3096 @node Building Mixed Ada & C++ Programs
3097 @section Building Mixed Ada & C++ Programs
3099 @noindent
3100 A programmer inexperienced with mixed-language development may find that
3101 building an application containing both Ada and C++ code can be a
3102 challenge. As a matter of fact, interfacing with C++ has not been
3103 standardized in the Ada 95 Reference Manual due to the immaturity of --
3104 and lack of standards for -- C++ at the time. This section gives a few
3105 hints that should make this task easier. The first section addresses
3106 the differences regarding interfacing with C. The second section
3107 looks into the delicate problem of linking the complete application from
3108 its Ada and C++ parts. The last section gives some hints on how the GNAT
3109 run time can be adapted in order to allow inter-language dispatching
3110 with a new C++ compiler.
3112 @menu
3113 * Interfacing to C++::
3114 * Linking a Mixed C++ & Ada Program::
3115 * A Simple Example::
3116 * Adapting the Run Time to a New C++ Compiler::
3117 @end menu
3119 @node Interfacing to C++
3120 @subsection Interfacing to C++
3122 @noindent
3123 GNAT supports interfacing with C++ compilers generating code that is
3124 compatible with the standard Application Binary Interface of the given
3125 platform.
3127 @noindent
3128 Interfacing can be done at 3 levels: simple data, subprograms, and
3129 classes. In the first two cases, GNAT offers a specific @var{Convention
3130 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3131 the names of subprograms, and currently, GNAT does not provide any help
3132 to solve the demangling problem. This problem can be addressed in two
3133 ways:
3134 @itemize @bullet
3135 @item
3136 by modifying the C++ code in order to force a C convention using
3137 the @code{extern "C"} syntax.
3139 @item
3140 by figuring out the mangled name and use it as the Link_Name argument of
3141 the pragma import.
3142 @end itemize
3144 @noindent
3145 Interfacing at the class level can be achieved by using the GNAT specific
3146 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3147 Reference Manual for additional information.
3149 @node Linking a Mixed C++ & Ada Program
3150 @subsection Linking a Mixed C++ & Ada Program
3152 @noindent
3153 Usually the linker of the C++ development system must be used to link
3154 mixed applications because most C++ systems will resolve elaboration
3155 issues (such as calling constructors on global class instances)
3156 transparently during the link phase. GNAT has been adapted to ease the
3157 use of a foreign linker for the last phase. Three cases can be
3158 considered:
3159 @enumerate
3161 @item
3162 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3163 The C++ linker can simply be called by using the C++ specific driver
3164 called @code{c++}. Note that this setup is not very common because it
3165 may involve recompiling the whole GCC tree from sources, which makes it
3166 harder to upgrade the compilation system for one language without
3167 destabilizing the other.
3169 @smallexample
3170 $ c++ -c file1.C
3171 $ c++ -c file2.C
3172 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3173 @end smallexample
3175 @item
3176 Using GNAT and G++ from two different GCC installations: If both
3177 compilers are on the PATH, the previous method may be used. It is
3178 important to note that environment variables such as C_INCLUDE_PATH,
3179 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3180 at the same time and may make one of the two compilers operate
3181 improperly if set during invocation of the wrong compiler.  It is also
3182 very important that the linker uses the proper @file{libgcc.a} GCC
3183 library -- that is, the one from the C++ compiler installation. The
3184 implicit link command as suggested in the gnatmake command from the
3185 former example can be replaced by an explicit link command with the
3186 full-verbosity option in order to verify which library is used:
3187 @smallexample
3188 $ gnatbind ada_unit
3189 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3190 @end smallexample
3191 If there is a problem due to interfering environment variables, it can
3192 be worked around by using an intermediate script. The following example
3193 shows the proper script to use when GNAT has not been installed at its
3194 default location and g++ has been installed at its default location:
3196 @smallexample
3197 $ cat ./my_script
3198 #!/bin/sh
3199 unset BINUTILS_ROOT
3200 unset GCC_ROOT
3201 c++ $*
3202 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3203 @end smallexample
3205 @item
3206 Using a non-GNU C++ compiler: The commands previously described can be
3207 used to insure that the C++ linker is used. Nonetheless, you need to add
3208 the path to libgcc explicitly, since some libraries needed by GNAT are
3209 located in this directory:
3211 @smallexample
3212 $ cat ./my_script
3213 #!/bin/sh
3214 CC $* `gcc -print-libgcc-file-name`
3215 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3216 @end smallexample
3218 Where CC is the name of the non-GNU C++ compiler.
3220 @end enumerate
3222 @node A Simple Example
3223 @subsection  A Simple Example
3224 @noindent
3225 The following example, provided as part of the GNAT examples, shows how
3226 to achieve procedural interfacing between Ada and C++ in both
3227 directions. The C++ class A has two methods. The first method is exported
3228 to Ada by the means of an extern C wrapper function. The second method
3229 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3230 a limited record with a layout comparable to the C++ class. The Ada
3231 subprogram, in turn, calls the C++ method. So, starting from the C++
3232 main program, the process passes back and forth between the two
3233 languages.
3235 @noindent
3236 Here are the compilation commands:
3237 @smallexample
3238 $ gnatmake -c simple_cpp_interface
3239 $ c++ -c cpp_main.C
3240 $ c++ -c ex7.C
3241 $ gnatbind -n simple_cpp_interface
3242 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3243       -lstdc++ ex7.o cpp_main.o
3244 @end smallexample
3246 @noindent
3247 Here are the corresponding sources:
3248 @smallexample
3250 //cpp_main.C
3252 #include "ex7.h"
3254 extern "C" @{
3255   void adainit (void);
3256   void adafinal (void);
3257   void method1 (A *t);
3260 void method1 (A *t)
3262   t->method1 ();
3265 int main ()
3267   A obj;
3268   adainit ();
3269   obj.method2 (3030);
3270   adafinal ();
3273 //ex7.h
3275 class Origin @{
3276  public:
3277   int o_value;
3279 class A : public Origin @{
3280  public:
3281   void method1 (void);
3282   void method2 (int v);
3283   A();
3284   int   a_value;
3287 //ex7.C
3289 #include "ex7.h"
3290 #include <stdio.h>
3292 extern "C" @{ void ada_method2 (A *t, int v);@}
3294 void A::method1 (void)
3296   a_value = 2020;
3297   printf ("in A::method1, a_value = %d \n",a_value);
3301 void A::method2 (int v)
3303    ada_method2 (this, v);
3304    printf ("in A::method2, a_value = %d \n",a_value);
3308 A::A(void)
3310    a_value = 1010;
3311   printf ("in A::A, a_value = %d \n",a_value);
3314 -- Ada sources
3315 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3317    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3318    @b{begin}
3319       Method1 (This);
3320       This.A_Value := V;
3321    @b{end} Ada_Method2;
3323 @b{end} Simple_Cpp_Interface;
3325 @b{package} Simple_Cpp_Interface @b{is}
3326    @b{type} A @b{is} @b{limited}
3327       @b{record}
3328          O_Value : Integer;
3329          A_Value : Integer;
3330       @b{end} @b{record};
3331    @b{pragma} Convention (C, A);
3333    @b{procedure} Method1 (This : @b{in} @b{out} A);
3334    @b{pragma} Import (C, Method1);
3336    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3337    @b{pragma} Export (C, Ada_Method2);
3339 @b{end} Simple_Cpp_Interface;
3340 @end smallexample
3342 @node Adapting the Run Time to a New C++ Compiler
3343 @subsection Adapting the Run Time to a New C++ Compiler
3344 @noindent
3345 GNAT offers the capability to derive Ada 95 tagged types directly from
3346 preexisting C++ classes and . See ``Interfacing with C++'' in the
3347 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3348 such a goal
3349 has been made user configurable through a GNAT library unit
3350 @code{Interfaces.CPP}. The default version of this file is adapted to
3351 the GNU C++ compiler. Internal knowledge of the virtual
3352 table layout used by the new C++ compiler is needed to configure
3353 properly this unit. The Interface of this unit is known by the compiler
3354 and cannot be changed except for the value of the constants defining the
3355 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3356 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3357 of this unit for more details.
3359 @node Comparison between GNAT and C/C++ Compilation Models
3360 @section Comparison between GNAT and C/C++ Compilation Models
3362 @noindent
3363 The GNAT model of compilation is close to the C and C++ models. You can
3364 think of Ada specs as corresponding to header files in C. As in C, you
3365 don't need to compile specs; they are compiled when they are used. The
3366 Ada @code{with} is similar in effect to the @code{#include} of a C
3367 header.
3369 One notable difference is that, in Ada, you may compile specs separately
3370 to check them for semantic and syntactic accuracy. This is not always
3371 possible with C headers because they are fragments of programs that have
3372 less specific syntactic or semantic rules.
3374 The other major difference is the requirement for running the binder,
3375 which performs two important functions. First, it checks for
3376 consistency. In C or C++, the only defense against assembling
3377 inconsistent programs lies outside the compiler, in a makefile, for
3378 example. The binder satisfies the Ada requirement that it be impossible
3379 to construct an inconsistent program when the compiler is used in normal
3380 mode.
3382 @cindex Elaboration order control
3383 The other important function of the binder is to deal with elaboration
3384 issues. There are also elaboration issues in C++ that are handled
3385 automatically. This automatic handling has the advantage of being
3386 simpler to use, but the C++ programmer has no control over elaboration.
3387 Where @code{gnatbind} might complain there was no valid order of
3388 elaboration, a C++ compiler would simply construct a program that
3389 malfunctioned at run time.
3391 @node Comparison between GNAT and Conventional Ada Library Models
3392 @section Comparison between GNAT and Conventional Ada Library Models
3394 @noindent
3395 This section is intended to be useful to Ada programmers who have
3396 previously used an Ada compiler implementing the traditional Ada library
3397 model, as described in the Ada 95 Language Reference Manual. If you
3398 have not used such a system, please go on to the next section.
3400 @cindex GNAT library
3401 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3402 source files themselves acts as the library. Compiling Ada programs does
3403 not generate any centralized information, but rather an object file and
3404 a ALI file, which are of interest only to the binder and linker.
3405 In a traditional system, the compiler reads information not only from
3406 the source file being compiled, but also from the centralized library.
3407 This means that the effect of a compilation depends on what has been
3408 previously compiled. In particular:
3410 @itemize @bullet
3411 @item
3412 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3413 to the version of the unit most recently compiled into the library.
3415 @item
3416 Inlining is effective only if the necessary body has already been
3417 compiled into the library.
3419 @item
3420 Compiling a unit may obsolete other units in the library.
3421 @end itemize
3423 @noindent
3424 In GNAT, compiling one unit never affects the compilation of any other
3425 units because the compiler reads only source files. Only changes to source
3426 files can affect the results of a compilation. In particular:
3428 @itemize @bullet
3429 @item
3430 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3431 to the source version of the unit that is currently accessible to the
3432 compiler.
3434 @item
3435 @cindex Inlining
3436 Inlining requires the appropriate source files for the package or
3437 subprogram bodies to be available to the compiler. Inlining is always
3438 effective, independent of the order in which units are complied.
3440 @item
3441 Compiling a unit never affects any other compilations. The editing of
3442 sources may cause previous compilations to be out of date if they
3443 depended on the source file being modified.
3444 @end itemize
3446 @noindent
3447 The most important result of these differences is that order of compilation
3448 is never significant in GNAT. There is no situation in which one is
3449 required to do one compilation before another. What shows up as order of
3450 compilation requirements in the traditional Ada library becomes, in
3451 GNAT, simple source dependencies; in other words, there is only a set
3452 of rules saying what source files must be present when a file is
3453 compiled.
3455 @ifset vms
3456 @node Placement of temporary files
3457 @section Placement of temporary files
3458 @cindex Temporary files (user control over placement)
3460 @noindent
3461 GNAT creates temporary files in the directory designated by the environment
3462 variable @env{TMPDIR}.
3463 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3464 for detailed information on how environment variables are resolved.
3465 For most users the easiest way to make use of this feature is to simply
3466 define @env{TMPDIR} as a job level logical name).
3467 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3468 for compiler temporary files, then you can include something like the
3469 following command in your @file{LOGIN.COM} file:
3471 @smallexample
3472 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3473 @end smallexample
3475 @noindent
3476 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3477 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3478 designated by @env{TEMP}.
3479 If none of these environment variables are defined then GNAT uses the
3480 directory designated by the logical name @code{SYS$SCRATCH:}
3481 (by default the user's home directory). If all else fails
3482 GNAT uses the current directory for temporary files.
3483 @end ifset
3485 @c *************************
3486 @node Compiling Using gcc
3487 @chapter Compiling Using @code{gcc}
3489 @noindent
3490 This chapter discusses how to compile Ada programs using the @code{gcc}
3491 command. It also describes the set of switches
3492 that can be used to control the behavior of the compiler.
3493 @menu
3494 * Compiling Programs::
3495 * Switches for gcc::
3496 * Search Paths and the Run-Time Library (RTL)::
3497 * Order of Compilation Issues::
3498 * Examples::
3499 @end menu
3501 @node Compiling Programs
3502 @section Compiling Programs
3504 @noindent
3505 The first step in creating an executable program is to compile the units
3506 of the program using the @code{gcc} command. You must compile the
3507 following files:
3509 @itemize @bullet
3510 @item
3511 the body file (@file{.adb}) for a library level subprogram or generic
3512 subprogram
3514 @item
3515 the spec file (@file{.ads}) for a library level package or generic
3516 package that has no body
3518 @item
3519 the body file (@file{.adb}) for a library level package
3520 or generic package that has a body
3522 @end itemize
3524 @noindent
3525 You need @emph{not} compile the following files
3527 @itemize @bullet
3529 @item
3530 the spec of a library unit which has a body
3532 @item
3533 subunits
3534 @end itemize
3536 @noindent
3537 because they are compiled as part of compiling related units. GNAT
3538 package specs
3539 when the corresponding body is compiled, and subunits when the parent is
3540 compiled.
3542 @cindex cannot generate code
3543 If you attempt to compile any of these files, you will get one of the
3544 following error messages (where fff is the name of the file you compiled):
3546 @smallexample
3547 cannot generate code for file @var{fff} (package spec)
3548 to check package spec, use -gnatc
3550 cannot generate code for file @var{fff} (missing subunits)
3551 to check parent unit, use -gnatc
3553 cannot generate code for file @var{fff} (subprogram spec)
3554 to check subprogram spec, use -gnatc
3556 cannot generate code for file @var{fff} (subunit)
3557 to check subunit, use -gnatc
3558 @end smallexample
3560 @noindent
3561 As indicated by the above error messages, if you want to submit
3562 one of these files to the compiler to check for correct semantics
3563 without generating code, then use the @option{-gnatc} switch.
3565 The basic command for compiling a file containing an Ada unit is
3567 @smallexample
3568 $ gcc -c [@var{switches}] @file{file name}
3569 @end smallexample
3571 @noindent
3572 where @var{file name} is the name of the Ada file (usually
3573 having an extension
3574 @file{.ads} for a spec or @file{.adb} for a body).
3575 @ifclear vms
3576 You specify the
3577 @option{-c} switch to tell @code{gcc} to compile, but not link, the file.
3578 @end ifclear
3579 The result of a successful compilation is an object file, which has the
3580 same name as the source file but an extension of @file{.o} and an Ada
3581 Library Information (ALI) file, which also has the same name as the
3582 source file, but with @file{.ali} as the extension. GNAT creates these
3583 two output files in the current directory, but you may specify a source
3584 file in any directory using an absolute or relative path specification
3585 containing the directory information.
3587 @findex gnat1
3588 @code{gcc} is actually a driver program that looks at the extensions of
3589 the file arguments and loads the appropriate compiler. For example, the
3590 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3591 These programs are in directories known to the driver program (in some
3592 configurations via environment variables you set), but need not be in
3593 your path. The @code{gcc} driver also calls the assembler and any other
3594 utilities needed to complete the generation of the required object
3595 files.
3597 It is possible to supply several file names on the same @code{gcc}
3598 command. This causes @code{gcc} to call the appropriate compiler for
3599 each file. For example, the following command lists three separate
3600 files to be compiled:
3602 @smallexample
3603 $ gcc -c x.adb y.adb z.c
3604 @end smallexample
3606 @noindent
3607 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3608 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3609 The compiler generates three object files @file{x.o}, @file{y.o} and
3610 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3611 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3612 @ifclear vms
3613 except for
3614 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3615 @end ifclear
3617 @node Switches for gcc
3618 @section Switches for @code{gcc}
3620 @noindent
3621 The @code{gcc} command accepts switches that control the
3622 compilation process. These switches are fully described in this section.
3623 First we briefly list all the switches, in alphabetical order, then we
3624 describe the switches in more detail in functionally grouped sections.
3626 @menu
3627 * Output and Error Message Control::
3628 * Warning Message Control::
3629 * Debugging and Assertion Control::
3630 * Validity Checking::
3631 * Style Checking::
3632 * Run-Time Checks::
3633 * Stack Overflow Checking::
3634 * Using gcc for Syntax Checking::
3635 * Using gcc for Semantic Checking::
3636 * Compiling Ada 83 Programs::
3637 * Character Set Control::
3638 * File Naming Control::
3639 * Subprogram Inlining Control::
3640 * Auxiliary Output Control::
3641 * Debugging Control::
3642 * Exception Handling Control::
3643 * Units to Sources Mapping Files::
3644 * Integrated Preprocessing::
3645 * Code Generation Control::
3646 @ifset vms
3647 * Return Codes::
3648 @end ifset
3649 @end menu
3651 @table @option
3652 @c !sort!
3653 @ifclear vms
3654 @cindex @option{-b} (@code{gcc})
3655 @item -b @var{target}
3656 Compile your program to run on @var{target}, which is the name of a
3657 system configuration. You must have a GNAT cross-compiler built if
3658 @var{target} is not the same as your host system.
3660 @item -B@var{dir}
3661 @cindex @option{-B} (@code{gcc})
3662 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3663 from @var{dir} instead of the default location. Only use this switch
3664 when multiple versions of the GNAT compiler are available. See the
3665 @code{gcc} manual page for further details. You would normally use the
3666 @option{-b} or @option{-V} switch instead.
3668 @item -c
3669 @cindex @option{-c} (@code{gcc})
3670 Compile. Always use this switch when compiling Ada programs.
3672 Note: for some other languages when using @code{gcc}, notably in
3673 the case of C and C++, it is possible to use
3674 use @code{gcc} without a @option{-c} switch to
3675 compile and link in one step. In the case of GNAT, you
3676 cannot use this approach, because the binder must be run
3677 and @code{gcc} cannot be used to run the GNAT binder.
3678 @end ifclear
3680 @item -fno-inline
3681 @cindex @option{-fno-inline} (@code{gcc})
3682 Suppresses all back-end inlining, even if other optimization or inlining
3683 switches are set.
3684 This includes suppression of inlining that results
3685 from the use of the pragma @code{Inline_Always}.
3686 See also @option{-gnatn} and @option{-gnatN}.
3688 @item -fno-strict-aliasing
3689 @cindex @option{-fno-strict-aliasing} (@code{gcc})
3690 Causes the compiler to avoid assumptions regarding non-aliasing
3691 of objects of different types. See section
3692 @pxref{Optimization and Strict Aliasing} for details.
3694 @item -fstack-check
3695 @cindex @option{-fstack-check} (@code{gcc})
3696 Activates stack checking.
3697 See @ref{Stack Overflow Checking} for details of the use of this option.
3699 @item ^-g^/DEBUG^
3700 @cindex @option{^-g^/DEBUG^} (@code{gcc})
3701 Generate debugging information. This information is stored in the object
3702 file and copied from there to the final executable file by the linker,
3703 where it can be read by the debugger. You must use the
3704 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3706 @item -gnat83
3707 @cindex @option{-gnat83} (@code{gcc})
3708 Enforce Ada 83 restrictions.
3710 @item -gnata
3711 @cindex @option{-gnata} (@code{gcc})
3712 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3713 activated.
3715 @item -gnatA
3716 @cindex @option{-gnatA} (@code{gcc})
3717 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3718 it will be ignored.
3720 @item -gnatb
3721 @cindex @option{-gnatb} (@code{gcc})
3722 Generate brief messages to @file{stderr} even if verbose mode set.
3724 @item -gnatc
3725 @cindex @option{-gnatc} (@code{gcc})
3726 Check syntax and semantics only (no code generation attempted).
3728 @item -gnatd
3729 @cindex @option{-gnatd} (@code{gcc})
3730 Specify debug options for the compiler. The string of characters after
3731 the @option{-gnatd} specify the specific debug options. The possible
3732 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3733 compiler source file @file{debug.adb} for details of the implemented
3734 debug options. Certain debug options are relevant to applications
3735 programmers, and these are documented at appropriate points in this
3736 users guide.
3738 @item -gnatD
3739 @cindex @option{-gnatD} (@code{gcc})
3740 Create expanded source files for source level debugging. This switch
3741 also suppress generation of cross-reference information
3742 (see @option{-gnatx}).
3744 @item -gnatec=@var{path}
3745 @cindex @option{-gnatec} (@code{gcc})
3746 Specify a configuration pragma file
3747 @ifclear vms
3748 (the equal sign is optional)
3749 @end ifclear
3750 (see @ref{The Configuration Pragmas Files}).
3752 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3753 @cindex @option{-gnateD} (@code{gcc})
3754 Defines a symbol, associated with value, for preprocessing.
3755 (see @ref{Integrated Preprocessing})
3757 @item -gnatef
3758 @cindex @option{-gnatef} (@code{gcc})
3759 Display full source path name in brief error messages.
3761 @item -gnatem=@var{path}
3762 @cindex @option{-gnatem} (@code{gcc})
3763 Specify a mapping file
3764 @ifclear vms
3765 (the equal sign is optional)
3766 @end ifclear
3767 (see @ref{Units to Sources Mapping Files}).
3769 @item -gnatep=@var{file}
3770 @cindex @option{-gnatep} (@code{gcc})
3771 Specify a preprocessing data file
3772 @ifclear vms
3773 (the equal sign is optional)
3774 @end ifclear
3775 (see @ref{Integrated Preprocessing}).
3777 @item -gnatE
3778 @cindex @option{-gnatE} (@code{gcc})
3779 Full dynamic elaboration checks.
3781 @item -gnatf
3782 @cindex @option{-gnatf} (@code{gcc})
3783 Full errors. Multiple errors per line, all undefined references, do not
3784 attempt to suppress cascaded errors.
3786 @item -gnatF
3787 @cindex @option{-gnatF} (@code{gcc})
3788 Externals names are folded to all uppercase.
3790 @item -gnatg
3791 @cindex @option{-gnatg} (@code{gcc})
3792 Internal GNAT implementation mode. This should not be used for
3793 applications programs, it is intended only for use by the compiler
3794 and its run-time library. For documentation, see the GNAT sources.
3795 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3796 are generated on unreferenced entities, and all warnings are treated
3797 as errors.
3799 @item -gnatG
3800 @cindex @option{-gnatG} (@code{gcc})
3801 List generated expanded code in source form.
3803 @item ^-gnath^/HELP^
3804 @cindex @option{^-gnath^/HELP^} (@code{gcc})
3805 Output usage information. The output is written to @file{stdout}.
3807 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3808 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
3809 Identifier character set
3810 @ifclear vms
3811 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3812 @end ifclear
3813 @ifset vms
3814 For details of the possible selections for @var{c},
3815 see @xref{Character Set Control}.
3816 @end ifset
3818 @item -gnatk=@var{n}
3819 @cindex @option{-gnatk} (@code{gcc})
3820 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3822 @item -gnatl
3823 @cindex @option{-gnatl} (@code{gcc})
3824 Output full source listing with embedded error messages.
3826 @item -gnatL
3827 @cindex @option{-gnatL} (@code{gcc})
3828 Use the longjmp/setjmp method for exception handling
3830 @item -gnatm=@var{n}
3831 @cindex @option{-gnatm} (@code{gcc})
3832 Limit number of detected error or warning messages to @var{n}
3833 where @var{n} is in the range 1..999_999. The default setting if
3834 no switch is given is 9999. Compilation is terminated if this
3835 limit is exceeded.
3837 @item -gnatn
3838 @cindex @option{-gnatn} (@code{gcc})
3839 Activate inlining for subprograms for which
3840 pragma @code{inline} is specified. This inlining is performed
3841 by the GCC back-end.
3843 @item -gnatN
3844 @cindex @option{-gnatN} (@code{gcc})
3845 Activate front end inlining for subprograms for which
3846 pragma @code{Inline} is specified. This inlining is performed
3847 by the front end and will be visible in the
3848 @option{-gnatG} output.
3849 In some cases, this has proved more effective than the back end
3850 inlining resulting from the use of
3851 @option{-gnatn}.
3852 Note that
3853 @option{-gnatN} automatically implies
3854 @option{-gnatn} so it is not necessary
3855 to specify both options. There are a few cases that the back-end inlining
3856 catches that cannot be dealt with in the front-end.
3858 @item -gnato
3859 @cindex @option{-gnato} (@code{gcc})
3860 Enable numeric overflow checking (which is not normally enabled by
3861 default). Not that division by zero is a separate check that is not
3862 controlled by this switch (division by zero checking is on by default).
3864 @item -gnatp
3865 @cindex @option{-gnatp} (@code{gcc})
3866 Suppress all checks.
3868 @item -gnatP
3869 @cindex @option{-gnatP} (@code{gcc})
3870 Enable polling. This is required on some systems (notably Windows NT) to
3871 obtain asynchronous abort and asynchronous transfer of control capability.
3872 See the description of pragma Polling in the GNAT Reference Manual for
3873 full details.
3875 @item -gnatq
3876 @cindex @option{-gnatq} (@code{gcc})
3877 Don't quit; try semantics, even if parse errors.
3879 @item -gnatQ
3880 @cindex @option{-gnatQ} (@code{gcc})
3881 Don't quit; generate @file{ALI} and tree files even if illegalities.
3883 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3884 @cindex @option{-gnatR} (@code{gcc})
3885 Output representation information for declared types and objects.
3887 @item -gnats
3888 @cindex @option{-gnats} (@code{gcc})
3889 Syntax check only.
3891 @item -gnatS
3892 @cindex @option{-gnatS} (@code{gcc})
3893 Print package Standard.
3895 @item -gnatt
3896 @cindex @option{-gnatt} (@code{gcc})
3897 Generate tree output file.
3899 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3900 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@code{gcc})
3901 All compiler tables start at @var{nnn} times usual starting size.
3903 @item -gnatu
3904 @cindex @option{-gnatu} (@code{gcc})
3905 List units for this compilation.
3907 @item -gnatU
3908 @cindex @option{-gnatU} (@code{gcc})
3909 Tag all error messages with the unique string ``error:''
3911 @item -gnatv
3912 @cindex @option{-gnatv} (@code{gcc})
3913 Verbose mode. Full error output with source lines to @file{stdout}.
3915 @item -gnatV
3916 @cindex @option{-gnatV} (@code{gcc})
3917 Control level of validity checking. See separate section describing
3918 this feature.
3920 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3921 @cindex @option{^-gnatw^/WARNINGS^} (@code{gcc})
3922 Warning mode where
3923 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3924 the exact warnings that
3925 are enabled or disabled. (see @ref{Warning Message Control})
3927 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3928 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
3929 Wide character encoding method
3930 @ifclear vms
3931 (@var{e}=n/h/u/s/e/8).
3932 @end ifclear
3933 @ifset vms
3934 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3935 @end ifset
3937 @item -gnatx
3938 @cindex @option{-gnatx} (@code{gcc})
3939 Suppress generation of cross-reference information.
3941 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3942 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@code{gcc})
3943 Enable built-in style checks. (see @ref{Style Checking})
3945 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3946 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@code{gcc})
3947 Distribution stub generation and compilation
3948 @ifclear vms
3949 (@var{m}=r/c for receiver/caller stubs).
3950 @end ifclear
3951 @ifset vms
3952 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3953 to be generated and compiled).
3954 @end ifset
3956 @item -gnatZ
3957 Use the zero cost method for exception handling
3959 @item ^-I^/SEARCH=^@var{dir}
3960 @cindex @option{^-I^/SEARCH^} (@code{gcc})
3961 @cindex RTL
3962 Direct GNAT to search the @var{dir} directory for source files needed by
3963 the current compilation
3964 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3966 @item ^-I-^/NOCURRENT_DIRECTORY^
3967 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3968 @cindex RTL
3969 Except for the source file named in the command line, do not look for source
3970 files in the directory containing the source file named in the command line
3971 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3973 @ifclear vms
3974 @item -mbig-switch
3975 @cindex @option{-mbig-switch} (@command{gcc})
3976 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
3977 This standard gcc switch causes the compiler to use larger offsets in its
3978 jump table representation for @code{case} statements.
3979 This may result in less efficient code, but is sometimes necessary
3980 (for example on HP-UX targets)
3981 @cindex HP-UX and @option{-mbig-switch} option
3982 in order to compile large and/or nested @code{case} statements.
3984 @item -o @var{file}
3985 @cindex @option{-o} (@code{gcc})
3986 This switch is used in @code{gcc} to redirect the generated object file
3987 and its associated ALI file. Beware of this switch with GNAT, because it may
3988 cause the object file and ALI file to have different names which in turn
3989 may confuse the binder and the linker.
3990 @end ifclear
3992 @item -nostdinc
3993 @cindex @option{-nostdinc} (@command{gcc})
3994 Inhibit the search of the default location for the GNAT Run Time
3995 Library (RTL) source files.
3997 @item -nostdlib
3998 @cindex @option{-nostdlib} (@command{gcc})
3999 Inhibit the search of the default location for the GNAT Run Time
4000 Library (RTL) ALI files.
4002 @ifclear vms
4003 @item -O[@var{n}]
4004 @cindex @option{-O} (@code{gcc})
4005 @var{n} controls the optimization level.
4007 @table @asis
4008 @item n = 0
4009 No optimization, the default setting if no @option{-O} appears
4011 @item n = 1
4012 Normal optimization, the default if you specify @option{-O} without
4013 an operand.
4015 @item n = 2
4016 Extensive optimization
4018 @item n = 3
4019 Extensive optimization with automatic inlining of subprograms not
4020 specified by pragma @code{Inline}. This applies only to
4021 inlining within a unit. For details on control of inlining
4022 see @xref{Subprogram Inlining Control}.
4023 @end table
4024 @end ifclear
4026 @ifset vms
4027 @item  /NOOPTIMIZE
4028 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4029 Equivalent to @option{/OPTIMIZE=NONE}.
4030 This is the default behavior in the absence of an @option{/OPTMIZE}
4031 qualifier.
4033 @item /OPTIMIZE[=(keyword[,...])]
4034 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4035 Selects the level of optimization for your program. The supported
4036 keywords are as follows:
4037 @table @code
4038 @item   ALL
4039 Perform most optimizations, including those that
4040 are expensive.
4041 This is the default if the @option{/OPTMIZE} qualifier is supplied
4042 without keyword options.
4044 @item   NONE
4045 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4047 @item SOME
4048 Perform some optimizations, but omit ones that are costly.
4050 @item   DEVELOPMENT
4051 Same as @code{SOME}.
4053 @item   INLINING
4054 Full optimization, and also attempt automatic inlining of small
4055 subprograms within a unit even when pragma @code{Inline}
4056 is not specified (@pxref{Inlining of Subprograms}).
4058 @item   UNROLL_LOOPS
4059 Try to unroll loops. This keyword may be specified together with
4060 any keyword above other than @code{NONE}. Loop unrolling
4061 usually, but not always, improves the performance of programs.
4062 @end table
4063 @end ifset
4065 @ifclear vms
4066 @item -pass-exit-codes
4067 @cindex @option{-pass-exit-codes} (@code{gcc})
4068 Catch exit codes from the compiler and use the most meaningful as
4069 exit status.
4070 @end ifclear
4072 @item --RTS=@var{rts-path}
4073 @cindex @option{--RTS} (@code{gcc})
4074 Specifies the default location of the runtime library. Same meaning as the
4075 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
4077 @item ^-S^/ASM^
4078 @cindex @option{^-S^/ASM^} (@code{gcc})
4079 ^Used in place of @option{-c} to^Used to^
4080 cause the assembler source file to be
4081 generated, using @file{^.s^.S^} as the extension,
4082 instead of the object file.
4083 This may be useful if you need to examine the generated assembly code.
4085 @item ^-fverbose-asm^/VERBOSE_ASM^
4086 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@code{gcc})
4087 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4088 to cause the generated assembly code file to be annotated with variable
4089 names, making it significantly easier to follow.
4091 @item ^-v^/VERBOSE^
4092 @cindex @option{^-v^/VERBOSE^} (@code{gcc})
4093 Show commands generated by the @code{gcc} driver. Normally used only for
4094 debugging purposes or if you need to be sure what version of the
4095 compiler you are executing.
4097 @ifclear vms
4098 @item -V @var{ver}
4099 @cindex @option{-V} (@code{gcc})
4100 Execute @var{ver} version of the compiler. This is the @code{gcc}
4101 version, not the GNAT version.
4102 @end ifclear
4104 @end table
4106 @ifclear vms
4107 You may combine a sequence of GNAT switches into a single switch. For
4108 example, the combined switch
4110 @cindex Combining GNAT switches
4111 @smallexample
4112 -gnatofi3
4113 @end smallexample
4115 @noindent
4116 is equivalent to specifying the following sequence of switches:
4118 @smallexample
4119 -gnato -gnatf -gnati3
4120 @end smallexample
4121 @end ifclear
4123 @c NEED TO CHECK THIS FOR VMS
4125 @noindent
4126 The following restrictions apply to the combination of switches
4127 in this manner:
4129 @itemize @bullet
4130 @item
4131 The switch @option{-gnatc} if combined with other switches must come
4132 first in the string.
4134 @item
4135 The switch @option{-gnats} if combined with other switches must come
4136 first in the string.
4138 @item
4139 The switches
4140 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4141 may not be combined with any other switches.
4143 @ifclear vms
4144 @item
4145 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4146 switch), then all further characters in the switch are interpreted
4147 as style modifiers (see description of @option{-gnaty}).
4149 @item
4150 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4151 switch), then all further characters in the switch are interpreted
4152 as debug flags (see description of @option{-gnatd}).
4154 @item
4155 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4156 switch), then all further characters in the switch are interpreted
4157 as warning mode modifiers (see description of @option{-gnatw}).
4159 @item
4160 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4161 switch), then all further characters in the switch are interpreted
4162 as validity checking options (see description of @option{-gnatV}).
4163 @end ifclear
4164 @end itemize
4166 @node Output and Error Message Control
4167 @subsection Output and Error Message Control
4168 @findex stderr
4170 @noindent
4171 The standard default format for error messages is called ``brief format''.
4172 Brief format messages are written to @file{stderr} (the standard error
4173 file) and have the following form:
4175 @smallexample
4176 e.adb:3:04: Incorrect spelling of keyword "function"
4177 e.adb:4:20: ";" should be "is"
4178 @end smallexample
4180 @noindent
4181 The first integer after the file name is the line number in the file,
4182 and the second integer is the column number within the line.
4183 @code{glide} can parse the error messages
4184 and point to the referenced character.
4185 The following switches provide control over the error message
4186 format:
4188 @table @option
4189 @c !sort!
4190 @item -gnatv
4191 @cindex @option{-gnatv} (@code{gcc})
4192 @findex stdout
4193 @ifclear vms
4194 The v stands for verbose.
4195 @end ifclear
4196 The effect of this setting is to write long-format error
4197 messages to @file{stdout} (the standard output file.
4198 The same program compiled with the
4199 @option{-gnatv} switch would generate:
4201 @smallexample
4202 @cartouche
4203 3. funcion X (Q : Integer)
4204    |
4205 >>> Incorrect spelling of keyword "function"
4206 4. return Integer;
4207                  |
4208 >>> ";" should be "is"
4209 @end cartouche
4210 @end smallexample
4212 @noindent
4213 The vertical bar indicates the location of the error, and the @samp{>>>}
4214 prefix can be used to search for error messages. When this switch is
4215 used the only source lines output are those with errors.
4217 @item -gnatl
4218 @cindex @option{-gnatl} (@code{gcc})
4219 @ifclear vms
4220 The @code{l} stands for list.
4221 @end ifclear
4222 This switch causes a full listing of
4223 the file to be generated. The output might look as follows:
4225 @smallexample
4226 @cartouche
4227  1. procedure E is
4228  2.    V : Integer;
4229  3.    funcion X (Q : Integer)
4230        |
4231     >>> Incorrect spelling of keyword "function"
4232  4.     return Integer;
4233                       |
4234     >>> ";" should be "is"
4235  5.    begin
4236  6.       return Q + Q;
4237  7.    end;
4238  8. begin
4239  9.    V := X + X;
4240 10.end E;
4241 @end cartouche
4242 @end smallexample
4244 @noindent
4245 @findex stderr
4246 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4247 standard output is redirected, a brief summary is written to
4248 @file{stderr} (standard error) giving the number of error messages and
4249 warning messages generated.
4251 @item -gnatU
4252 @cindex @option{-gnatU} (@code{gcc})
4253 This switch forces all error messages to be preceded by the unique
4254 string ``error:''. This means that error messages take a few more
4255 characters in space, but allows easy searching for and identification
4256 of error messages.
4258 @item -gnatb
4259 @cindex @option{-gnatb} (@code{gcc})
4260 @ifclear vms
4261 The @code{b} stands for brief.
4262 @end ifclear
4263 This switch causes GNAT to generate the
4264 brief format error messages to @file{stderr} (the standard error
4265 file) as well as the verbose
4266 format message or full listing (which as usual is written to
4267 @file{stdout} (the standard output file).
4269 @item -gnatm^^=^@var{n}
4270 @cindex @option{-gnatm} (@code{gcc})
4271 @ifclear vms
4272 The @code{m} stands for maximum.
4273 @end ifclear
4274 @var{n} is a decimal integer in the
4275 range of 1 to 999 and limits the number of error messages to be
4276 generated. For example, using @option{-gnatm2} might yield
4278 @smallexample
4279 e.adb:3:04: Incorrect spelling of keyword "function"
4280 e.adb:5:35: missing ".."
4281 fatal error: maximum errors reached
4282 compilation abandoned
4283 @end smallexample
4285 @item -gnatf
4286 @cindex @option{-gnatf} (@code{gcc})
4287 @cindex Error messages, suppressing
4288 @ifclear vms
4289 The @code{f} stands for full.
4290 @end ifclear
4291 Normally, the compiler suppresses error messages that are likely to be
4292 redundant. This switch causes all error
4293 messages to be generated. In particular, in the case of
4294 references to undefined variables. If a given variable is referenced
4295 several times, the normal format of messages is
4296 @smallexample
4297 e.adb:7:07: "V" is undefined (more references follow)
4298 @end smallexample
4300 @noindent
4301 where the parenthetical comment warns that there are additional
4302 references to the variable @code{V}. Compiling the same program with the
4303 @option{-gnatf} switch yields
4305 @smallexample
4306 e.adb:7:07: "V" is undefined
4307 e.adb:8:07: "V" is undefined
4308 e.adb:8:12: "V" is undefined
4309 e.adb:8:16: "V" is undefined
4310 e.adb:9:07: "V" is undefined
4311 e.adb:9:12: "V" is undefined
4312 @end smallexample
4314 @noindent
4315 The @option{-gnatf} switch also generates additional information for
4316 some error messages.  Some examples are:
4318 @itemize @bullet
4319 @item
4320 Full details on entities not available in high integrity mode
4321 @item
4322 Details on possibly non-portable unchecked conversion
4323 @item
4324 List possible interpretations for ambiguous calls
4325 @item
4326 Additional details on incorrect parameters
4327 @end itemize
4329 @item -gnatq
4330 @cindex @option{-gnatq} (@code{gcc})
4331 @ifclear vms
4332 The @code{q} stands for quit (really ``don't quit'').
4333 @end ifclear
4334 In normal operation mode, the compiler first parses the program and
4335 determines if there are any syntax errors. If there are, appropriate
4336 error messages are generated and compilation is immediately terminated.
4337 This switch tells
4338 GNAT to continue with semantic analysis even if syntax errors have been
4339 found. This may enable the detection of more errors in a single run. On
4340 the other hand, the semantic analyzer is more likely to encounter some
4341 internal fatal error when given a syntactically invalid tree.
4343 @item -gnatQ
4344 @cindex @option{-gnatQ} (@code{gcc})
4345 In normal operation mode, the @file{ALI} file is not generated if any
4346 illegalities are detected in the program. The use of @option{-gnatQ} forces
4347 generation of the @file{ALI} file. This file is marked as being in
4348 error, so it cannot be used for binding purposes, but it does contain
4349 reasonably complete cross-reference information, and thus may be useful
4350 for use by tools (e.g. semantic browsing tools or integrated development
4351 environments) that are driven from the @file{ALI} file. This switch
4352 implies @option{-gnatq}, since the semantic phase must be run to get a
4353 meaningful ALI file.
4355 In addition, if @option{-gnatt} is also specified, then the tree file is
4356 generated even if there are illegalities. It may be useful in this case
4357 to also specify @option{-gnatq} to ensure that full semantic processing
4358 occurs. The resulting tree file can be processed by ASIS, for the purpose
4359 of providing partial information about illegal units, but if the error
4360 causes the tree to be badly malformed, then ASIS may crash during the
4361 analysis.
4363 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4364 being in error, @code{gnatmake} will attempt to recompile the source when it
4365 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4367 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4368 since ALI files are never generated if @option{-gnats} is set.
4370 @end table
4372 @node Warning Message Control
4373 @subsection Warning Message Control
4374 @cindex Warning messages
4375 @noindent
4376 In addition to error messages, which correspond to illegalities as defined
4377 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4378 situations.
4380 First, the compiler considers some constructs suspicious and generates a
4381 warning message to alert you to a possible error. Second, if the
4382 compiler detects a situation that is sure to raise an exception at
4383 run time, it generates a warning message. The following shows an example
4384 of warning messages:
4385 @smallexample
4386 e.adb:4:24: warning: creation of object may raise Storage_Error
4387 e.adb:10:17: warning: static value out of range
4388 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4389 @end smallexample
4391 @noindent
4392 GNAT considers a large number of situations as appropriate
4393 for the generation of warning messages. As always, warnings are not
4394 definite indications of errors. For example, if you do an out-of-range
4395 assignment with the deliberate intention of raising a
4396 @code{Constraint_Error} exception, then the warning that may be
4397 issued does not indicate an error. Some of the situations for which GNAT
4398 issues warnings (at least some of the time) are given in the following
4399 list. This list is not complete, and new warnings are often added to
4400 subsequent versions of GNAT. The list is intended to give a general idea
4401 of the kinds of warnings that are generated.
4403 @itemize @bullet
4404 @item
4405 Possible infinitely recursive calls
4407 @item
4408 Out-of-range values being assigned
4410 @item
4411 Possible order of elaboration problems
4413 @item
4414 Unreachable code
4416 @item
4417 Fixed-point type declarations with a null range
4419 @item
4420 Direct_IO or Sequential_IO instantiated with a type that has access values
4422 @item
4423 Variables that are never assigned a value
4425 @item
4426 Variables that are referenced before being initialized
4428 @item
4429 Task entries with no corresponding @code{accept} statement
4431 @item
4432 Duplicate accepts for the same task entry in a @code{select}
4434 @item
4435 Objects that take too much storage
4437 @item
4438 Unchecked conversion between types of differing sizes
4440 @item
4441 Missing @code{return} statement along some execution path in a function
4443 @item
4444 Incorrect (unrecognized) pragmas
4446 @item
4447 Incorrect external names
4449 @item
4450 Allocation from empty storage pool
4452 @item
4453 Potentially blocking operation in protected type
4455 @item
4456 Suspicious parenthesization of expressions
4458 @item
4459 Mismatching bounds in an aggregate
4461 @item
4462 Attempt to return local value by reference
4464 @item
4465 Premature instantiation of a generic body
4467 @item
4468 Attempt to pack aliased components
4470 @item
4471 Out of bounds array subscripts
4473 @item
4474 Wrong length on string assignment
4476 @item
4477 Violations of style rules if style checking is enabled
4479 @item
4480 Unused @code{with} clauses
4482 @item
4483 @code{Bit_Order} usage that does not have any effect
4485 @item
4486 @code{Standard.Duration} used to resolve universal fixed expression
4488 @item
4489 Dereference of possibly null value
4491 @item
4492 Declaration that is likely to cause storage error
4494 @item
4495 Internal GNAT unit @code{with}'ed by application unit
4497 @item
4498 Values known to be out of range at compile time
4500 @item
4501 Unreferenced labels and variables
4503 @item
4504 Address overlays that could clobber memory
4506 @item
4507 Unexpected initialization when address clause present
4509 @item
4510 Bad alignment for address clause
4512 @item
4513 Useless type conversions
4515 @item
4516 Redundant assignment statements and other redundant constructs
4518 @item
4519 Useless exception handlers
4521 @item
4522 Accidental hiding of name by child unit
4524 @item
4525 Access before elaboration detected at compile time
4527 @item
4528 A range in a @code{for} loop that is known to be null or might be null
4530 @end itemize
4532 @noindent
4533 The following switches are available to control the handling of
4534 warning messages:
4536 @table @option
4537 @c !sort!
4538 @item -gnatwa
4539 @emph{Activate all optional errors.}
4540 @cindex @option{-gnatwa} (@code{gcc})
4541 This switch activates most optional warning messages, see remaining list
4542 in this section for details on optional warning messages that can be
4543 individually controlled.  The warnings that are not turned on by this
4544 switch are
4545 @option{-gnatwd} (implicit dereferencing),
4546 @option{-gnatwh} (hiding),
4547 and @option{-gnatwl} (elaboration warnings).
4548 All other optional warnings are turned on.
4550 @item -gnatwA
4551 @emph{Suppress all optional errors.}
4552 @cindex @option{-gnatwA} (@code{gcc})
4553 This switch suppresses all optional warning messages, see remaining list
4554 in this section for details on optional warning messages that can be
4555 individually controlled.
4557 @item -gnatwc
4558 @emph{Activate warnings on conditionals.}
4559 @cindex @option{-gnatwc} (@code{gcc})
4560 @cindex Conditionals, constant
4561 This switch activates warnings for conditional expressions used in
4562 tests that are known to be True or False at compile time. The default
4563 is that such warnings are not generated.
4564 Note that this warning does
4565 not get issued for the use of boolean variables or constants whose
4566 values are known at compile time, since this is a standard technique
4567 for conditional compilation in Ada, and this would generate too many
4568 ``false positive'' warnings.
4569 This warning can also be turned on using @option{-gnatwa}.
4571 @item -gnatwC
4572 @emph{Suppress warnings on conditionals.}
4573 @cindex @option{-gnatwC} (@code{gcc})
4574 This switch suppresses warnings for conditional expressions used in
4575 tests that are known to be True or False at compile time.
4577 @item -gnatwd
4578 @emph{Activate warnings on implicit dereferencing.}
4579 @cindex @option{-gnatwd} (@code{gcc})
4580 If this switch is set, then the use of a prefix of an access type
4581 in an indexed component, slice, or selected component without an
4582 explicit @code{.all} will generate a warning. With this warning
4583 enabled, access checks occur only at points where an explicit
4584 @code{.all} appears in the source code (assuming no warnings are
4585 generated as a result of this switch). The default is that such
4586 warnings are not generated.
4587 Note that @option{-gnatwa} does not affect the setting of
4588 this warning option.
4590 @item -gnatwD
4591 @emph{Suppress warnings on implicit dereferencing.}
4592 @cindex @option{-gnatwD} (@code{gcc})
4593 @cindex Implicit dereferencing
4594 @cindex Dereferencing, implicit
4595 This switch suppresses warnings for implicit dereferences in
4596 indexed components, slices, and selected components.
4598 @item -gnatwe
4599 @emph{Treat warnings as errors.}
4600 @cindex @option{-gnatwe} (@code{gcc})
4601 @cindex Warnings, treat as error
4602 This switch causes warning messages to be treated as errors.
4603 The warning string still appears, but the warning messages are counted
4604 as errors, and prevent the generation of an object file.
4606 @item -gnatwf
4607 @emph{Activate warnings on unreferenced formals.}
4608 @cindex @option{-gnatwf} (@code{gcc})
4609 @cindex Formals, unreferenced
4610 This switch causes a warning to be generated if a formal parameter
4611 is not referenced in the body of the subprogram. This warning can
4612 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4614 @item -gnatwF
4615 @emph{Suppress warnings on unreferenced formals.}
4616 @cindex @option{-gnatwF} (@code{gcc})
4617 This switch suppresses warnings for unreferenced formal
4618 parameters. Note that the
4619 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4620 effect of warning on unreferenced entities other than subprogram
4621 formals.
4623 @item -gnatwg
4624 @emph{Activate warnings on unrecognized pragmas.}
4625 @cindex @option{-gnatwg} (@code{gcc})
4626 @cindex Pragmas, unrecognized
4627 This switch causes a warning to be generated if an unrecognized
4628 pragma is encountered. Apart from issuing this warning, the
4629 pragma is ignored and has no effect. This warning can
4630 also be turned on using @option{-gnatwa}. The default
4631 is that such warnings are issued (satisfying the Ada Reference
4632 Manual requirement that such warnings appear).
4634 @item -gnatwG
4635 @emph{Suppress warnings on unrecognized pragmas.}
4636 @cindex @option{-gnatwG} (@code{gcc})
4637 This switch suppresses warnings for unrecognized pragmas.
4639 @item -gnatwh
4640 @emph{Activate warnings on hiding.}
4641 @cindex @option{-gnatwh} (@code{gcc})
4642 @cindex Hiding of Declarations
4643 This switch activates warnings on hiding declarations.
4644 A declaration is considered hiding
4645 if it is for a non-overloadable entity, and it declares an entity with the
4646 same name as some other entity that is directly or use-visible. The default
4647 is that such warnings are not generated.
4648 Note that @option{-gnatwa} does not affect the setting of this warning option.
4650 @item -gnatwH
4651 @emph{Suppress warnings on hiding.}
4652 @cindex @option{-gnatwH} (@code{gcc})
4653 This switch suppresses warnings on hiding declarations.
4655 @item -gnatwi
4656 @emph{Activate warnings on implementation units.}
4657 @cindex @option{-gnatwi} (@code{gcc})
4658 This switch activates warnings for a @code{with} of an internal GNAT
4659 implementation unit, defined as any unit from the @code{Ada},
4660 @code{Interfaces}, @code{GNAT},
4661 ^^@code{DEC},^ or @code{System}
4662 hierarchies that is not
4663 documented in either the Ada Reference Manual or the GNAT
4664 Programmer's Reference Manual. Such units are intended only
4665 for internal implementation purposes and should not be @code{with}'ed
4666 by user programs. The default is that such warnings are generated
4667 This warning can also be turned on using @option{-gnatwa}.
4669 @item -gnatwI
4670 @emph{Disable warnings on implementation units.}
4671 @cindex @option{-gnatwI} (@code{gcc})
4672 This switch disables warnings for a @code{with} of an internal GNAT
4673 implementation unit.
4675 @item -gnatwj
4676 @emph{Activate warnings on obsolescent features (Annex J).}
4677 @cindex @option{-gnatwj} (@code{gcc})
4678 @cindex Features, obsolescent
4679 @cindex Obsolescent features
4680 If this warning option is activated, then warnings are generated for
4681 calls to subprograms marked with @code{pragma Obsolescent} and
4682 for use of features in Annex J of the Ada Reference Manual. In the
4683 case of Annex J, not all features are flagged. In particular use
4684 of the renamed packages (like @code{Text_IO}) and use of package
4685 @code{ASCII} are not flagged, since these are very common and
4686 would generate many annoying positive warnings. The default is that
4687 such warnings are not generated.
4689 In addition to the above cases, warnings are also generated for
4690 GNAT features that have been provided in past versions but which
4691 have been superceded (typically by features in the new Ada standard).
4692 For example, @code{pragma Ravenscar} will be flagged since its
4693 function is replaced by @code{pragma Profile(Ravenscar)}.
4695 Note that this warning option functions differently from the
4696 restriction @code{No_Obsolescent_Features} in two respects.
4697 First, the restriction applies only to annex J features.
4698 Second, the restriction does flag uses of package @code{ASCII}.
4700 @item -gnatwJ
4701 @emph{Suppress warnings on obsolescent features (Annex J).}
4702 @cindex @option{-gnatwJ} (@code{gcc})
4703 This switch disables warnings on use of obsolescent features.
4705 @item -gnatwk
4706 @emph{Activate warnings on variables that could be constants.}
4707 @cindex @option{-gnatwk} (@code{gcc})
4708 This switch activates warnings for variables that are initialized but
4709 never modified, and then could be declared constants.
4711 @item -gnatwK
4712 @emph{Suppress warnings on variables that could be constants.}
4713 @cindex @option{-gnatwK} (@code{gcc})
4714 This switch disables warnings on variables that could be declared constants.
4716 @item -gnatwl
4717 @emph{Activate warnings for missing elaboration pragmas.}
4718 @cindex @option{-gnatwl} (@code{gcc})
4719 @cindex Elaboration, warnings
4720 This switch activates warnings on missing
4721 @code{pragma Elaborate_All} statements.
4722 See the section in this guide on elaboration checking for details on
4723 when such pragma should be used. Warnings are also generated if you
4724 are using the static mode of elaboration, and a @code{pragma Elaborate}
4725 is encountered. The default is that such warnings
4726 are not generated.
4727 This warning is not automatically turned on by the use of @option{-gnatwa}.
4729 @item -gnatwL
4730 @emph{Suppress warnings for missing elaboration pragmas.}
4731 @cindex @option{-gnatwL} (@code{gcc})
4732 This switch suppresses warnings on missing pragma Elaborate_All statements.
4733 See the section in this guide on elaboration checking for details on
4734 when such pragma should be used.
4736 @item -gnatwm
4737 @emph{Activate warnings on modified but unreferenced variables.}
4738 @cindex @option{-gnatwm} (@code{gcc})
4739 This switch activates warnings for variables that are assigned (using
4740 an initialization value or with one or more assignment statements) but
4741 whose value is never read. The warning is suppressed for volatile
4742 variables and also for variables that are renamings of other variables
4743 or for which an address clause is given.
4744 This warning can also be turned on using @option{-gnatwa}.
4746 @item -gnatwM
4747 @emph{Disable warnings on modified but unreferenced variables.}
4748 @cindex @option{-gnatwM} (@code{gcc})
4749 This switch disables warnings for variables that are assigned or
4750 initialized, but never read.
4752 @item -gnatwn
4753 @emph{Set normal warnings mode.}
4754 @cindex @option{-gnatwn} (@code{gcc})
4755 This switch sets normal warning mode, in which enabled warnings are
4756 issued and treated as warnings rather than errors. This is the default
4757 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4758 an explicit @option{-gnatws} or
4759 @option{-gnatwe}. It also cancels the effect of the
4760 implicit @option{-gnatwe} that is activated by the
4761 use of @option{-gnatg}.
4763 @item -gnatwo
4764 @emph{Activate warnings on address clause overlays.}
4765 @cindex @option{-gnatwo} (@code{gcc})
4766 @cindex Address Clauses, warnings
4767 This switch activates warnings for possibly unintended initialization
4768 effects of defining address clauses that cause one variable to overlap
4769 another. The default is that such warnings are generated.
4770 This warning can also be turned on using @option{-gnatwa}.
4772 @item -gnatwO
4773 @emph{Suppress warnings on address clause overlays.}
4774 @cindex @option{-gnatwO} (@code{gcc})
4775 This switch suppresses warnings on possibly unintended initialization
4776 effects of defining address clauses that cause one variable to overlap
4777 another.
4779 @item -gnatwp
4780 @emph{Activate warnings on ineffective pragma Inlines.}
4781 @cindex @option{-gnatwp} (@code{gcc})
4782 @cindex Inlining, warnings
4783 This switch activates warnings for failure of front end inlining
4784 (activated by @option{-gnatN}) to inline a particular call. There are
4785 many reasons for not being able to inline a call, including most
4786 commonly that the call is too complex to inline.
4787 This warning can also be turned on using @option{-gnatwa}.
4789 @item -gnatwP
4790 @emph{Suppress warnings on ineffective pragma Inlines.}
4791 @cindex @option{-gnatwP} (@code{gcc})
4792 This switch suppresses warnings on ineffective pragma Inlines. If the
4793 inlining mechanism cannot inline a call, it will simply ignore the
4794 request silently.
4796 @item -gnatwr
4797 @emph{Activate warnings on redundant constructs.}
4798 @cindex @option{-gnatwr} (@code{gcc})
4799 This switch activates warnings for redundant constructs. The following
4800 is the current list of constructs regarded as redundant:
4801 This warning can also be turned on using @option{-gnatwa}.
4803 @itemize @bullet
4804 @item
4805 Assignment of an item to itself.
4806 @item
4807 Type conversion that converts an expression to its own type.
4808 @item
4809 Use of the attribute @code{Base} where @code{typ'Base} is the same
4810 as @code{typ}.
4811 @item
4812 Use of pragma @code{Pack} when all components are placed by a record
4813 representation clause.
4814 @item
4815 Exception handler containing only a reraise statement (raise with no
4816 operand) which has no effect.
4817 @item
4818 Use of the operator abs on an operand that is known at compile time
4819 to be non-negative
4820 @item
4821 Comparison of boolean expressions to an explicit True value.
4822 @end itemize
4824 @item -gnatwR
4825 @emph{Suppress warnings on redundant constructs.}
4826 @cindex @option{-gnatwR} (@code{gcc})
4827 This switch suppresses warnings for redundant constructs.
4829 @item -gnatws
4830 @emph{Suppress all warnings.}
4831 @cindex @option{-gnatws} (@code{gcc})
4832 This switch completely suppresses the
4833 output of all warning messages from the GNAT front end.
4834 Note that it does not suppress warnings from the @code{gcc} back end.
4835 To suppress these back end warnings as well, use the switch @option{-w}
4836 in addition to @option{-gnatws}.
4838 @item -gnatwu
4839 @emph{Activate warnings on unused entities.}
4840 @cindex @option{-gnatwu} (@code{gcc})
4841 This switch activates warnings to be generated for entities that
4842 are declared but not referenced, and for units that are @code{with}'ed
4843 and not
4844 referenced. In the case of packages, a warning is also generated if
4845 no entities in the package are referenced. This means that if the package
4846 is referenced but the only references are in @code{use}
4847 clauses or @code{renames}
4848 declarations, a warning is still generated. A warning is also generated
4849 for a generic package that is @code{with}'ed but never instantiated.
4850 In the case where a package or subprogram body is compiled, and there
4851 is a @code{with} on the corresponding spec
4852 that is only referenced in the body,
4853 a warning is also generated, noting that the
4854 @code{with} can be moved to the body. The default is that
4855 such warnings are not generated.
4856 This switch also activates warnings on unreferenced formals
4857 (it is includes the effect of @option{-gnatwf}).
4858 This warning can also be turned on using @option{-gnatwa}.
4860 @item -gnatwU
4861 @emph{Suppress warnings on unused entities.}
4862 @cindex @option{-gnatwU} (@code{gcc})
4863 This switch suppresses warnings for unused entities and packages.
4864 It also turns off warnings on unreferenced formals (and thus includes
4865 the effect of @option{-gnatwF}).
4867 @item -gnatwv
4868 @emph{Activate warnings on unassigned variables.}
4869 @cindex @option{-gnatwv} (@code{gcc})
4870 @cindex Unassigned variable warnings
4871 This switch activates warnings for access to variables which
4872 may not be properly initialized. The default is that
4873 such warnings are generated.
4875 @item -gnatwV
4876 @emph{Suppress warnings on unassigned variables.}
4877 @cindex @option{-gnatwV} (@code{gcc})
4878 This switch suppresses warnings for access to variables which
4879 may not be properly initialized.
4881 @item -gnatwx
4882 @emph{Activate warnings on Export/Import pragmas.}
4883 @cindex @option{-gnatwx} (@code{gcc})
4884 @cindex Export/Import pragma warnings
4885 This switch activates warnings on Export/Import pragmas when
4886 the compiler detects a possible conflict between the Ada and
4887 foreign language calling sequences. For example, the use of
4888 default parameters in a convention C procedure is dubious
4889 because the C compiler cannot supply the proper default, so
4890 a warning is issued. The default is that such warnings are
4891 generated.
4893 @item -gnatwX
4894 @emph{Suppress warnings on Export/Import pragmas.}
4895 @cindex @option{-gnatwX} (@code{gcc})
4896 This switch suppresses warnings on Export/Import pragmas.
4897 The sense of this is that you are telling the compiler that
4898 you know what you are doing in writing the pragma, and it
4899 should not complain at you.
4901 @item -gnatwz
4902 @emph{Activate warnings on unchecked conversions.}
4903 @cindex @option{-gnatwz} (@code{gcc})
4904 @cindex Unchecked_Conversion warnings
4905 This switch activates warnings for unchecked conversions
4906 where the types are known at compile time to have different
4907 sizes. The default
4908 is that such warnings are generated.
4910 @item -gnatwZ
4911 @emph{Suppress warnings on unchecked conversions.}
4912 @cindex @option{-gnatwZ} (@code{gcc})
4913 This switch suppresses warnings for unchecked conversions
4914 where the types are known at compile time to have different
4915 sizes.
4917 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4918 @cindex @option{-Wuninitialized}
4919 The warnings controlled by the @option{-gnatw} switch are generated by the
4920 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4921 can provide additional warnings. One such useful warning is provided by
4922 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4923 conjunction with tunrning on optimization mode. This causes the flow
4924 analysis circuits of the back end optimizer to output additional
4925 warnings about uninitialized variables.
4927 @item ^-w^/NO_BACK_END_WARNINGS^
4928 @cindex @option{-w}
4929 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4930 be used in conjunction with @option{-gnatws} to ensure that all warnings
4931 are suppressed during the entire compilation process.
4933 @end table
4935 @noindent
4936 @ifclear vms
4937 A string of warning parameters can be used in the same parameter. For example:
4939 @smallexample
4940 -gnatwaLe
4941 @end smallexample
4943 @noindent
4944 will turn on all optional warnings except for elaboration pragma warnings,
4945 and also specify that warnings should be treated as errors.
4946 @end ifclear
4947 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4949 @table @option
4950 @c !sort!
4951 @item -gnatwC
4952 @item -gnatwD
4953 @item -gnatwF
4954 @item -gnatwg
4955 @item -gnatwH
4956 @item -gnatwi
4957 @item -gnatwJ
4958 @item -gnatwK
4959 @item -gnatwL
4960 @item -gnatwM
4961 @item -gnatwn
4962 @item -gnatwo
4963 @item -gnatwP
4964 @item -gnatwR
4965 @item -gnatwU
4966 @item -gnatwv
4967 @item -gnatwz
4968 @item -gnatwx
4970 @end table
4972 @node Debugging and Assertion Control
4973 @subsection Debugging and Assertion Control
4975 @table @option
4976 @item -gnata
4977 @cindex @option{-gnata} (@code{gcc})
4978 @findex Assert
4979 @findex Debug
4980 @cindex Assertions
4982 @noindent
4983 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4984 are ignored. This switch, where @samp{a} stands for assert, causes
4985 @code{Assert} and @code{Debug} pragmas to be activated.
4987 The pragmas have the form:
4989 @smallexample
4990 @cartouche
4991    @b{pragma} Assert (@var{Boolean-expression} [,
4992                       @var{static-string-expression}])
4993    @b{pragma} Debug (@var{procedure call})
4994 @end cartouche
4995 @end smallexample
4997 @noindent
4998 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4999 If the result is @code{True}, the pragma has no effect (other than
5000 possible side effects from evaluating the expression). If the result is
5001 @code{False}, the exception @code{Assert_Failure} declared in the package
5002 @code{System.Assertions} is
5003 raised (passing @var{static-string-expression}, if present, as the
5004 message associated with the exception). If no string expression is
5005 given the default is a string giving the file name and line number
5006 of the pragma.
5008 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5009 @code{pragma Debug} may appear within a declaration sequence, allowing
5010 debugging procedures to be called between declarations.
5012 @ifset vms
5013 @item /DEBUG[=debug-level]
5014 @itemx  /NODEBUG
5015 Specifies how much debugging information is to be included in
5016 the resulting object file where 'debug-level' is one of the following:
5017 @table @code
5018 @item   TRACEBACK
5019 Include both debugger symbol records and traceback
5020 the object file.
5021 This is the default setting.
5022 @item   ALL
5023 Include both debugger symbol records and traceback in
5024 object file.
5025 @item   NONE
5026 Excludes both debugger symbol records and traceback
5027 the object file. Same as /NODEBUG.
5028 @item   SYMBOLS
5029 Includes only debugger symbol records in the object
5030 file. Note that this doesn't include traceback information.
5031 @end table
5032 @end ifset
5033 @end table
5035 @node Validity Checking
5036 @subsection Validity Checking
5037 @findex Validity Checking
5039 @noindent
5040 The Ada 95 Reference Manual has specific requirements for checking
5041 for invalid values. In particular, RM 13.9.1 requires that the
5042 evaluation of invalid values (for example from unchecked conversions),
5043 not result in erroneous execution. In GNAT, the result of such an
5044 evaluation in normal default mode is to either use the value
5045 unmodified, or to raise Constraint_Error in those cases where use
5046 of the unmodified value would cause erroneous execution. The cases
5047 where unmodified values might lead to erroneous execution are case
5048 statements (where a wild jump might result from an invalid value),
5049 and subscripts on the left hand side (where memory corruption could
5050 occur as a result of an invalid value).
5052 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5053 checking mode.
5054 @ifclear vms
5055 The @code{x} argument is a string of letters that
5056 indicate validity checks that are performed or not performed in addition
5057 to the default checks described above.
5058 @end ifclear
5059 @ifset vms
5060 The options allowed for this qualifier
5061 indicate validity checks that are performed or not performed in addition
5062 to the default checks described above.
5063 @end ifset
5065 @table @option
5066 @c !sort!
5067 @item -gnatVa
5068 @emph{All validity checks.}
5069 @cindex @option{-gnatVa} (@code{gcc})
5070 All validity checks are turned on.
5071 @ifclear vms
5072 That is, @option{-gnatVa} is
5073 equivalent to @option{gnatVcdfimorst}.
5074 @end ifclear
5076 @item -gnatVc
5077 @emph{Validity checks for copies.}
5078 @cindex @option{-gnatVc} (@code{gcc})
5079 The right hand side of assignments, and the initializing values of
5080 object declarations are validity checked.
5082 @item -gnatVd
5083 @emph{Default (RM) validity checks.}
5084 @cindex @option{-gnatVd} (@code{gcc})
5085 Some validity checks are done by default following normal Ada semantics
5086 (RM 13.9.1 (9-11)).
5087 A check is done in case statements that the expression is within the range
5088 of the subtype. If it is not, Constraint_Error is raised.
5089 For assignments to array components, a check is done that the expression used
5090 as index is within the range. If it is not, Constraint_Error is raised.
5091 Both these validity checks may be turned off using switch @option{-gnatVD}.
5092 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5093 switch @option{-gnatVd} will leave the checks turned on.
5094 Switch @option{-gnatVD} should be used only if you are sure that all such
5095 expressions have valid values. If you use this switch and invalid values
5096 are present, then the program is erroneous, and wild jumps or memory
5097 overwriting may occur.
5099 @item -gnatVf
5100 @emph{Validity checks for floating-point values.}
5101 @cindex @option{-gnatVf} (@code{gcc})
5102 In the absence of this switch, validity checking occurs only for discrete
5103 values. If @option{-gnatVf} is specified, then validity checking also applies
5104 for floating-point values, and NaN's and infinities are considered invalid,
5105 as well as out of range values for constrained types. Note that this means
5106 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5107 in which floating-point values are checked depends on the setting of other
5108 options. For example,
5109 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5110 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5111 (the order does not matter) specifies that floating-point parameters of mode
5112 @code{in} should be validity checked.
5114 @item -gnatVi
5115 @emph{Validity checks for @code{in} mode parameters}
5116 @cindex @option{-gnatVi} (@code{gcc})
5117 Arguments for parameters of mode @code{in} are validity checked in function
5118 and procedure calls at the point of call.
5120 @item -gnatVm
5121 @emph{Validity checks for @code{in out} mode parameters.}
5122 @cindex @option{-gnatVm} (@code{gcc})
5123 Arguments for parameters of mode @code{in out} are validity checked in
5124 procedure calls at the point of call. The @code{'m'} here stands for
5125 modify, since this concerns parameters that can be modified by the call.
5126 Note that there is no specific option to test @code{out} parameters,
5127 but any reference within the subprogram will be tested in the usual
5128 manner, and if an invalid value is copied back, any reference to it
5129 will be subject to validity checking.
5131 @item -gnatVn
5132 @emph{No validity checks.}
5133 @cindex @option{-gnatVn} (@code{gcc})
5134 This switch turns off all validity checking, including the default checking
5135 for case statements and left hand side subscripts. Note that the use of
5136 the switch @option{-gnatp} suppresses all run-time checks, including
5137 validity checks, and thus implies @option{-gnatVn}. When this switch
5138 is used, it cancels any other @option{-gnatV} previously issued.
5140 @item -gnatVo
5141 @emph{Validity checks for operator and attribute operands.}
5142 @cindex @option{-gnatVo} (@code{gcc})
5143 Arguments for predefined operators and attributes are validity checked.
5144 This includes all operators in package @code{Standard},
5145 the shift operators defined as intrinsic in package @code{Interfaces}
5146 and operands for attributes such as @code{Pos}. Checks are also made
5147 on individual component values for composite comparisons.
5149 @item -gnatVp
5150 @emph{Validity checks for parameters.}
5151 @cindex @option{-gnatVp} (@code{gcc})
5152 This controls the treatment of parameters within a subprogram (as opposed
5153 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5154 of parameters on a call. If either of these call options is used, then
5155 normally an assumption is made within a subprogram that the input arguments
5156 have been validity checking at the point of call, and do not need checking
5157 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5158 is not made, and parameters are not assumed to be valid, so their validity
5159 will be checked (or rechecked) within the subprogram.
5161 @item -gnatVr
5162 @emph{Validity checks for function returns.}
5163 @cindex @option{-gnatVr} (@code{gcc})
5164 The expression in @code{return} statements in functions is validity
5165 checked.
5167 @item -gnatVs
5168 @emph{Validity checks for subscripts.}
5169 @cindex @option{-gnatVs} (@code{gcc})
5170 All subscripts expressions are checked for validity, whether they appear
5171 on the right side or left side (in default mode only left side subscripts
5172 are validity checked).
5174 @item -gnatVt
5175 @emph{Validity checks for tests.}
5176 @cindex @option{-gnatVt} (@code{gcc})
5177 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5178 statements are checked, as well as guard expressions in entry calls.
5180 @end table
5182 @noindent
5183 The @option{-gnatV} switch may be followed by
5184 ^a string of letters^a list of options^
5185 to turn on a series of validity checking options.
5186 For example,
5187 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5188 specifies that in addition to the default validity checking, copies and
5189 function return expressions are to be validity checked.
5190 In order to make it easier
5191 to specify the desired combination of effects,
5192 @ifclear vms
5193 the upper case letters @code{CDFIMORST} may
5194 be used to turn off the corresponding lower case option.
5195 @end ifclear
5196 @ifset vms
5197 the prefix @code{NO} on an option turns off the corresponding validity
5198 checking:
5199 @itemize @bullet
5200 @item @code{NOCOPIES}
5201 @item @code{NODEFAULT}
5202 @item @code{NOFLOATS}
5203 @item @code{NOIN_PARAMS}
5204 @item @code{NOMOD_PARAMS}
5205 @item @code{NOOPERANDS}
5206 @item @code{NORETURNS}
5207 @item @code{NOSUBSCRIPTS}
5208 @item @code{NOTESTS}
5209 @end itemize
5210 @end ifset
5211 Thus
5212 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5213 turns on all validity checking options except for
5214 checking of @code{@b{in out}} procedure arguments.
5216 The specification of additional validity checking generates extra code (and
5217 in the case of @option{-gnatVa} the code expansion can be substantial.
5218 However, these additional checks can be very useful in detecting
5219 uninitialized variables, incorrect use of unchecked conversion, and other
5220 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5221 is useful in conjunction with the extra validity checking, since this
5222 ensures that wherever possible uninitialized variables have invalid values.
5224 See also the pragma @code{Validity_Checks} which allows modification of
5225 the validity checking mode at the program source level, and also allows for
5226 temporary disabling of validity checks.
5228 @node Style Checking
5229 @subsection Style Checking
5230 @findex Style checking
5232 @noindent
5233 The @option{-gnaty^x^(option,option,...)^} switch
5234 @cindex @option{-gnaty} (@code{gcc})
5235 causes the compiler to
5236 enforce specified style rules. A limited set of style rules has been used
5237 in writing the GNAT sources themselves. This switch allows user programs
5238 to activate all or some of these checks. If the source program fails a
5239 specified style check, an appropriate warning message is given, preceded by
5240 the character sequence ``(style)''.
5241 @ifset vms
5242 @code{(option,option,...)} is a sequence of keywords
5243 @end ifset
5244 @ifclear vms
5245 The string @var{x} is a sequence of letters or digits
5246 @end ifclear
5247 indicating the particular style
5248 checks to be performed. The following checks are defined:
5250 @table @option
5251 @c !sort!
5252 @item 1-9
5253 @emph{Specify indentation level.}
5254 If a digit from 1-9 appears
5255 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5256 then proper indentation is checked, with the digit indicating the
5257 indentation level required.
5258 The general style of required indentation is as specified by
5259 the examples in the Ada Reference Manual. Full line comments must be
5260 aligned with the @code{--} starting on a column that is a multiple of
5261 the alignment level.
5263 @item ^a^ATTRIBUTE^
5264 @emph{Check attribute casing.}
5265 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5266 then attribute names, including the case of keywords such as @code{digits}
5267 used as attributes names, must be written in mixed case, that is, the
5268 initial letter and any letter following an underscore must be uppercase.
5269 All other letters must be lowercase.
5271 @item ^b^BLANKS^
5272 @emph{Blanks not allowed at statement end.}
5273 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5274 trailing blanks are not allowed at the end of statements. The purpose of this
5275 rule, together with h (no horizontal tabs), is to enforce a canonical format
5276 for the use of blanks to separate source tokens.
5278 @item ^c^COMMENTS^
5279 @emph{Check comments.}
5280 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5281 then comments must meet the following set of rules:
5283 @itemize @bullet
5285 @item
5286 The ``@code{--}'' that starts the column must either start in column one,
5287 or else at least one blank must precede this sequence.
5289 @item
5290 Comments that follow other tokens on a line must have at least one blank
5291 following the ``@code{--}'' at the start of the comment.
5293 @item
5294 Full line comments must have two blanks following the ``@code{--}'' that
5295 starts the comment, with the following exceptions.
5297 @item
5298 A line consisting only of the ``@code{--}'' characters, possibly preceded
5299 by blanks is permitted.
5301 @item
5302 A comment starting with ``@code{--x}'' where @code{x} is a special character
5303 is permitted.
5304 This allows proper processing of the output generated by specialized tools
5305 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5306 annotation
5307 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5308 special character is defined as being in one of the ASCII ranges
5309 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5310 Note that this usage is not permitted
5311 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5313 @item
5314 A line consisting entirely of minus signs, possibly preceded by blanks, is
5315 permitted. This allows the construction of box comments where lines of minus
5316 signs are used to form the top and bottom of the box.
5318 @item
5319 If a comment starts and ends with ``@code{--}'' is permitted as long as at
5320 least one blank follows the initial ``@code{--}''. Together with the preceding
5321 rule, this allows the construction of box comments, as shown in the following
5322 example:
5323 @smallexample
5324 ---------------------------
5325 -- This is a box comment --
5326 -- with two text lines.  --
5327 ---------------------------
5328 @end smallexample
5329 @end itemize
5331 @item ^e^END^
5332 @emph{Check end/exit labels.}
5333 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5334 optional labels on @code{end} statements ending subprograms and on
5335 @code{exit} statements exiting named loops, are required to be present.
5337 @item ^f^VTABS^
5338 @emph{No form feeds or vertical tabs.}
5339 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5340 neither form feeds nor vertical tab characters are not permitted
5341 in the source text.
5343 @item ^h^HTABS^
5344 @emph{No horizontal tabs.}
5345 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5346 horizontal tab characters are not permitted in the source text.
5347 Together with the b (no blanks at end of line) check, this
5348 enforces a canonical form for the use of blanks to separate
5349 source tokens.
5351 @item ^i^IF_THEN^
5352 @emph{Check if-then layout.}
5353 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5354 then the keyword @code{then} must appear either on the same
5355 line as corresponding @code{if}, or on a line on its own, lined
5356 up under the @code{if} with at least one non-blank line in between
5357 containing all or part of the condition to be tested.
5359 @item ^k^KEYWORD^
5360 @emph{Check keyword casing.}
5361 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5362 all keywords must be in lower case (with the exception of keywords
5363 such as @code{digits} used as attribute names to which this check
5364 does not apply).
5366 @item ^l^LAYOUT^
5367 @emph{Check layout.}
5368 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5369 layout of statement and declaration constructs must follow the
5370 recommendations in the Ada Reference Manual, as indicated by the
5371 form of the syntax rules. For example an @code{else} keyword must
5372 be lined up with the corresponding @code{if} keyword.
5374 There are two respects in which the style rule enforced by this check
5375 option are more liberal than those in the Ada Reference Manual. First
5376 in the case of record declarations, it is permissible to put the
5377 @code{record} keyword on the same line as the @code{type} keyword, and
5378 then the @code{end} in @code{end record} must line up under @code{type}.
5379 For example, either of the following two layouts is acceptable:
5381 @smallexample @c ada
5382 @cartouche
5383 type q is record
5384    a : integer;
5385    b : integer;
5386 end record;
5388 type q is
5389    record
5390       a : integer;
5391       b : integer;
5392    end record;
5393 @end cartouche
5394 @end smallexample
5396 @noindent
5397 Second, in the case of a block statement, a permitted alternative
5398 is to put the block label on the same line as the @code{declare} or
5399 @code{begin} keyword, and then line the @code{end} keyword up under
5400 the block label. For example both the following are permitted:
5402 @smallexample @c ada
5403 @cartouche
5404 Block : declare
5405    A : Integer := 3;
5406 begin
5407    Proc (A, A);
5408 end Block;
5410 Block :
5411    declare
5412       A : Integer := 3;
5413    begin
5414       Proc (A, A);
5415    end Block;
5416 @end cartouche
5417 @end smallexample
5419 @noindent
5420 The same alternative format is allowed for loops. For example, both of
5421 the following are permitted:
5423 @smallexample @c ada
5424 @cartouche
5425 Clear : while J < 10 loop
5426    A (J) := 0;
5427 end loop Clear;
5429 Clear :
5430    while J < 10 loop
5431       A (J) := 0;
5432    end loop Clear;
5433 @end cartouche
5434 @end smallexample
5436 @item ^Lnnn^MAX_NESTING=nnn^
5437 @emph{Set maximum nesting level}
5438 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5439 the range 0-999, appears in the string after @option{-gnaty} then the
5440 maximum level of nesting of constructs (including subprograms, loops,
5441 blocks, packages, and conditionals) may not exceed the given value. A
5442 value of zero disconnects this style check.
5444 @item ^m^LINE_LENGTH^
5445 @emph{Check maximum line length.}
5446 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5447 then the length of source lines must not exceed 79 characters, including
5448 any trailing blanks. The value of 79 allows convenient display on an
5449 80 character wide device or window, allowing for possible special
5450 treatment of 80 character lines. Note that this count is of raw
5451 characters in the source text. This means that a tab character counts
5452 as one character in this count and a wide character sequence counts as
5453 several characters (however many are needed in the encoding).
5455 @item ^Mnnn^MAX_LENGTH=nnn^
5456 @emph{Set maximum line length.}
5457 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5458 the string after @option{-gnaty} then the length of lines must not exceed the
5459 given value.
5461 @item ^n^STANDARD_CASING^
5462 @emph{Check casing of entities in Standard.}
5463 If the ^letter n^word STANDARD_CASING^ appears in the string
5464 after @option{-gnaty} then any identifier from Standard must be cased
5465 to match the presentation in the Ada Reference Manual (for example,
5466 @code{Integer} and @code{ASCII.NUL}).
5468 @item ^o^ORDERED_SUBPROGRAMS^
5469 @emph{Check order of subprogram bodies.}
5470 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5471 after @option{-gnaty} then all subprogram bodies in a given scope
5472 (e.g. a package body) must be in alphabetical order. The ordering
5473 rule uses normal Ada rules for comparing strings, ignoring casing
5474 of letters, except that if there is a trailing numeric suffix, then
5475 the value of this suffix is used in the ordering (e.g. Junk2 comes
5476 before Junk10).
5478 @item ^p^PRAGMA^
5479 @emph{Check pragma casing.}
5480 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5481 pragma names must be written in mixed case, that is, the
5482 initial letter and any letter following an underscore must be uppercase.
5483 All other letters must be lowercase.
5485 @item ^r^REFERENCES^
5486 @emph{Check references.}
5487 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5488 then all identifier references must be cased in the same way as the
5489 corresponding declaration. No specific casing style is imposed on
5490 identifiers. The only requirement is for consistency of references
5491 with declarations.
5493 @item ^s^SPECS^
5494 @emph{Check separate specs.}
5495 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5496 separate declarations (``specs'') are required for subprograms (a
5497 body is not allowed to serve as its own declaration). The only
5498 exception is that parameterless library level procedures are
5499 not required to have a separate declaration. This exception covers
5500 the most frequent form of main program procedures.
5502 @item ^t^TOKEN^
5503 @emph{Check token spacing.}
5504 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5505 the following token spacing rules are enforced:
5507 @itemize @bullet
5509 @item
5510 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5512 @item
5513 The token @code{=>} must be surrounded by spaces.
5515 @item
5516 The token @code{<>} must be preceded by a space or a left parenthesis.
5518 @item
5519 Binary operators other than @code{**} must be surrounded by spaces.
5520 There is no restriction on the layout of the @code{**} binary operator.
5522 @item
5523 Colon must be surrounded by spaces.
5525 @item
5526 Colon-equal (assignment, initialization) must be surrounded by spaces.
5528 @item
5529 Comma must be the first non-blank character on the line, or be
5530 immediately preceded by a non-blank character, and must be followed
5531 by a space.
5533 @item
5534 If the token preceding a left parenthesis ends with a letter or digit, then
5535 a space must separate the two tokens.
5537 @item
5538 A right parenthesis must either be the first non-blank character on
5539 a line, or it must be preceded by a non-blank character.
5541 @item
5542 A semicolon must not be preceded by a space, and must not be followed by
5543 a non-blank character.
5545 @item
5546 A unary plus or minus may not be followed by a space.
5548 @item
5549 A vertical bar must be surrounded by spaces.
5550 @end itemize
5552 @item ^x^XTRA_PARENS^
5553 @emph{Check extra parentheses.}
5554 Check for the use of an unnecessary extra level of parentheses (C-style)
5555 around conditions in @code{if} statements, @code{while} statements and
5556 @code{exit} statements.
5558 @end table
5560 @noindent
5561 In the above rules, appearing in column one is always permitted, that is,
5562 counts as meeting either a requirement for a required preceding space,
5563 or as meeting a requirement for no preceding space.
5565 Appearing at the end of a line is also always permitted, that is, counts
5566 as meeting either a requirement for a following space, or as meeting
5567 a requirement for no following space.
5569 @noindent
5570 If any of these style rules is violated, a message is generated giving
5571 details on the violation. The initial characters of such messages are
5572 always ``@code{(style)}''. Note that these messages are treated as warning
5573 messages, so they normally do not prevent the generation of an object
5574 file. The @option{-gnatwe} switch can be used to treat warning messages,
5575 including style messages, as fatal errors.
5577 The switch
5578 @ifclear vms
5579 @option{-gnaty} on its own (that is not
5580 followed by any letters or digits),
5581 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5582 options enabled with the exception of -gnatyo,
5583 @end ifclear
5584 @ifset vms
5585 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5586 the exception of ORDERED_SUBPROGRAMS,
5587 @end ifset
5588 with an indentation level of 3. This is the standard
5589 checking option that is used for the GNAT sources.
5591 The switch
5592 @ifclear vms
5593 @option{-gnatyN}
5594 @end ifclear
5595 @ifset vms
5596 /STYLE_CHECKS=NONE
5597 @end ifset
5598 clears any previously set style checks.
5600 @node Run-Time Checks
5601 @subsection Run-Time Checks
5602 @cindex Division by zero
5603 @cindex Access before elaboration
5604 @cindex Checks, division by zero
5605 @cindex Checks, access before elaboration
5607 @noindent
5608 If you compile with the default options, GNAT will insert many run-time
5609 checks into the compiled code, including code that performs range
5610 checking against constraints, but not arithmetic overflow checking for
5611 integer operations (including division by zero) or checks for access
5612 before elaboration on subprogram calls. All other run-time checks, as
5613 required by the Ada 95 Reference Manual, are generated by default.
5614 The following @code{gcc} switches refine this default behavior:
5616 @table @option
5617 @c !sort!
5618 @item -gnatp
5619 @cindex @option{-gnatp} (@code{gcc})
5620 @cindex Suppressing checks
5621 @cindex Checks, suppressing
5622 @findex Suppress
5623 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5624 had been present in the source. Validity checks are also suppressed (in
5625 other words @option{-gnatp} also implies @option{-gnatVn}.
5626 Use this switch to improve the performance
5627 of the code at the expense of safety in the presence of invalid data or
5628 program bugs.
5630 @item -gnato
5631 @cindex @option{-gnato} (@code{gcc})
5632 @cindex Overflow checks
5633 @cindex Check, overflow
5634 Enables overflow checking for integer operations.
5635 This causes GNAT to generate slower and larger executable
5636 programs by adding code to check for overflow (resulting in raising
5637 @code{Constraint_Error} as required by standard Ada
5638 semantics). These overflow checks correspond to situations in which
5639 the true value of the result of an operation may be outside the base
5640 range of the result type. The following example shows the distinction:
5642 @smallexample @c ada
5643 X1 : Integer := Integer'Last;
5644 X2 : Integer range 1 .. 5 := 5;
5645 X3 : Integer := Integer'Last;
5646 X4 : Integer range 1 .. 5 := 5;
5647 F  : Float := 2.0E+20;
5649 X1 := X1 + 1;
5650 X2 := X2 + 1;
5651 X3 := Integer (F);
5652 X4 := Integer (F);
5653 @end smallexample
5655 @noindent
5656 Here the first addition results in a value that is outside the base range
5657 of Integer, and hence requires an overflow check for detection of the
5658 constraint error. Thus the first assignment to @code{X1} raises a
5659 @code{Constraint_Error} exception only if @option{-gnato} is set.
5661 The second increment operation results in a violation
5662 of the explicit range constraint, and such range checks are always
5663 performed (unless specifically suppressed with a pragma @code{suppress}
5664 or the use of @option{-gnatp}).
5666 The two conversions of @code{F} both result in values that are outside
5667 the base range of type @code{Integer} and thus will raise
5668 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5669 The fact that the result of the second conversion is assigned to
5670 variable @code{X4} with a restricted range is irrelevant, since the problem
5671 is in the conversion, not the assignment.
5673 Basically the rule is that in the default mode (@option{-gnato} not
5674 used), the generated code assures that all integer variables stay
5675 within their declared ranges, or within the base range if there is
5676 no declared range. This prevents any serious problems like indexes
5677 out of range for array operations.
5679 What is not checked in default mode is an overflow that results in
5680 an in-range, but incorrect value. In the above example, the assignments
5681 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5682 range of the target variable, but the result is wrong in the sense that
5683 it is too large to be represented correctly. Typically the assignment
5684 to @code{X1} will result in wrap around to the largest negative number.
5685 The conversions of @code{F} will result in some @code{Integer} value
5686 and if that integer value is out of the @code{X4} range then the
5687 subsequent assignment would generate an exception.
5689 @findex Machine_Overflows
5690 Note that the @option{-gnato} switch does not affect the code generated
5691 for any floating-point operations; it applies only to integer
5692 semantics).
5693 For floating-point, GNAT has the @code{Machine_Overflows}
5694 attribute set to @code{False} and the normal mode of operation is to
5695 generate IEEE NaN and infinite values on overflow or invalid operations
5696 (such as dividing 0.0 by 0.0).
5698 The reason that we distinguish overflow checking from other kinds of
5699 range constraint checking is that a failure of an overflow check can
5700 generate an incorrect value, but cannot cause erroneous behavior. This
5701 is unlike the situation with a constraint check on an array subscript,
5702 where failure to perform the check can result in random memory description,
5703 or the range check on a case statement, where failure to perform the check
5704 can cause a wild jump.
5706 Note again that @option{-gnato} is off by default, so overflow checking is
5707 not performed in default mode. This means that out of the box, with the
5708 default settings, GNAT does not do all the checks expected from the
5709 language description in the Ada Reference Manual. If you want all constraint
5710 checks to be performed, as described in this Manual, then you must
5711 explicitly use the -gnato switch either on the @code{gnatmake} or
5712 @code{gcc} command.
5714 @item -gnatE
5715 @cindex @option{-gnatE} (@code{gcc})
5716 @cindex Elaboration checks
5717 @cindex Check, elaboration
5718 Enables dynamic checks for access-before-elaboration
5719 on subprogram calls and generic instantiations.
5720 For full details of the effect and use of this switch,
5721 @xref{Compiling Using gcc}.
5722 @end table
5724 @findex Unsuppress
5725 @noindent
5726 The setting of these switches only controls the default setting of the
5727 checks. You may modify them using either @code{Suppress} (to remove
5728 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5729 the program source.
5731 @node Stack Overflow Checking
5732 @subsection Stack Overflow Checking
5733 @cindex Stack Overflow Checking
5734 @cindex -fstack-check
5736 @noindent
5737 For most operating systems, @code{gcc} does not perform stack overflow
5738 checking by default. This means that if the main environment task or
5739 some other task exceeds the available stack space, then unpredictable
5740 behavior will occur.
5742 To activate stack checking, compile all units with the gcc option
5743 @option{-fstack-check}. For example:
5745 @smallexample
5746 gcc -c -fstack-check package1.adb
5747 @end smallexample
5749 @noindent
5750 Units compiled with this option will generate extra instructions to check
5751 that any use of the stack (for procedure calls or for declaring local
5752 variables in declare blocks) do not exceed the available stack space.
5753 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5755 For declared tasks, the stack size is always controlled by the size
5756 given in an applicable @code{Storage_Size} pragma (or is set to
5757 the default size if no pragma is used.
5759 For the environment task, the stack size depends on
5760 system defaults and is unknown to the compiler. The stack
5761 may even dynamically grow on some systems, precluding the
5762 normal Ada semantics for stack overflow. In the worst case,
5763 unbounded stack usage, causes unbounded stack expansion
5764 resulting in the system running out of virtual memory.
5766 The stack checking may still work correctly if a fixed
5767 size stack is allocated, but this cannot be guaranteed.
5768 To ensure that a clean exception is signalled for stack
5769 overflow, set the environment variable
5770 @code{GNAT_STACK_LIMIT} to indicate the maximum
5771 stack area that can be used, as in:
5772 @cindex GNAT_STACK_LIMIT
5774 @smallexample
5775 SET GNAT_STACK_LIMIT 1600
5776 @end smallexample
5778 @noindent
5779 The limit is given in kilobytes, so the above declaration would
5780 set the stack limit of the environment task to 1.6 megabytes.
5781 Note that the only purpose of this usage is to limit the amount
5782 of stack used by the environment task. If it is necessary to
5783 increase the amount of stack for the environment task, then this
5784 is an operating systems issue, and must be addressed with the
5785 appropriate operating systems commands.
5787 @node Using gcc for Syntax Checking
5788 @subsection Using @code{gcc} for Syntax Checking
5789 @table @option
5790 @item -gnats
5791 @cindex @option{-gnats} (@code{gcc})
5792 @ifclear vms
5794 @noindent
5795 The @code{s} stands for ``syntax''.
5796 @end ifclear
5798 Run GNAT in syntax checking only mode. For
5799 example, the command
5801 @smallexample
5802 $ gcc -c -gnats x.adb
5803 @end smallexample
5805 @noindent
5806 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5807 series of files in a single command
5808 @ifclear vms
5809 , and can use wild cards to specify such a group of files.
5810 Note that you must specify the @option{-c} (compile
5811 only) flag in addition to the @option{-gnats} flag.
5812 @end ifclear
5814 You may use other switches in conjunction with @option{-gnats}. In
5815 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5816 format of any generated error messages.
5818 When the source file is empty or contains only empty lines and/or comments,
5819 the output is a warning:
5821 @smallexample
5822 $ gcc -c -gnats -x ada toto.txt
5823 toto.txt:1:01: warning: empty file, contains no compilation units
5825 @end smallexample
5827 Otherwise, the output is simply the error messages, if any. No object file or
5828 ALI file is generated by a syntax-only compilation. Also, no units other
5829 than the one specified are accessed. For example, if a unit @code{X}
5830 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5831 check only mode does not access the source file containing unit
5832 @code{Y}.
5834 @cindex Multiple units, syntax checking
5835 Normally, GNAT allows only a single unit in a source file. However, this
5836 restriction does not apply in syntax-check-only mode, and it is possible
5837 to check a file containing multiple compilation units concatenated
5838 together. This is primarily used by the @code{gnatchop} utility
5839 (@pxref{Renaming Files Using gnatchop}).
5840 @end table
5842 @node Using gcc for Semantic Checking
5843 @subsection Using @code{gcc} for Semantic Checking
5844 @table @option
5845 @item -gnatc
5846 @cindex @option{-gnatc} (@code{gcc})
5848 @ifclear vms
5849 @noindent
5850 The @code{c} stands for ``check''.
5851 @end ifclear
5852 Causes the compiler to operate in semantic check mode,
5853 with full checking for all illegalities specified in the
5854 Ada 95 Reference Manual, but without generation of any object code
5855 (no object file is generated).
5857 Because dependent files must be accessed, you must follow the GNAT
5858 semantic restrictions on file structuring to operate in this mode:
5860 @itemize @bullet
5861 @item
5862 The needed source files must be accessible
5863 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5865 @item
5866 Each file must contain only one compilation unit.
5868 @item
5869 The file name and unit name must match (@pxref{File Naming Rules}).
5870 @end itemize
5872 The output consists of error messages as appropriate. No object file is
5873 generated. An @file{ALI} file is generated for use in the context of
5874 cross-reference tools, but this file is marked as not being suitable
5875 for binding (since no object file is generated).
5876 The checking corresponds exactly to the notion of
5877 legality in the Ada 95 Reference Manual.
5879 Any unit can be compiled in semantics-checking-only mode, including
5880 units that would not normally be compiled (subunits,
5881 and specifications where a separate body is present).
5882 @end table
5884 @node Compiling Ada 83 Programs
5885 @subsection Compiling Ada 83 Programs
5886 @table @option
5887 @cindex Ada 83 compatibility
5888 @item -gnat83
5889 @cindex @option{-gnat83} (@code{gcc})
5890 @cindex ACVC, Ada 83 tests
5892 @noindent
5893 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5894 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5895 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5896 where this can be done easily.
5897 It is not possible to guarantee this switch does a perfect
5898 job; for example, some subtle tests, such as are
5899 found in earlier ACVC tests (and that have been removed from the ACATS suite
5900 for Ada 95), might not compile correctly.
5901 Nevertheless, this switch may be useful in some circumstances, for example
5902 where, due to contractual reasons, legacy code needs to be maintained
5903 using only Ada 83 features.
5905 With few exceptions (most notably the need to use @code{<>} on
5906 @cindex Generic formal parameters
5907 unconstrained generic formal parameters, the use of the new Ada 95
5908 reserved words, and the use of packages
5909 with optional bodies), it is not necessary to use the
5910 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5911 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5912 means that a correct Ada 83 program is usually also a correct Ada 95
5913 program.
5914 For further information, please refer to @ref{Compatibility and Porting Guide}.
5916 @end table
5918 @node Character Set Control
5919 @subsection Character Set Control
5920 @table @option
5921 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
5922 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
5924 @noindent
5925 Normally GNAT recognizes the Latin-1 character set in source program
5926 identifiers, as described in the Ada 95 Reference Manual.
5927 This switch causes
5928 GNAT to recognize alternate character sets in identifiers. @var{c} is a
5929 single character ^^or word^ indicating the character set, as follows:
5931 @table @code
5932 @item 1
5933 ISO 8859-1 (Latin-1) identifiers
5935 @item 2
5936 ISO 8859-2 (Latin-2) letters allowed in identifiers
5938 @item 3
5939 ISO 8859-3 (Latin-3) letters allowed in identifiers
5941 @item 4
5942 ISO 8859-4 (Latin-4) letters allowed in identifiers
5944 @item 5
5945 ISO 8859-5 (Cyrillic) letters allowed in identifiers
5947 @item 9
5948 ISO 8859-15 (Latin-9) letters allowed in identifiers
5950 @item ^p^PC^
5951 IBM PC letters (code page 437) allowed in identifiers
5953 @item ^8^PC850^
5954 IBM PC letters (code page 850) allowed in identifiers
5956 @item ^f^FULL_UPPER^
5957 Full upper-half codes allowed in identifiers
5959 @item ^n^NO_UPPER^
5960 No upper-half codes allowed in identifiers
5962 @item ^w^WIDE^
5963 Wide-character codes (that is, codes greater than 255)
5964 allowed in identifiers
5965 @end table
5967 @xref{Foreign Language Representation}, for full details on the
5968 implementation of these character sets.
5970 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5971 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
5972 Specify the method of encoding for wide characters.
5973 @var{e} is one of the following:
5975 @table @code
5977 @item ^h^HEX^
5978 Hex encoding (brackets coding also recognized)
5980 @item ^u^UPPER^
5981 Upper half encoding (brackets encoding also recognized)
5983 @item ^s^SHIFT_JIS^
5984 Shift/JIS encoding (brackets encoding also recognized)
5986 @item ^e^EUC^
5987 EUC encoding (brackets encoding also recognized)
5989 @item ^8^UTF8^
5990 UTF-8 encoding (brackets encoding also recognized)
5992 @item ^b^BRACKETS^
5993 Brackets encoding only (default value)
5994 @end table
5995 For full details on the these encoding
5996 methods see @xref{Wide Character Encodings}.
5997 Note that brackets coding is always accepted, even if one of the other
5998 options is specified, so for example @option{-gnatW8} specifies that both
5999 brackets and @code{UTF-8} encodings will be recognized. The units that are
6000 with'ed directly or indirectly will be scanned using the specified
6001 representation scheme, and so if one of the non-brackets scheme is
6002 used, it must be used consistently throughout the program. However,
6003 since brackets encoding is always recognized, it may be conveniently
6004 used in standard libraries, allowing these libraries to be used with
6005 any of the available coding schemes.
6006 scheme. If no @option{-gnatW?} parameter is present, then the default
6007 representation is Brackets encoding only.
6009 Note that the wide character representation that is specified (explicitly
6010 or by default) for the main program also acts as the default encoding used
6011 for Wide_Text_IO files if not specifically overridden by a WCEM form
6012 parameter.
6014 @end table
6015 @node File Naming Control
6016 @subsection File Naming Control
6018 @table @option
6019 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6020 @cindex @option{-gnatk} (@code{gcc})
6021 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6022 1-999, indicates the maximum allowable length of a file name (not
6023 including the @file{.ads} or @file{.adb} extension). The default is not
6024 to enable file name krunching.
6026 For the source file naming rules, @xref{File Naming Rules}.
6027 @end table
6029 @node Subprogram Inlining Control
6030 @subsection Subprogram Inlining Control
6032 @table @option
6033 @c !sort!
6034 @item -gnatn
6035 @cindex @option{-gnatn} (@code{gcc})
6036 @ifclear vms
6037 The @code{n} here is intended to suggest the first syllable of the
6038 word ``inline''.
6039 @end ifclear
6040 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6041 inlining to actually occur, optimization must be enabled. To enable
6042 inlining of subprograms specified by pragma @code{Inline},
6043 you must also specify this switch.
6044 In the absence of this switch, GNAT does not attempt
6045 inlining and does not need to access the bodies of
6046 subprograms for which @code{pragma Inline} is specified if they are not
6047 in the current unit.
6049 If you specify this switch the compiler will access these bodies,
6050 creating an extra source dependency for the resulting object file, and
6051 where possible, the call will be inlined.
6052 For further details on when inlining is possible
6053 see @xref{Inlining of Subprograms}.
6055 @item -gnatN
6056 @cindex @option{-gnatN} (@code{gcc})
6057 The front end inlining activated by this switch is generally more extensive,
6058 and quite often more effective than the standard @option{-gnatn} inlining mode.
6059 It will also generate additional dependencies.
6060 Note that
6061 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6062 to specify both options.
6063 @end table
6065 @node Auxiliary Output Control
6066 @subsection Auxiliary Output Control
6068 @table @option
6069 @item -gnatt
6070 @cindex @option{-gnatt} (@code{gcc})
6071 @cindex Writing internal trees
6072 @cindex Internal trees, writing to file
6073 Causes GNAT to write the internal tree for a unit to a file (with the
6074 extension @file{.adt}.
6075 This not normally required, but is used by separate analysis tools.
6076 Typically
6077 these tools do the necessary compilations automatically, so you should
6078 not have to specify this switch in normal operation.
6080 @item -gnatu
6081 @cindex @option{-gnatu} (@code{gcc})
6082 Print a list of units required by this compilation on @file{stdout}.
6083 The listing includes all units on which the unit being compiled depends
6084 either directly or indirectly.
6086 @ifclear vms
6087 @item -pass-exit-codes
6088 @cindex @option{-pass-exit-codes} (@code{gcc})
6089 If this switch is not used, the exit code returned by @code{gcc} when
6090 compiling multiple files indicates whether all source files have
6091 been successfully used to generate object files or not.
6093 When @option{-pass-exit-codes} is used, @code{gcc} exits with an extended
6094 exit status and allows an integrated development environment to better
6095 react to a compilation failure. Those exit status are:
6097 @table @asis
6098 @item 5
6099 There was an error in at least one source file.
6100 @item 3
6101 At least one source file did not generate an object file.
6102 @item 2
6103 The compiler died unexpectedly (internal error for example).
6104 @item 0
6105 An object file has been generated for every source file.
6106 @end table
6107 @end ifclear
6108 @end table
6110 @node Debugging Control
6111 @subsection Debugging Control
6113 @table @option
6114 @c !sort!
6115 @cindex Debugging options
6116 @ifclear vms
6117 @item -gnatd@var{x}
6118 @cindex @option{-gnatd} (@code{gcc})
6119 Activate internal debugging switches. @var{x} is a letter or digit, or
6120 string of letters or digits, which specifies the type of debugging
6121 outputs desired. Normally these are used only for internal development
6122 or system debugging purposes. You can find full documentation for these
6123 switches in the body of the @code{Debug} unit in the compiler source
6124 file @file{debug.adb}.
6125 @end ifclear
6127 @item -gnatG
6128 @cindex @option{-gnatG} (@code{gcc})
6129 This switch causes the compiler to generate auxiliary output containing
6130 a pseudo-source listing of the generated expanded code. Like most Ada
6131 compilers, GNAT works by first transforming the high level Ada code into
6132 lower level constructs. For example, tasking operations are transformed
6133 into calls to the tasking run-time routines. A unique capability of GNAT
6134 is to list this expanded code in a form very close to normal Ada source.
6135 This is very useful in understanding the implications of various Ada
6136 usage on the efficiency of the generated code. There are many cases in
6137 Ada (e.g. the use of controlled types), where simple Ada statements can
6138 generate a lot of run-time code. By using @option{-gnatG} you can identify
6139 these cases, and consider whether it may be desirable to modify the coding
6140 approach to improve efficiency.
6142 The format of the output is very similar to standard Ada source, and is
6143 easily understood by an Ada programmer. The following special syntactic
6144 additions correspond to low level features used in the generated code that
6145 do not have any exact analogies in pure Ada source form. The following
6146 is a partial list of these special constructions. See the specification
6147 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6149 @table @code
6150 @item new @var{xxx} [storage_pool = @var{yyy}]
6151 Shows the storage pool being used for an allocator.
6153 @item at end @var{procedure-name};
6154 Shows the finalization (cleanup) procedure for a scope.
6156 @item (if @var{expr} then @var{expr} else @var{expr})
6157 Conditional expression equivalent to the @code{x?y:z} construction in C.
6159 @item @var{target}^^^(@var{source})
6160 A conversion with floating-point truncation instead of rounding.
6162 @item @var{target}?(@var{source})
6163 A conversion that bypasses normal Ada semantic checking. In particular
6164 enumeration types and fixed-point types are treated simply as integers.
6166 @item @var{target}?^^^(@var{source})
6167 Combines the above two cases.
6169 @item @var{x} #/ @var{y}
6170 @itemx @var{x} #mod @var{y}
6171 @itemx @var{x} #* @var{y}
6172 @itemx @var{x} #rem @var{y}
6173 A division or multiplication of fixed-point values which are treated as
6174 integers without any kind of scaling.
6176 @item free @var{expr} [storage_pool = @var{xxx}]
6177 Shows the storage pool associated with a @code{free} statement.
6179 @item freeze @var{typename} [@var{actions}]
6180 Shows the point at which @var{typename} is frozen, with possible
6181 associated actions to be performed at the freeze point.
6183 @item reference @var{itype}
6184 Reference (and hence definition) to internal type @var{itype}.
6186 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6187 Intrinsic function call.
6189 @item @var{labelname} : label
6190 Declaration of label @var{labelname}.
6192 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6193 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6194 @var{expr}, but handled more efficiently).
6196 @item [constraint_error]
6197 Raise the @code{Constraint_Error} exception.
6199 @item @var{expression}'reference
6200 A pointer to the result of evaluating @var{expression}.
6202 @item @var{target-type}!(@var{source-expression})
6203 An unchecked conversion of @var{source-expression} to @var{target-type}.
6205 @item [@var{numerator}/@var{denominator}]
6206 Used to represent internal real literals (that) have no exact
6207 representation in base 2-16 (for example, the result of compile time
6208 evaluation of the expression 1.0/27.0).
6209 @end table
6211 @item -gnatD
6212 @cindex @option{-gnatD} (@code{gcc})
6213 When used in conjunction with @option{-gnatG}, this switch causes
6214 the expanded source, as described above for
6215 @option{-gnatG} to be written to files with names
6216 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6217 instead of to the standard ooutput file. For
6218 example, if the source file name is @file{hello.adb}, then a file
6219 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6220 information generated by the @code{gcc} @option{^-g^/DEBUG^} switch
6221 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6222 you to do source level debugging using the generated code which is
6223 sometimes useful for complex code, for example to find out exactly
6224 which part of a complex construction raised an exception. This switch
6225 also suppress generation of cross-reference information (see
6226 @option{-gnatx}) since otherwise the cross-reference information
6227 would refer to the @file{^.dg^.DG^} file, which would cause
6228 confusion since this is not the original source file.
6230 Note that @option{-gnatD} actually implies @option{-gnatG}
6231 automatically, so it is not necessary to give both options.
6232 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6234 @ifclear vms
6235 @item -gnatR[0|1|2|3[s]]
6236 @cindex @option{-gnatR} (@code{gcc})
6237 This switch controls output from the compiler of a listing showing
6238 representation information for declared types and objects. For
6239 @option{-gnatR0}, no information is output (equivalent to omitting
6240 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6241 so @option{-gnatR} with no parameter has the same effect), size and alignment
6242 information is listed for declared array and record types. For
6243 @option{-gnatR2}, size and alignment information is listed for all
6244 expression information for values that are computed at run time for
6245 variant records. These symbolic expressions have a mostly obvious
6246 format with #n being used to represent the value of the n'th
6247 discriminant. See source files @file{repinfo.ads/adb} in the
6248 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6249 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6250 the output is to a file with the name @file{^file.rep^file_REP^} where
6251 file is the name of the corresponding source file.
6252 @end ifclear
6253 @ifset vms
6254 @item /REPRESENTATION_INFO
6255 @cindex @option{/REPRESENTATION_INFO} (@code{gcc})
6256 This qualifier controls output from the compiler of a listing showing
6257 representation information for declared types and objects. For
6258 @option{/REPRESENTATION_INFO=NONE}, no information is output
6259 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6260 @option{/REPRESENTATION_INFO} without option is equivalent to
6261 @option{/REPRESENTATION_INFO=ARRAYS}.
6262 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6263 information is listed for declared array and record types. For
6264 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6265 is listed for all expression information for values that are computed
6266 at run time for variant records. These symbolic expressions have a mostly
6267 obvious format with #n being used to represent the value of the n'th
6268 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6269 @code{GNAT} sources for full details on the format of
6270 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6271 If _FILE is added at the end of an option
6272 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6273 then the output is to a file with the name @file{file_REP} where
6274 file is the name of the corresponding source file.
6275 @end ifset
6277 @item -gnatS
6278 @cindex @option{-gnatS} (@code{gcc})
6279 The use of the switch @option{-gnatS} for an
6280 Ada compilation will cause the compiler to output a
6281 representation of package Standard in a form very
6282 close to standard Ada. It is not quite possible to
6283 do this entirely in standard Ada (since new
6284 numeric base types cannot be created in standard
6285 Ada), but the output is easily
6286 readable to any Ada programmer, and is useful to
6287 determine the characteristics of target dependent
6288 types in package Standard.
6290 @item -gnatx
6291 @cindex @option{-gnatx} (@code{gcc})
6292 Normally the compiler generates full cross-referencing information in
6293 the @file{ALI} file. This information is used by a number of tools,
6294 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6295 suppresses this information. This saves some space and may slightly
6296 speed up compilation, but means that these tools cannot be used.
6297 @end table
6299 @node Exception Handling Control
6300 @subsection Exception Handling Control
6302 @noindent
6303 GNAT uses two methods for handling exceptions at run-time. The
6304 @code{longjmp/setjmp} method saves the context when entering
6305 a frame with an exception handler. Then when an exception is
6306 raised, the context can be restored immediately, without the
6307 need for tracing stack frames. This method provides very fast
6308 exception propagation, but introduces significant overhead for
6309 the use of exception handlers, even if no exception is raised.
6311 The other approach is called ``zero cost'' exception handling.
6312 With this method, the compiler builds static tables to describe
6313 the exception ranges. No dynamic code is required when entering
6314 a frame containing an exception handler. When an exception is
6315 raised, the tables are used to control a back trace of the
6316 subprogram invocation stack to locate the required exception
6317 handler. This method has considerably poorer performance for
6318 the propagation of exceptions, but there is no overhead for
6319 exception handlers if no exception is raised.
6321 The following switches can be used to control which of the
6322 two exception handling methods is used.
6324 @table @option
6325 @c !sort!
6327 @item -gnatL
6328 @cindex @option{-gnatL} (@code{gcc})
6329 This switch causes the longjmp/setjmp approach to be used
6330 for exception handling. If this is the default mechanism for the
6331 target (see below), then this has no effect. If the default
6332 mechanism for the target is zero cost exceptions, then
6333 this switch can be used to modify this default, but it must be
6334 used for all units in the partition, including all run-time
6335 library units. One way to achieve this is to use the
6336 @option{-a} and @option{-f} switches for @code{gnatmake}.
6337 This option is rarely used. One case in which it may be
6338 advantageous is if you have an application where exception
6339 raising is common and the overall performance of the
6340 application is improved by favoring exception propagation.
6342 @item -gnatZ
6343 @cindex @option{-gnatZ} (@code{gcc})
6344 @cindex Zero Cost Exceptions
6345 This switch causes the zero cost approach to be sed
6346 for exception handling. If this is the default mechanism for the
6347 target (see below), then this has no effect. If the default
6348 mechanism for the target is longjmp/setjmp exceptions, then
6349 this switch can be used to modify this default, but it must be
6350 used for all units in the partition, including all run-time
6351 library units. One way to achieve this is to use the
6352 @option{-a} and @option{-f} switches for @code{gnatmake}.
6353 This option can only be used if the zero cost approach
6354 is available for the target in use (see below).
6355 @end table
6357 @noindent
6358 The @code{longjmp/setjmp} approach is available on all targets, but
6359 the @code{zero cost} approach is only available on selected targets.
6360 To determine whether zero cost exceptions can be used for a
6361 particular target, look at the private part of the file system.ads.
6362 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6363 be True to use the zero cost approach. If both of these switches
6364 are set to False, this means that zero cost exception handling
6365 is not yet available for that target. The switch
6366 @code{ZCX_By_Default} indicates the default approach. If this
6367 switch is set to True, then the @code{zero cost} approach is
6368 used by default.
6370 @node Units to Sources Mapping Files
6371 @subsection Units to Sources Mapping Files
6373 @table @option
6375 @item -gnatem^^=^@var{path}
6376 @cindex @option{-gnatem} (@code{gcc})
6377 A mapping file is a way to communicate to the compiler two mappings:
6378 from unit names to file names (without any directory information) and from
6379 file names to path names (with full directory information). These mappings
6380 are used by the compiler to short-circuit the path search.
6382 The use of mapping files is not required for correct operation of the
6383 compiler, but mapping files can improve efficiency, particularly when
6384 sources are read over a slow network connection. In normal operation,
6385 you need not be concerned with the format or use of mapping files,
6386 and the @option{-gnatem} switch is not a switch that you would use
6387 explicitly. it is intended only for use by automatic tools such as
6388 @code{gnatmake} running under the project file facility. The
6389 description here of the format of mapping files is provided
6390 for completeness and for possible use by other tools.
6392 A mapping file is a sequence of sets of three lines. In each set,
6393 the first line is the unit name, in lower case, with ``@code{%s}''
6394 appended for
6395 specifications and ``@code{%b}'' appended for bodies; the second line is the
6396 file name; and the third line is the path name.
6398 Example:
6399 @smallexample
6400    main%b
6401    main.2.ada
6402    /gnat/project1/sources/main.2.ada
6403 @end smallexample
6405 When the switch @option{-gnatem} is specified, the compiler will create
6406 in memory the two mappings from the specified file. If there is any problem
6407 (non existent file, truncated file or duplicate entries), no mapping
6408 will be created.
6410 Several @option{-gnatem} switches may be specified; however, only the last
6411 one on the command line will be taken into account.
6413 When using a project file, @code{gnatmake} create a temporary mapping file
6414 and communicates it to the compiler using this switch.
6416 @end table
6418 @node Integrated Preprocessing
6419 @subsection Integrated Preprocessing
6421 @noindent
6422 GNAT sources may be preprocessed immediately before compilation; the actual
6423 text of the source is not the text of the source file, but is derived from it
6424 through a process called preprocessing. Integrated preprocessing is specified
6425 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6426 indicates, through a text file, the preprocessing data to be used.
6427 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6429 @noindent
6430 It is recommended that @code{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6431 used when Integrated Preprocessing is used. The reason is that preprocessing
6432 with another Preprocessing Data file without changing the sources will
6433 not trigger recompilation without this switch.
6435 @noindent
6436 Note that @code{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6437 always trigger recompilation for sources that are preprocessed,
6438 because @code{gnatmake} cannot compute the checksum of the source after
6439 preprocessing.
6441 @noindent
6442 The actual preprocessing function is described in details in section
6443 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6444 preprocessing is triggered and parameterized.
6446 @table @code
6448 @item -gnatep=@var{file}
6449 @cindex @option{-gnatep} (@code{gcc})
6450 This switch indicates to the compiler the file name (without directory
6451 information) of the preprocessor data file to use. The preprocessor data file
6452 should be found in the source directories.
6454 @noindent
6455 A preprocessing data file is a text file with significant lines indicating
6456 how should be preprocessed either a specific source or all sources not
6457 mentioned in other lines. A significant line is a non empty, non comment line.
6458 Comments are similar to Ada comments.
6460 @noindent
6461 Each significant line starts with either a literal string or the character '*'.
6462 A literal string is the file name (without directory information) of the source
6463 to preprocess. A character '*' indicates the preprocessing for all the sources
6464 that are not specified explicitly on other lines (order of the lines is not
6465 significant). It is an error to have two lines with the same file name or two
6466 lines starting with the character '*'.
6468 @noindent
6469 After the file name or the character '*', another optional literal string
6470 indicating the file name of the definition file to be used for preprocessing.
6471 (see @ref{Form of Definitions File}. The definition files are found by the
6472 compiler in one of the source directories. In some cases, when compiling
6473 a source in a directory other than the current directory, if the definition
6474 file is in the current directory, it may be necessary to add the current
6475 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6476 the compiler would not find the definition file.
6478 @noindent
6479 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6480 be found. Those ^switches^switches^ are:
6482 @table @code
6484 @item -b
6485 Causes both preprocessor lines and the lines deleted by
6486 preprocessing to be replaced by blank lines, preserving the line number.
6487 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6488 it cancels the effect of @option{-c}.
6490 @item -c
6491 Causes both preprocessor lines and the lines deleted
6492 by preprocessing to be retained as comments marked
6493 with the special string ``@code{--! }''.
6495 @item -Dsymbol=value
6496 Define or redefine a symbol, associated with value. A symbol is an Ada
6497 identifier, or an Ada reserved word, with the exception of @code{if},
6498 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6499 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6500 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6501 same name defined in a definition file.
6503 @item -s
6504 Causes a sorted list of symbol names and values to be
6505 listed on the standard output file.
6507 @item -u
6508 Causes undefined symbols to be treated as having the value @code{FALSE}
6509 in the context
6510 of a preprocessor test. In the absence of this option, an undefined symbol in
6511 a @code{#if} or @code{#elsif} test will be treated as an error.
6513 @end table
6515 @noindent
6516 Examples of valid lines in a preprocessor data file:
6518 @smallexample
6519   "toto.adb"  "prep.def" -u
6520   --  preprocess "toto.adb", using definition file "prep.def",
6521   --  undefined symbol are False.
6523   * -c -DVERSION=V101
6524   --  preprocess all other sources without a definition file;
6525   --  suppressed lined are commented; symbol VERSION has the value V101.
6527   "titi.adb" "prep2.def" -s
6528   --  preprocess "titi.adb", using definition file "prep2.def";
6529   --  list all symbols with their values.
6530 @end smallexample
6532 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6533 @cindex @option{-gnateD} (@code{gcc})
6534 Define or redefine a preprocessing symbol, associated with value. If no value
6535 is given on the command line, then the value of the symbol is @code{True}.
6536 A symbol is an identifier, following normal Ada (case-insensitive)
6537 rules for its syntax, and value is any sequence (including an empty sequence)
6538 of characters from the set (letters, digits, period, underline).
6539 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6540 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6542 @noindent
6543 A symbol declared with this ^switch^switch^ on the command line replaces a
6544 symbol with the same name either in a definition file or specified with a
6545 ^switch^switch^ -D in the preprocessor data file.
6547 @noindent
6548 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6550 @end table
6552 @node Code Generation Control
6553 @subsection Code Generation Control
6555 @noindent
6557 The GCC technology provides a wide range of target dependent
6558 @option{-m} switches for controlling
6559 details of code generation with respect to different versions of
6560 architectures. This includes variations in instruction sets (e.g.
6561 different members of the power pc family), and different requirements
6562 for optimal arrangement of instructions (e.g. different members of
6563 the x86 family). The list of available @option{-m} switches may be
6564 found in the GCC documentation.
6566 Use of the these @option{-m} switches may in some cases result in improved
6567 code performance.
6569 The GNAT Pro technology is tested and qualified without any
6570 @option{-m} switches,
6571 so generally the most reliable approach is to avoid the use of these
6572 switches. However, we generally expect most of these switches to work
6573 successfully with GNAT Pro, and many customers have reported successful
6574 use of these options.
6576 Our general advice is to avoid the use of @option{-m} switches unless
6577 special needs lead to requirements in this area. In particular,
6578 there is no point in using @option{-m} switches to improve performance
6579 unless you actually see a performance improvement.
6581 @ifset vms
6582 @node Return Codes
6583 @subsection Return Codes
6584 @cindex Return Codes
6585 @cindex @option{/RETURN_CODES=VMS}
6587 @noindent
6588 On VMS, GNAT compiled programs return POSIX-style codes by default,
6589 e.g. @option{/RETURN_CODES=POSIX}.
6591 To enable VMS style return codes, GNAT LINK with the option
6592 @option{/RETURN_CODES=VMS}. For example:
6594 @smallexample
6595 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6596 @end smallexample
6598 @noindent
6599 Programs built with /RETURN_CODES=VMS are suitable to be called in
6600 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6601 are suitable for spawning with appropriate GNAT RTL routines.
6603 @end ifset
6605 @node Search Paths and the Run-Time Library (RTL)
6606 @section Search Paths and the Run-Time Library (RTL)
6608 @noindent
6609 With the GNAT source-based library system, the compiler must be able to
6610 find source files for units that are needed by the unit being compiled.
6611 Search paths are used to guide this process.
6613 The compiler compiles one source file whose name must be given
6614 explicitly on the command line. In other words, no searching is done
6615 for this file. To find all other source files that are needed (the most
6616 common being the specs of units), the compiler examines the following
6617 directories, in the following order:
6619 @enumerate
6620 @item
6621 The directory containing the source file of the main unit being compiled
6622 (the file name on the command line).
6624 @item
6625 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6626 @code{gcc} command line, in the order given.
6628 @item
6629 @findex ADA_INCLUDE_PATH
6630 Each of the directories listed in the value of the
6631 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6632 @ifclear vms
6633 Construct this value
6634 exactly as the @code{PATH} environment variable: a list of directory
6635 names separated by colons (semicolons when working with the NT version).
6636 @end ifclear
6637 @ifset vms
6638 Normally, define this value as a logical name containing a comma separated
6639 list of directory names.
6641 This variable can also be defined by means of an environment string
6642 (an argument to the DEC C exec* set of functions).
6644 Logical Name:
6645 @smallexample
6646 DEFINE ANOTHER_PATH FOO:[BAG]
6647 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6648 @end smallexample
6650 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6651 first, followed by the standard Ada 95
6652 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6653 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6654 (Text_IO, Sequential_IO, etc)
6655 instead of the Ada95 packages. Thus, in order to get the Ada 95
6656 packages by default, ADA_INCLUDE_PATH must be redefined.
6657 @end ifset
6659 @item
6660 @findex ADA_PRJ_INCLUDE_FILE
6661 Each of the directories listed in the text file whose name is given
6662 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6664 @noindent
6665 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6666 driver when project files are used. It should not normally be set
6667 by other means.
6669 @item
6670 The content of the @file{ada_source_path} file which is part of the GNAT
6671 installation tree and is used to store standard libraries such as the
6672 GNAT Run Time Library (RTL) source files.
6673 @ifclear vms
6674 @ref{Installing a library}
6675 @end ifclear
6676 @end enumerate
6678 @noindent
6679 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6680 inhibits the use of the directory
6681 containing the source file named in the command line. You can still
6682 have this directory on your search path, but in this case it must be
6683 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6685 Specifying the switch @option{-nostdinc}
6686 inhibits the search of the default location for the GNAT Run Time
6687 Library (RTL) source files.
6689 The compiler outputs its object files and ALI files in the current
6690 working directory.
6691 @ifclear vms
6692 Caution: The object file can be redirected with the @option{-o} switch;
6693 however, @code{gcc} and @code{gnat1} have not been coordinated on this
6694 so the @file{ALI} file will not go to the right place. Therefore, you should
6695 avoid using the @option{-o} switch.
6696 @end ifclear
6698 @findex System.IO
6699 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6700 children make up the GNAT RTL, together with the simple @code{System.IO}
6701 package used in the @code{"Hello World"} example. The sources for these units
6702 are needed by the compiler and are kept together in one directory. Not
6703 all of the bodies are needed, but all of the sources are kept together
6704 anyway. In a normal installation, you need not specify these directory
6705 names when compiling or binding. Either the environment variables or
6706 the built-in defaults cause these files to be found.
6708 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6709 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6710 consisting of child units of @code{GNAT}. This is a collection of generally
6711 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6712 further details.
6714 Besides simplifying access to the RTL, a major use of search paths is
6715 in compiling sources from multiple directories. This can make
6716 development environments much more flexible.
6718 @node Order of Compilation Issues
6719 @section Order of Compilation Issues
6721 @noindent
6722 If, in our earlier example, there was a spec for the @code{hello}
6723 procedure, it would be contained in the file @file{hello.ads}; yet this
6724 file would not have to be explicitly compiled. This is the result of the
6725 model we chose to implement library management. Some of the consequences
6726 of this model are as follows:
6728 @itemize @bullet
6729 @item
6730 There is no point in compiling specs (except for package
6731 specs with no bodies) because these are compiled as needed by clients. If
6732 you attempt a useless compilation, you will receive an error message.
6733 It is also useless to compile subunits because they are compiled as needed
6734 by the parent.
6736 @item
6737 There are no order of compilation requirements: performing a
6738 compilation never obsoletes anything. The only way you can obsolete
6739 something and require recompilations is to modify one of the
6740 source files on which it depends.
6742 @item
6743 There is no library as such, apart from the ALI files
6744 (@pxref{The Ada Library Information Files}, for information on the format
6745 of these files). For now we find it convenient to create separate ALI files,
6746 but eventually the information therein may be incorporated into the object
6747 file directly.
6749 @item
6750 When you compile a unit, the source files for the specs of all units
6751 that it @code{with}'s, all its subunits, and the bodies of any generics it
6752 instantiates must be available (reachable by the search-paths mechanism
6753 described above), or you will receive a fatal error message.
6754 @end itemize
6756 @node Examples
6757 @section Examples
6759 @noindent
6760 The following are some typical Ada compilation command line examples:
6762 @table @code
6763 @item $ gcc -c xyz.adb
6764 Compile body in file @file{xyz.adb} with all default options.
6766 @ifclear vms
6767 @item $ gcc -c -O2 -gnata xyz-def.adb
6768 @end ifclear
6769 @ifset vms
6770 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6771 @end ifset
6773 Compile the child unit package in file @file{xyz-def.adb} with extensive
6774 optimizations, and pragma @code{Assert}/@code{Debug} statements
6775 enabled.
6777 @item $ gcc -c -gnatc abc-def.adb
6778 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6779 mode.
6780 @end table
6782 @node Binding Using gnatbind
6783 @chapter Binding Using @code{gnatbind}
6784 @findex gnatbind
6786 @menu
6787 * Running gnatbind::
6788 * Switches for gnatbind::
6789 * Command-Line Access::
6790 * Search Paths for gnatbind::
6791 * Examples of gnatbind Usage::
6792 @end menu
6794 @noindent
6795 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6796 to bind compiled GNAT objects. The @code{gnatbind} program performs
6797 four separate functions:
6799 @enumerate
6800 @item
6801 Checks that a program is consistent, in accordance with the rules in
6802 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6803 messages are generated if a program uses inconsistent versions of a
6804 given unit.
6806 @item
6807 Checks that an acceptable order of elaboration exists for the program
6808 and issues an error message if it cannot find an order of elaboration
6809 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6811 @item
6812 Generates a main program incorporating the given elaboration order.
6813 This program is a small Ada package (body and spec) that
6814 must be subsequently compiled
6815 using the GNAT compiler. The necessary compilation step is usually
6816 performed automatically by @code{gnatlink}. The two most important
6817 functions of this program
6818 are to call the elaboration routines of units in an appropriate order
6819 and to call the main program.
6821 @item
6822 Determines the set of object files required by the given main program.
6823 This information is output in the forms of comments in the generated program,
6824 to be read by the @code{gnatlink} utility used to link the Ada application.
6825 @end enumerate
6827 @node Running gnatbind
6828 @section Running @code{gnatbind}
6830 @noindent
6831 The form of the @code{gnatbind} command is
6833 @smallexample
6834 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6835 @end smallexample
6837 @noindent
6838 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6839 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6840 package in two files whose names are
6841 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6842 For example, if given the
6843 parameter @file{hello.ali}, for a main program contained in file
6844 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6845 and @file{b~hello.adb}.
6847 When doing consistency checking, the binder takes into consideration
6848 any source files it can locate. For example, if the binder determines
6849 that the given main program requires the package @code{Pack}, whose
6850 @file{.ALI}
6851 file is @file{pack.ali} and whose corresponding source spec file is
6852 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6853 (using the same search path conventions as previously described for the
6854 @code{gcc} command). If it can locate this source file, it checks that
6855 the time stamps
6856 or source checksums of the source and its references to in @file{ALI} files
6857 match. In other words, any @file{ALI} files that mentions this spec must have
6858 resulted from compiling this version of the source file (or in the case
6859 where the source checksums match, a version close enough that the
6860 difference does not matter).
6862 @cindex Source files, use by binder
6863 The effect of this consistency checking, which includes source files, is
6864 that the binder ensures that the program is consistent with the latest
6865 version of the source files that can be located at bind time. Editing a
6866 source file without compiling files that depend on the source file cause
6867 error messages to be generated by the binder.
6869 For example, suppose you have a main program @file{hello.adb} and a
6870 package @code{P}, from file @file{p.ads} and you perform the following
6871 steps:
6873 @enumerate
6874 @item
6875 Enter @code{gcc -c hello.adb} to compile the main program.
6877 @item
6878 Enter @code{gcc -c p.ads} to compile package @code{P}.
6880 @item
6881 Edit file @file{p.ads}.
6883 @item
6884 Enter @code{gnatbind hello}.
6885 @end enumerate
6887 @noindent
6888 At this point, the file @file{p.ali} contains an out-of-date time stamp
6889 because the file @file{p.ads} has been edited. The attempt at binding
6890 fails, and the binder generates the following error messages:
6892 @smallexample
6893 error: "hello.adb" must be recompiled ("p.ads" has been modified)
6894 error: "p.ads" has been modified and must be recompiled
6895 @end smallexample
6897 @noindent
6898 Now both files must be recompiled as indicated, and then the bind can
6899 succeed, generating a main program. You need not normally be concerned
6900 with the contents of this file, but for reference purposes a sample
6901 binder output file is given in @ref{Example of Binder Output File}.
6903 In most normal usage, the default mode of @command{gnatbind} which is to
6904 generate the main package in Ada, as described in the previous section.
6905 In particular, this means that any Ada programmer can read and understand
6906 the generated main program. It can also be debugged just like any other
6907 Ada code provided the @option{^-g^/DEBUG^} switch is used for
6908 @command{gnatbind} and @command{gnatlink}.
6910 However for some purposes it may be convenient to generate the main
6911 program in C rather than Ada. This may for example be helpful when you
6912 are generating a mixed language program with the main program in C. The
6913 GNAT compiler itself is an example.
6914 The use of the @option{^-C^/BIND_FILE=C^} switch
6915 for both @code{gnatbind} and @code{gnatlink} will cause the program to
6916 be generated in C (and compiled using the gnu C compiler).
6918 @node Switches for gnatbind
6919 @section Switches for @command{gnatbind}
6921 @noindent
6922 The following switches are available with @code{gnatbind}; details will
6923 be presented in subsequent sections.
6925 @menu
6926 * Consistency-Checking Modes::
6927 * Binder Error Message Control::
6928 * Elaboration Control::
6929 * Output Control::
6930 * Binding with Non-Ada Main Programs::
6931 * Binding Programs with No Main Subprogram::
6932 @end menu
6934 @table @option
6935 @c !sort!
6936 @item ^-aO^/OBJECT_SEARCH^
6937 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
6938 Specify directory to be searched for ALI files.
6940 @item ^-aI^/SOURCE_SEARCH^
6941 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
6942 Specify directory to be searched for source file.
6944 @item ^-A^/BIND_FILE=ADA^
6945 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
6946 Generate binder program in Ada (default)
6948 @item ^-b^/REPORT_ERRORS=BRIEF^
6949 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
6950 Generate brief messages to @file{stderr} even if verbose mode set.
6952 @item ^-c^/NOOUTPUT^
6953 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
6954 Check only, no generation of binder output file.
6956 @item ^-C^/BIND_FILE=C^
6957 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
6958 Generate binder program in C
6960 @item ^-e^/ELABORATION_DEPENDENCIES^
6961 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
6962 Output complete list of elaboration-order dependencies.
6964 @item ^-E^/STORE_TRACEBACKS^
6965 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
6966 Store tracebacks in exception occurrences when the target supports it.
6967 This is the default with the zero cost exception mechanism.
6968 @ignore
6969 @c The following may get moved to an appendix
6970 This option is currently supported on the following targets:
6971 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6972 @end ignore
6973 See also the packages @code{GNAT.Traceback} and
6974 @code{GNAT.Traceback.Symbolic} for more information.
6975 @ifclear vms
6976 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
6977 @code{gcc} option.
6978 @end ifclear
6980 @item ^-F^/FORCE_ELABS_FLAGS^
6981 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
6982 Force the checks of elaboration flags. @command{gnatbind} does not normally
6983 generate checks of elaboration flags for the main executable, except when
6984 a Stand-Alone Library is used. However, there are cases when this cannot be
6985 detected by gnatbind. An example is importing an interface of a Stand-Alone
6986 Library through a pragma Import and only specifying through a linker switch
6987 this Stand-Alone Library. This switch is used to guarantee that elaboration
6988 flag checks are generated.
6990 @item ^-h^/HELP^
6991 @cindex @option{^-h^/HELP^} (@command{gnatbind})
6992 Output usage (help) information
6994 @item ^-I^/SEARCH^
6995 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
6996 Specify directory to be searched for source and ALI files.
6998 @item ^-I-^/NOCURRENT_DIRECTORY^
6999 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7000 Do not look for sources in the current directory where @code{gnatbind} was
7001 invoked, and do not look for ALI files in the directory containing the
7002 ALI file named in the @code{gnatbind} command line.
7004 @item ^-l^/ORDER_OF_ELABORATION^
7005 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7006 Output chosen elaboration order.
7008 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7009 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7010 Binds the units for library building. In this case the adainit and
7011 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
7012 are renamed to ^xxxinit^XXXINIT^ and
7013 ^xxxfinal^XXXFINAL^.
7014 Implies ^-n^/NOCOMPILE^.
7015 @ifclear vms
7016 (@pxref{GNAT and Libraries}, for more details.)
7017 @end ifclear
7018 @ifset vms
7019 On OpenVMS, these init and final procedures are exported in uppercase
7020 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7021 the init procedure will be "TOTOINIT" and the exported name of the final
7022 procedure will be "TOTOFINAL".
7023 @end ifset
7025 @item ^-Mxyz^/RENAME_MAIN=xyz^
7026 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7027 Rename generated main program from main to xyz
7029 @item ^-m^/ERROR_LIMIT=^@var{n}
7030 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7031 Limit number of detected errors to @var{n}, where @var{n} is
7032 in the range 1..999_999. The default value if no switch is
7033 given is 9999. Binding is terminated if the limit is exceeded.
7034 @ifset unw
7035 Furthermore, under Windows, the sources pointed to by the libraries path
7036 set in the registry are not searched for.
7037 @end ifset
7039 @item ^-n^/NOMAIN^
7040 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7041 No main program.
7043 @item -nostdinc
7044 @cindex @option{-nostdinc} (@command{gnatbind})
7045 Do not look for sources in the system default directory.
7047 @item -nostdlib
7048 @cindex @option{-nostdlib} (@command{gnatbind})
7049 Do not look for library files in the system default directory.
7051 @item --RTS=@var{rts-path}
7052 @cindex @option{--RTS} (@code{gnatbind})
7053 Specifies the default location of the runtime library. Same meaning as the
7054 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
7056 @item ^-o ^/OUTPUT=^@var{file}
7057 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7058 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7059 Note that if this option is used, then linking must be done manually,
7060 gnatlink cannot be used.
7062 @item ^-O^/OBJECT_LIST^
7063 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7064 Output object list.
7066 @item ^-p^/PESSIMISTIC_ELABORATION^
7067 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7068 Pessimistic (worst-case) elaboration order
7070 @item ^-s^/READ_SOURCES=ALL^
7071 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7072 Require all source files to be present.
7074 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7075 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7076 Specifies the value to be used when detecting uninitialized scalar
7077 objects with pragma Initialize_Scalars.
7078 The @var{xxx} ^string specified with the switch^option^ may be either
7079 @itemize @bullet
7080 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7081 @item ``@option{^lo^LOW^}'' for the lowest possible value
7082 possible, and the low
7083 @item ``@option{^hi^HIGH^}'' for the highest possible value
7084 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7085 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7086 @end itemize
7088 In addition, you can specify @option{-Sev} to indicate that the value is
7089 to be set at run time. In this case, the program will look for an environment
7090 @cindex GNAT_INIT_SCALARS
7091 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7092 of @option{in/lo/hi/xx} with the same meanings as above.
7093 If no environment variable is found, or if it does not have a valid value,
7094 then the default is @option{in} (invalid values).
7096 @ifclear vms
7097 @item -static
7098 @cindex @option{-static} (@code{gnatbind})
7099 Link against a static GNAT run time.
7101 @item -shared
7102 @cindex @option{-shared} (@code{gnatbind})
7103 Link against a shared GNAT run time when available.
7104 @end ifclear
7106 @item ^-t^/NOTIME_STAMP_CHECK^
7107 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7108 Tolerate time stamp and other consistency errors
7110 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7111 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7112 Set the time slice value to @var{n} milliseconds. If the system supports
7113 the specification of a specific time slice value, then the indicated value
7114 is used. If the system does not support specific time slice values, but
7115 does support some general notion of round-robin scheduling, then any
7116 non-zero value will activate round-robin scheduling.
7118 A value of zero is treated specially. It turns off time
7119 slicing, and in addition, indicates to the tasking run time that the
7120 semantics should match as closely as possible the Annex D
7121 requirements of the Ada RM, and in particular sets the default
7122 scheduling policy to @code{FIFO_Within_Priorities}.
7124 @item ^-v^/REPORT_ERRORS=VERBOSE^
7125 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7126 Verbose mode. Write error messages, header, summary output to
7127 @file{stdout}.
7129 @ifclear vms
7130 @item -w@var{x}
7131 @cindex @option{-w} (@code{gnatbind})
7132 Warning mode (@var{x}=s/e for suppress/treat as error)
7133 @end ifclear
7135 @ifset vms
7136 @item /WARNINGS=NORMAL
7137 @cindex @option{/WARNINGS} (@code{gnatbind})
7138 Normal warnings mode. Warnings are issued but ignored
7140 @item /WARNINGS=SUPPRESS
7141 @cindex @option{/WARNINGS} (@code{gnatbind})
7142 All warning messages are suppressed
7144 @item /WARNINGS=ERROR
7145 @cindex @option{/WARNINGS} (@code{gnatbind})
7146 Warning messages are treated as fatal errors
7147 @end ifset
7149 @item ^-x^/READ_SOURCES=NONE^
7150 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7151 Exclude source files (check object consistency only).
7153 @ifset vms
7154 @item /READ_SOURCES=AVAILABLE
7155 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7156 Default mode, in which sources are checked for consistency only if
7157 they are available.
7158 @end ifset
7160 @item ^-z^/ZERO_MAIN^
7161 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7162 No main subprogram.
7163 @end table
7165 @ifclear vms
7166 @noindent
7167 You may obtain this listing of switches by running @code{gnatbind} with
7168 no arguments.
7169 @end ifclear
7171 @node Consistency-Checking Modes
7172 @subsection Consistency-Checking Modes
7174 @noindent
7175 As described earlier, by default @code{gnatbind} checks
7176 that object files are consistent with one another and are consistent
7177 with any source files it can locate. The following switches control binder
7178 access to sources.
7180 @table @option
7181 @c !sort!
7182 @item ^-s^/READ_SOURCES=ALL^
7183 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7184 Require source files to be present. In this mode, the binder must be
7185 able to locate all source files that are referenced, in order to check
7186 their consistency. In normal mode, if a source file cannot be located it
7187 is simply ignored. If you specify this switch, a missing source
7188 file is an error.
7190 @item ^-x^/READ_SOURCES=NONE^
7191 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7192 Exclude source files. In this mode, the binder only checks that ALI
7193 files are consistent with one another. Source files are not accessed.
7194 The binder runs faster in this mode, and there is still a guarantee that
7195 the resulting program is self-consistent.
7196 If a source file has been edited since it was last compiled, and you
7197 specify this switch, the binder will not detect that the object
7198 file is out of date with respect to the source file. Note that this is the
7199 mode that is automatically used by @code{gnatmake} because in this
7200 case the checking against sources has already been performed by
7201 @code{gnatmake} in the course of compilation (i.e. before binding).
7203 @ifset vms
7204 @item /READ_SOURCES=AVAILABLE
7205 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7206 This is the default mode in which source files are checked if they are
7207 available, and ignored if they are not available.
7208 @end ifset
7209 @end table
7211 @node Binder Error Message Control
7212 @subsection Binder Error Message Control
7214 @noindent
7215 The following switches provide control over the generation of error
7216 messages from the binder:
7218 @table @option
7219 @c !sort!
7220 @item ^-v^/REPORT_ERRORS=VERBOSE^
7221 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7222 Verbose mode. In the normal mode, brief error messages are generated to
7223 @file{stderr}. If this switch is present, a header is written
7224 to @file{stdout} and any error messages are directed to @file{stdout}.
7225 All that is written to @file{stderr} is a brief summary message.
7227 @item ^-b^/REPORT_ERRORS=BRIEF^
7228 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7229 Generate brief error messages to @file{stderr} even if verbose mode is
7230 specified. This is relevant only when used with the
7231 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7233 @ifclear vms
7234 @item -m@var{n}
7235 @cindex @option{-m} (@code{gnatbind})
7236 Limits the number of error messages to @var{n}, a decimal integer in the
7237 range 1-999. The binder terminates immediately if this limit is reached.
7239 @item -M@var{xxx}
7240 @cindex @option{-M} (@code{gnatbind})
7241 Renames the generated main program from @code{main} to @code{xxx}.
7242 This is useful in the case of some cross-building environments, where
7243 the actual main program is separate from the one generated
7244 by @code{gnatbind}.
7245 @end ifclear
7247 @item ^-ws^/WARNINGS=SUPPRESS^
7248 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7249 @cindex Warnings
7250 Suppress all warning messages.
7252 @item ^-we^/WARNINGS=ERROR^
7253 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7254 Treat any warning messages as fatal errors.
7256 @ifset vms
7257 @item /WARNINGS=NORMAL
7258 Standard mode with warnings generated, but warnings do not get treated
7259 as errors.
7260 @end ifset
7262 @item ^-t^/NOTIME_STAMP_CHECK^
7263 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7264 @cindex Time stamp checks, in binder
7265 @cindex Binder consistency checks
7266 @cindex Consistency checks, in binder
7267 The binder performs a number of consistency checks including:
7269 @itemize @bullet
7270 @item
7271 Check that time stamps of a given source unit are consistent
7272 @item
7273 Check that checksums of a given source unit are consistent
7274 @item
7275 Check that consistent versions of @code{GNAT} were used for compilation
7276 @item
7277 Check consistency of configuration pragmas as required
7278 @end itemize
7280 @noindent
7281 Normally failure of such checks, in accordance with the consistency
7282 requirements of the Ada Reference Manual, causes error messages to be
7283 generated which abort the binder and prevent the output of a binder
7284 file and subsequent link to obtain an executable.
7286 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7287 into warnings, so that
7288 binding and linking can continue to completion even in the presence of such
7289 errors. The result may be a failed link (due to missing symbols), or a
7290 non-functional executable which has undefined semantics.
7291 @emph{This means that
7292 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7293 with extreme care.}
7294 @end table
7296 @node Elaboration Control
7297 @subsection Elaboration Control
7299 @noindent
7300 The following switches provide additional control over the elaboration
7301 order. For full details see @xref{Elaboration Order Handling in GNAT}.
7303 @table @option
7304 @item ^-p^/PESSIMISTIC_ELABORATION^
7305 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7306 Normally the binder attempts to choose an elaboration order that is
7307 likely to minimize the likelihood of an elaboration order error resulting
7308 in raising a @code{Program_Error} exception. This switch reverses the
7309 action of the binder, and requests that it deliberately choose an order
7310 that is likely to maximize the likelihood of an elaboration error.
7311 This is useful in ensuring portability and avoiding dependence on
7312 accidental fortuitous elaboration ordering.
7314 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7315 switch if dynamic
7316 elaboration checking is used (@option{-gnatE} switch used for compilation).
7317 This is because in the default static elaboration mode, all necessary
7318 @code{Elaborate_All} pragmas are implicitly inserted.
7319 These implicit pragmas are still respected by the binder in
7320 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7321 safe elaboration order is assured.
7322 @end table
7324 @node Output Control
7325 @subsection Output Control
7327 @noindent
7328 The following switches allow additional control over the output
7329 generated by the binder.
7331 @table @option
7332 @c !sort!
7334 @item ^-A^/BIND_FILE=ADA^
7335 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7336 Generate binder program in Ada (default). The binder program is named
7337 @file{b~@var{mainprog}.adb} by default. This can be changed with
7338 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7340 @item ^-c^/NOOUTPUT^
7341 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7342 Check only. Do not generate the binder output file. In this mode the
7343 binder performs all error checks but does not generate an output file.
7345 @item ^-C^/BIND_FILE=C^
7346 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7347 Generate binder program in C. The binder program is named
7348 @file{b_@var{mainprog}.c}.
7349 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7350 option.
7352 @item ^-e^/ELABORATION_DEPENDENCIES^
7353 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7354 Output complete list of elaboration-order dependencies, showing the
7355 reason for each dependency. This output can be rather extensive but may
7356 be useful in diagnosing problems with elaboration order. The output is
7357 written to @file{stdout}.
7359 @item ^-h^/HELP^
7360 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7361 Output usage information. The output is written to @file{stdout}.
7363 @item ^-K^/LINKER_OPTION_LIST^
7364 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7365 Output linker options to @file{stdout}. Includes library search paths,
7366 contents of pragmas Ident and Linker_Options, and libraries added
7367 by @code{gnatbind}.
7369 @item ^-l^/ORDER_OF_ELABORATION^
7370 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7371 Output chosen elaboration order. The output is written to @file{stdout}.
7373 @item ^-O^/OBJECT_LIST^
7374 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7375 Output full names of all the object files that must be linked to provide
7376 the Ada component of the program. The output is written to @file{stdout}.
7377 This list includes the files explicitly supplied and referenced by the user
7378 as well as implicitly referenced run-time unit files. The latter are
7379 omitted if the corresponding units reside in shared libraries. The
7380 directory names for the run-time units depend on the system configuration.
7382 @item ^-o ^/OUTPUT=^@var{file}
7383 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7384 Set name of output file to @var{file} instead of the normal
7385 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7386 binder generated body filename. In C mode you would normally give
7387 @var{file} an extension of @file{.c} because it will be a C source program.
7388 Note that if this option is used, then linking must be done manually.
7389 It is not possible to use gnatlink in this case, since it cannot locate
7390 the binder file.
7392 @item ^-r^/RESTRICTION_LIST^
7393 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7394 Generate list of @code{pragma Restrictions} that could be applied to
7395 the current unit. This is useful for code audit purposes, and also may
7396 be used to improve code generation in some cases.
7398 @end table
7400 @node Binding with Non-Ada Main Programs
7401 @subsection Binding with Non-Ada Main Programs
7403 @noindent
7404 In our description so far we have assumed that the main
7405 program is in Ada, and that the task of the binder is to generate a
7406 corresponding function @code{main} that invokes this Ada main
7407 program. GNAT also supports the building of executable programs where
7408 the main program is not in Ada, but some of the called routines are
7409 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7410 The following switch is used in this situation:
7412 @table @option
7413 @item ^-n^/NOMAIN^
7414 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7415 No main program. The main program is not in Ada.
7416 @end table
7418 @noindent
7419 In this case, most of the functions of the binder are still required,
7420 but instead of generating a main program, the binder generates a file
7421 containing the following callable routines:
7423 @table @code
7424 @item adainit
7425 @findex adainit
7426 You must call this routine to initialize the Ada part of the program by
7427 calling the necessary elaboration routines. A call to @code{adainit} is
7428 required before the first call to an Ada subprogram.
7430 Note that it is assumed that the basic execution environment must be setup
7431 to be appropriate for Ada execution at the point where the first Ada
7432 subprogram is called. In particular, if the Ada code will do any
7433 floating-point operations, then the FPU must be setup in an appropriate
7434 manner. For the case of the x86, for example, full precision mode is
7435 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7436 that the FPU is in the right state.
7438 @item adafinal
7439 @findex adafinal
7440 You must call this routine to perform any library-level finalization
7441 required by the Ada subprograms. A call to @code{adafinal} is required
7442 after the last call to an Ada subprogram, and before the program
7443 terminates.
7444 @end table
7446 @noindent
7447 If the @option{^-n^/NOMAIN^} switch
7448 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7449 @cindex Binder, multiple input files
7450 is given, more than one ALI file may appear on
7451 the command line for @code{gnatbind}. The normal @dfn{closure}
7452 calculation is performed for each of the specified units. Calculating
7453 the closure means finding out the set of units involved by tracing
7454 @code{with} references. The reason it is necessary to be able to
7455 specify more than one ALI file is that a given program may invoke two or
7456 more quite separate groups of Ada units.
7458 The binder takes the name of its output file from the last specified ALI
7459 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7460 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7461 The output is an Ada unit in source form that can
7462 be compiled with GNAT unless the -C switch is used in which case the
7463 output is a C source file, which must be compiled using the C compiler.
7464 This compilation occurs automatically as part of the @code{gnatlink}
7465 processing.
7467 Currently the GNAT run time requires a FPU using 80 bits mode
7468 precision. Under targets where this is not the default it is required to
7469 call GNAT.Float_Control.Reset before using floating point numbers (this
7470 include float computation, float input and output) in the Ada code. A
7471 side effect is that this could be the wrong mode for the foreign code
7472 where floating point computation could be broken after this call.
7474 @node Binding Programs with No Main Subprogram
7475 @subsection Binding Programs with No Main Subprogram
7477 @noindent
7478 It is possible to have an Ada program which does not have a main
7479 subprogram. This program will call the elaboration routines of all the
7480 packages, then the finalization routines.
7482 The following switch is used to bind programs organized in this manner:
7484 @table @option
7485 @item ^-z^/ZERO_MAIN^
7486 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7487 Normally the binder checks that the unit name given on the command line
7488 corresponds to a suitable main subprogram. When this switch is used,
7489 a list of ALI files can be given, and the execution of the program
7490 consists of elaboration of these units in an appropriate order.
7491 @end table
7493 @node Command-Line Access
7494 @section Command-Line Access
7496 @noindent
7497 The package @code{Ada.Command_Line} provides access to the command-line
7498 arguments and program name. In order for this interface to operate
7499 correctly, the two variables
7501 @smallexample
7502 @group
7503 int gnat_argc;
7504 char **gnat_argv;
7505 @end group
7506 @end smallexample
7508 @noindent
7509 @findex gnat_argv
7510 @findex gnat_argc
7511 are declared in one of the GNAT library routines. These variables must
7512 be set from the actual @code{argc} and @code{argv} values passed to the
7513 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7514 generates the C main program to automatically set these variables.
7515 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7516 set these variables. If they are not set, the procedures in
7517 @code{Ada.Command_Line} will not be available, and any attempt to use
7518 them will raise @code{Constraint_Error}. If command line access is
7519 required, your main program must set @code{gnat_argc} and
7520 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7523 @node Search Paths for gnatbind
7524 @section Search Paths for @code{gnatbind}
7526 @noindent
7527 The binder takes the name of an ALI file as its argument and needs to
7528 locate source files as well as other ALI files to verify object consistency.
7530 For source files, it follows exactly the same search rules as @code{gcc}
7531 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7532 directories searched are:
7534 @enumerate
7535 @item
7536 The directory containing the ALI file named in the command line, unless
7537 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7539 @item
7540 All directories specified by @option{^-I^/SEARCH^}
7541 switches on the @code{gnatbind}
7542 command line, in the order given.
7544 @item
7545 @findex ADA_OBJECTS_PATH
7546 Each of the directories listed in the value of the
7547 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7548 @ifset unw
7549 Construct this value
7550 exactly as the @code{PATH} environment variable: a list of directory
7551 names separated by colons (semicolons when working with the NT version
7552 of GNAT).
7553 @end ifset
7554 @ifset vms
7555 Normally, define this value as a logical name containing a comma separated
7556 list of directory names.
7558 This variable can also be defined by means of an environment string
7559 (an argument to the DEC C exec* set of functions).
7561 Logical Name:
7562 @smallexample
7563 DEFINE ANOTHER_PATH FOO:[BAG]
7564 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7565 @end smallexample
7567 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7568 first, followed by the standard Ada 95
7569 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7570 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7571 (Text_IO, Sequential_IO, etc)
7572 instead of the Ada95 packages. Thus, in order to get the Ada 95
7573 packages by default, ADA_OBJECTS_PATH must be redefined.
7574 @end ifset
7576 @item
7577 @findex ADA_PRJ_OBJECTS_FILE
7578 Each of the directories listed in the text file whose name is given
7579 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7581 @noindent
7582 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7583 driver when project files are used. It should not normally be set
7584 by other means.
7586 @item
7587 The content of the @file{ada_object_path} file which is part of the GNAT
7588 installation tree and is used to store standard libraries such as the
7589 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7590 specified.
7591 @ifclear vms
7592 @ref{Installing a library}
7593 @end ifclear
7594 @end enumerate
7596 @noindent
7597 In the binder the switch @option{^-I^/SEARCH^}
7598 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7599 is used to specify both source and
7600 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7601 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7602 instead if you want to specify
7603 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7604 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7605 if you want to specify library paths
7606 only. This means that for the binder
7607 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7608 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7609 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7610 The binder generates the bind file (a C language source file) in the
7611 current working directory.
7613 @findex Ada
7614 @findex System
7615 @findex Interfaces
7616 @findex GNAT
7617 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7618 children make up the GNAT Run-Time Library, together with the package
7619 GNAT and its children, which contain a set of useful additional
7620 library functions provided by GNAT. The sources for these units are
7621 needed by the compiler and are kept together in one directory. The ALI
7622 files and object files generated by compiling the RTL are needed by the
7623 binder and the linker and are kept together in one directory, typically
7624 different from the directory containing the sources. In a normal
7625 installation, you need not specify these directory names when compiling
7626 or binding. Either the environment variables or the built-in defaults
7627 cause these files to be found.
7629 Besides simplifying access to the RTL, a major use of search paths is
7630 in compiling sources from multiple directories. This can make
7631 development environments much more flexible.
7633 @node Examples of gnatbind Usage
7634 @section Examples of @code{gnatbind} Usage
7636 @noindent
7637 This section contains a number of examples of using the GNAT binding
7638 utility @code{gnatbind}.
7640 @table @code
7641 @item gnatbind hello
7642 The main program @code{Hello} (source program in @file{hello.adb}) is
7643 bound using the standard switch settings. The generated main program is
7644 @file{b~hello.adb}. This is the normal, default use of the binder.
7646 @ifclear vms
7647 @item gnatbind hello -o mainprog.adb
7648 @end ifclear
7649 @ifset vms
7650 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7651 @end ifset
7652 The main program @code{Hello} (source program in @file{hello.adb}) is
7653 bound using the standard switch settings. The generated main program is
7654 @file{mainprog.adb} with the associated spec in
7655 @file{mainprog.ads}. Note that you must specify the body here not the
7656 spec, in the case where the output is in Ada. Note that if this option
7657 is used, then linking must be done manually, since gnatlink will not
7658 be able to find the generated file.
7660 @ifclear vms
7661 @item gnatbind main -C -o mainprog.c -x
7662 @end ifclear
7663 @ifset vms
7664 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7665 @end ifset
7666 The main program @code{Main} (source program in
7667 @file{main.adb}) is bound, excluding source files from the
7668 consistency checking, generating
7669 the file @file{mainprog.c}.
7671 @ifclear vms
7672 @item gnatbind -x main_program -C -o mainprog.c
7673 This command is exactly the same as the previous example. Switches may
7674 appear anywhere in the command line, and single letter switches may be
7675 combined into a single switch.
7676 @end ifclear
7678 @ifclear vms
7679 @item gnatbind -n math dbase -C -o ada-control.c
7680 @end ifclear
7681 @ifset vms
7682 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7683 @end ifset
7684 The main program is in a language other than Ada, but calls to
7685 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7686 to @code{gnatbind} generates the file @file{ada-control.c} containing
7687 the @code{adainit} and @code{adafinal} routines to be called before and
7688 after accessing the Ada units.
7689 @end table
7691 @c ------------------------------------
7692 @node Linking Using gnatlink
7693 @chapter Linking Using @code{gnatlink}
7694 @c ------------------------------------
7695 @findex gnatlink
7697 @noindent
7698 This chapter discusses @code{gnatlink}, a tool that links
7699 an Ada program and builds an executable file. This utility
7700 invokes the system linker ^(via the @code{gcc} command)^^
7701 with a correct list of object files and library references.
7702 @code{gnatlink} automatically determines the list of files and
7703 references for the Ada part of a program. It uses the binder file
7704 generated by the @command{gnatbind} to determine this list.
7706 @menu
7707 * Running gnatlink::
7708 * Switches for gnatlink::
7709 * Setting Stack Size from gnatlink::
7710 * Setting Heap Size from gnatlink::
7711 @end menu
7713 @node Running gnatlink
7714 @section Running @code{gnatlink}
7716 @noindent
7717 The form of the @code{gnatlink} command is
7719 @smallexample
7720 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7721            [@var{non-Ada objects}] [@var{linker options}]
7722 @end smallexample
7724 @noindent
7725 The arguments of @code{gnatlink} (switches, main @file{ALI} file,
7726 non-Ada objects
7727 or linker options) may be in any order, provided that no non-Ada object may
7728 be mistaken for a main @file{ALI} file.
7729 Any file name @file{F} without the @file{.ali}
7730 extension will be taken as the main @file{ALI} file if a file exists
7731 whose name is the concatenation of @file{F} and @file{.ali}.
7733 @noindent
7734 @file{@var{mainprog}.ali} references the ALI file of the main program.
7735 The @file{.ali} extension of this file can be omitted. From this
7736 reference, @code{gnatlink} locates the corresponding binder file
7737 @file{b~@var{mainprog}.adb} and, using the information in this file along
7738 with the list of non-Ada objects and linker options, constructs a
7739 linker command file to create the executable.
7741 The arguments other than the @code{gnatlink} switches and the main @file{ALI}
7742 file are passed to the linker uninterpreted.
7743 They typically include the names of
7744 object files for units written in other languages than Ada and any library
7745 references required to resolve references in any of these foreign language
7746 units, or in @code{Import} pragmas in any Ada units.
7748 @var{linker options} is an optional list of linker specific
7749 switches.
7750 The default linker called by gnatlink is @var{gcc} which in
7751 turn calls the appropriate system linker.
7752 Standard options for the linker such as @option{-lmy_lib} or
7753 @option{-Ldir} can be added as is.
7754 For options that are not recognized by
7755 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7756 @option{-Wl,}.
7757 Refer to the GCC documentation for
7758 details. Here is an example showing how to generate a linker map:
7760 @ifclear vms
7761 @smallexample
7762 $ gnatlink my_prog -Wl,-Map,MAPFILE
7763 @end smallexample
7764 @end ifclear
7766 @ifset vms
7767 <<Need example for VMS>>
7768 @end ifset
7770 Using @var{linker options} it is possible to set the program stack and
7771 heap size. See @ref{Setting Stack Size from gnatlink}, and
7772 @ref{Setting Heap Size from gnatlink}.
7774 @code{gnatlink} determines the list of objects required by the Ada
7775 program and prepends them to the list of objects passed to the linker.
7776 @code{gnatlink} also gathers any arguments set by the use of
7777 @code{pragma Linker_Options} and adds them to the list of arguments
7778 presented to the linker.
7780 @ifset vms
7781 @code{gnatlink} accepts the following types of extra files on the command
7782 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7783 options files (.OPT). These are recognized and handled according to their
7784 extension.
7785 @end ifset
7787 @node Switches for gnatlink
7788 @section Switches for @code{gnatlink}
7790 @noindent
7791 The following switches are available with the @code{gnatlink} utility:
7793 @table @option
7794 @c !sort!
7796 @item ^-A^/BIND_FILE=ADA^
7797 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7798 The binder has generated code in Ada. This is the default.
7800 @item ^-C^/BIND_FILE=C^
7801 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatlink})
7802 If instead of generating a file in Ada, the binder has generated one in
7803 C, then the linker needs to know about it. Use this switch to signal
7804 to @code{gnatlink} that the binder has generated C code rather than
7805 Ada code.
7807 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7808 @cindex Command line length
7809 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@code{gnatlink})
7810 On some targets, the command line length is limited, and @code{gnatlink}
7811 will generate a separate file for the linker if the list of object files
7812 is too long.
7813 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7814 to be generated even if
7815 the limit is not exceeded. This is useful in some cases to deal with
7816 special situations where the command line length is exceeded.
7818 @item ^-g^/DEBUG^
7819 @cindex Debugging information, including
7820 @cindex @option{^-g^/DEBUG^} (@code{gnatlink})
7821 The option to include debugging information causes the Ada bind file (in
7822 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7823 @option{^-g^/DEBUG^}.
7824 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7825 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7826 Without @option{^-g^/DEBUG^}, the binder removes these files by
7827 default. The same procedure apply if a C bind file was generated using
7828 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7829 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7831 @item ^-n^/NOCOMPILE^
7832 @cindex @option{^-n^/NOCOMPILE^} (@code{gnatlink})
7833 Do not compile the file generated by the binder. This may be used when
7834 a link is rerun with different options, but there is no need to recompile
7835 the binder file.
7837 @item ^-v^/VERBOSE^
7838 @cindex @option{^-v^/VERBOSE^} (@code{gnatlink})
7839 Causes additional information to be output, including a full list of the
7840 included object files. This switch option is most useful when you want
7841 to see what set of object files are being used in the link step.
7843 @item ^-v -v^/VERBOSE/VERBOSE^
7844 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@code{gnatlink})
7845 Very verbose mode. Requests that the compiler operate in verbose mode when
7846 it compiles the binder file, and that the system linker run in verbose mode.
7848 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7849 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatlink})
7850 @var{exec-name} specifies an alternate name for the generated
7851 executable program. If this switch is omitted, the executable has the same
7852 name as the main unit. For example, @code{gnatlink try.ali} creates
7853 an executable called @file{^try^TRY.EXE^}.
7855 @ifclear vms
7856 @item -b @var{target}
7857 @cindex @option{-b} (@code{gnatlink})
7858 Compile your program to run on @var{target}, which is the name of a
7859 system configuration. You must have a GNAT cross-compiler built if
7860 @var{target} is not the same as your host system.
7862 @item -B@var{dir}
7863 @cindex @option{-B} (@code{gnatlink})
7864 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7865 from @var{dir} instead of the default location. Only use this switch
7866 when multiple versions of the GNAT compiler are available. See the
7867 @code{gcc} manual page for further details. You would normally use the
7868 @option{-b} or @option{-V} switch instead.
7870 @item --GCC=@var{compiler_name}
7871 @cindex @option{--GCC=compiler_name} (@code{gnatlink})
7872 Program used for compiling the binder file. The default is
7873 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
7874 @code{compiler_name} contains spaces or other separator characters. As
7875 an example @option{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7876 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7877 inserted after your command name. Thus in the above example the compiler
7878 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7879 If several @option{--GCC=compiler_name} are used, only the last
7880 @var{compiler_name} is taken into account. However, all the additional
7881 switches are also taken into account. Thus,
7882 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7883 @option{--GCC="bar -x -y -z -t"}.
7885 @item --LINK=@var{name}
7886 @cindex @option{--LINK=} (@code{gnatlink})
7887 @var{name} is the name of the linker to be invoked. This is especially
7888 useful in mixed language programs since languages such as C++ require
7889 their own linker to be used. When this switch is omitted, the default
7890 name for the linker is (@file{gcc}). When this switch is used, the
7891 specified linker is called instead of (@file{gcc}) with exactly the same
7892 parameters that would have been passed to (@file{gcc}) so if the desired
7893 linker requires different parameters it is necessary to use a wrapper
7894 script that massages the parameters before invoking the real linker. It
7895 may be useful to control the exact invocation by using the verbose
7896 switch.
7898 @end ifclear
7900 @ifset vms
7901 @item /DEBUG=TRACEBACK
7902 @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7903 This qualifier causes sufficient information to be included in the
7904 executable file to allow a traceback, but does not include the full
7905 symbol information needed by the debugger.
7907 @item /IDENTIFICATION="<string>"
7908 @code{"<string>"} specifies the string to be stored in the image file
7909 identification field in the image header.
7910 It overrides any pragma @code{Ident} specified string.
7912 @item /NOINHIBIT-EXEC
7913 Generate the executable file even if there are linker warnings.
7915 @item /NOSTART_FILES
7916 Don't link in the object file containing the ``main'' transfer address.
7917 Used when linking with a foreign language main program compiled with a
7918 Digital compiler.
7920 @item /STATIC
7921 Prefer linking with object libraries over sharable images, even without
7922 /DEBUG.
7923 @end ifset
7925 @end table
7927 @node Setting Stack Size from gnatlink
7928 @section Setting Stack Size from @code{gnatlink}
7930 @noindent
7931 Under Windows systems, it is possible to specify the program stack size from
7932 @code{gnatlink} using either:
7934 @itemize @bullet
7936 @item using @option{-Xlinker} linker option
7938 @smallexample
7939 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7940 @end smallexample
7942 This sets the stack reserve size to 0x10000 bytes and the stack commit
7943 size to 0x1000 bytes.
7945 @item using @option{-Wl} linker option
7947 @smallexample
7948 $ gnatlink hello -Wl,--stack=0x1000000
7949 @end smallexample
7951 This sets the stack reserve size to 0x1000000 bytes. Note that with
7952 @option{-Wl} option it is not possible to set the stack commit size
7953 because the coma is a separator for this option.
7955 @end itemize
7957 @node Setting Heap Size from gnatlink
7958 @section Setting Heap Size from @code{gnatlink}
7960 @noindent
7961 Under Windows systems, it is possible to specify the program heap size from
7962 @code{gnatlink} using either:
7964 @itemize @bullet
7966 @item using @option{-Xlinker} linker option
7968 @smallexample
7969 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7970 @end smallexample
7972 This sets the heap reserve size to 0x10000 bytes and the heap commit
7973 size to 0x1000 bytes.
7975 @item using @option{-Wl} linker option
7977 @smallexample
7978 $ gnatlink hello -Wl,--heap=0x1000000
7979 @end smallexample
7981 This sets the heap reserve size to 0x1000000 bytes. Note that with
7982 @option{-Wl} option it is not possible to set the heap commit size
7983 because the coma is a separator for this option.
7985 @end itemize
7987 @node The GNAT Make Program gnatmake
7988 @chapter The GNAT Make Program @code{gnatmake}
7989 @findex gnatmake
7991 @menu
7992 * Running gnatmake::
7993 * Switches for gnatmake::
7994 * Mode Switches for gnatmake::
7995 * Notes on the Command Line::
7996 * How gnatmake Works::
7997 * Examples of gnatmake Usage::
7998 @end menu
7999 @noindent
8000 A typical development cycle when working on an Ada program consists of
8001 the following steps:
8003 @enumerate
8004 @item
8005 Edit some sources to fix bugs.
8007 @item
8008 Add enhancements.
8010 @item
8011 Compile all sources affected.
8013 @item
8014 Rebind and relink.
8016 @item
8017 Test.
8018 @end enumerate
8020 @noindent
8021 The third step can be tricky, because not only do the modified files
8022 @cindex Dependency rules
8023 have to be compiled, but any files depending on these files must also be
8024 recompiled. The dependency rules in Ada can be quite complex, especially
8025 in the presence of overloading, @code{use} clauses, generics and inlined
8026 subprograms.
8028 @code{gnatmake} automatically takes care of the third and fourth steps
8029 of this process. It determines which sources need to be compiled,
8030 compiles them, and binds and links the resulting object files.
8032 Unlike some other Ada make programs, the dependencies are always
8033 accurately recomputed from the new sources. The source based approach of
8034 the GNAT compilation model makes this possible. This means that if
8035 changes to the source program cause corresponding changes in
8036 dependencies, they will always be tracked exactly correctly by
8037 @code{gnatmake}.
8039 @node Running gnatmake
8040 @section Running @code{gnatmake}
8042 @noindent
8043 The usual form of the @code{gnatmake} command is
8045 @smallexample
8046 $ gnatmake [@var{switches}] @var{file_name}
8047       [@var{file_names}] [@var{mode_switches}]
8048 @end smallexample
8050 @noindent
8051 The only required argument is one @var{file_name}, which specifies
8052 a compilation unit that is a main program. Several @var{file_names} can be
8053 specified: this will result in several executables being built.
8054 If @code{switches} are present, they can be placed before the first
8055 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8056 If @var{mode_switches} are present, they must always be placed after
8057 the last @var{file_name} and all @code{switches}.
8059 If you are using standard file extensions (.adb and .ads), then the
8060 extension may be omitted from the @var{file_name} arguments. However, if
8061 you are using non-standard extensions, then it is required that the
8062 extension be given. A relative or absolute directory path can be
8063 specified in a @var{file_name}, in which case, the input source file will
8064 be searched for in the specified directory only. Otherwise, the input
8065 source file will first be searched in the directory where
8066 @code{gnatmake} was invoked and if it is not found, it will be search on
8067 the source path of the compiler as described in
8068 @ref{Search Paths and the Run-Time Library (RTL)}.
8070 All @code{gnatmake} output (except when you specify
8071 @option{^-M^/DEPENDENCIES_LIST^}) is to
8072 @file{stderr}. The output produced by the
8073 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8074 @file{stdout}.
8076 @node Switches for gnatmake
8077 @section Switches for @code{gnatmake}
8079 @noindent
8080 You may specify any of the following switches to @code{gnatmake}:
8082 @table @option
8083 @c !sort!
8084 @ifclear vms
8085 @item --GCC=@var{compiler_name}
8086 @cindex @option{--GCC=compiler_name} (@code{gnatmake})
8087 Program used for compiling. The default is `@code{gcc}'. You need to use
8088 quotes around @var{compiler_name} if @code{compiler_name} contains
8089 spaces or other separator characters. As an example @option{--GCC="foo -x
8090 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
8091 compiler. Note that switch @option{-c} is always inserted after your
8092 command name. Thus in the above example the compiler command that will
8093 be used by @code{gnatmake} will be @code{foo -c -x -y}.
8094 If several @option{--GCC=compiler_name} are used, only the last
8095 @var{compiler_name} is taken into account. However, all the additional
8096 switches are also taken into account. Thus,
8097 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8098 @option{--GCC="bar -x -y -z -t"}.
8100 @item --GNATBIND=@var{binder_name}
8101 @cindex @option{--GNATBIND=binder_name} (@code{gnatmake})
8102 Program used for binding. The default is `@code{gnatbind}'. You need to
8103 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8104 or other separator characters. As an example @option{--GNATBIND="bar -x
8105 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
8106 binder. Binder switches that are normally appended by @code{gnatmake} to
8107 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8109 @item --GNATLINK=@var{linker_name}
8110 @cindex @option{--GNATLINK=linker_name} (@code{gnatmake})
8111 Program used for linking. The default is `@code{gnatlink}'. You need to
8112 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8113 or other separator characters. As an example @option{--GNATLINK="lan -x
8114 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
8115 linker. Linker switches that are normally appended by @code{gnatmake} to
8116 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
8118 @end ifclear
8120 @item ^-a^/ALL_FILES^
8121 @cindex @option{^-a^/ALL_FILES^} (@code{gnatmake})
8122 Consider all files in the make process, even the GNAT internal system
8123 files (for example, the predefined Ada library files), as well as any
8124 locked files. Locked files are files whose ALI file is write-protected.
8125 By default,
8126 @code{gnatmake} does not check these files,
8127 because the assumption is that the GNAT internal files are properly up
8128 to date, and also that any write protected ALI files have been properly
8129 installed. Note that if there is an installation problem, such that one
8130 of these files is not up to date, it will be properly caught by the
8131 binder.
8132 You may have to specify this switch if you are working on GNAT
8133 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8134 in conjunction with @option{^-f^/FORCE_COMPILE^}
8135 if you need to recompile an entire application,
8136 including run-time files, using special configuration pragmas,
8137 such as a @code{Normalize_Scalars} pragma.
8139 By default
8140 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8141 internal files with
8142 @ifclear vms
8143 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8144 @end ifclear
8145 @ifset vms
8146 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8147 @end ifset
8149 @item ^-b^/ACTIONS=BIND^
8150 @cindex @option{^-b^/ACTIONS=BIND^} (@code{gnatmake})
8151 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8152 compilation and binding, but no link.
8153 Can be combined with @option{^-l^/ACTIONS=LINK^}
8154 to do binding and linking. When not combined with
8155 @option{^-c^/ACTIONS=COMPILE^}
8156 all the units in the closure of the main program must have been previously
8157 compiled and must be up to date. The root unit specified by @var{file_name}
8158 may be given without extension, with the source extension or, if no GNAT
8159 Project File is specified, with the ALI file extension.
8161 @item ^-c^/ACTIONS=COMPILE^
8162 @cindex @option{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
8163 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8164 is also specified. Do not perform linking, except if both
8165 @option{^-b^/ACTIONS=BIND^} and
8166  @option{^-l^/ACTIONS=LINK^} are also specified.
8167 If the root unit specified by @var{file_name} is not a main unit, this is the
8168 default. Otherwise @code{gnatmake} will attempt binding and linking
8169 unless all objects are up to date and the executable is more recent than
8170 the objects.
8172 @item ^-C^/MAPPING^
8173 @cindex @option{^-C^/MAPPING^} (@code{gnatmake})
8174 Use a temporary mapping file. A mapping file is a way to communicate to the
8175 compiler two mappings: from unit names to file names (without any directory
8176 information) and from file names to path names (with full directory
8177 information). These mappings are used by the compiler to short-circuit the path
8178 search. When @code{gnatmake} is invoked with this switch, it will create
8179 a temporary mapping file, initially populated by the project manager,
8180 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8181 Each invocation of the compiler will add the newly accessed sources to the
8182 mapping file. This will improve the source search during the next invocation
8183 of the compiler.
8185 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8186 @cindex @option{^-C=^/USE_MAPPING^} (@code{gnatmake})
8187 Use a specific mapping file. The file, specified as a path name (absolute or
8188 relative) by this switch, should already exist, otherwise the switch is
8189 ineffective. The specified mapping file will be communicated to the compiler.
8190 This switch is not compatible with a project file
8191 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8192 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8194 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8195 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatmake})
8196 Put all object files and ALI file in directory @var{dir}.
8197 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8198 and ALI files go in the current working directory.
8200 This switch cannot be used when using a project file.
8202 @ifclear vms
8203 @item -eL
8204 @cindex @option{-eL} (@code{gnatmake})
8205 Follow all symbolic links when processing project files.
8206 @end ifclear
8208 @item ^-f^/FORCE_COMPILE^
8209 @cindex @option{^-f^/FORCE_COMPILE^} (@code{gnatmake})
8210 Force recompilations. Recompile all sources, even though some object
8211 files may be up to date, but don't recompile predefined or GNAT internal
8212 files or locked files (files with a write-protected ALI file),
8213 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8215 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8216 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatmake})
8217 When using project files, if some errors or warnings are detected during
8218 parsing and verbose mode is not in effect (no use of switch
8219 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8220 file, rather than its simple file name.
8222 @item ^-i^/IN_PLACE^
8223 @cindex @option{^-i^/IN_PLACE^} (@code{gnatmake})
8224 In normal mode, @code{gnatmake} compiles all object files and ALI files
8225 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8226 then instead object files and ALI files that already exist are overwritten
8227 in place. This means that once a large project is organized into separate
8228 directories in the desired manner, then @code{gnatmake} will automatically
8229 maintain and update this organization. If no ALI files are found on the
8230 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8231 the new object and ALI files are created in the
8232 directory containing the source being compiled. If another organization
8233 is desired, where objects and sources are kept in different directories,
8234 a useful technique is to create dummy ALI files in the desired directories.
8235 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
8236 the corresponding source file, and it will be put the resulting object
8237 and ALI files in the directory where it found the dummy file.
8239 @item ^-j^/PROCESSES=^@var{n}
8240 @cindex @option{^-j^/PROCESSES^} (@code{gnatmake})
8241 @cindex Parallel make
8242 Use @var{n} processes to carry out the (re)compilations. On a
8243 multiprocessor machine compilations will occur in parallel. In the
8244 event of compilation errors, messages from various compilations might
8245 get interspersed (but @code{gnatmake} will give you the full ordered
8246 list of failing compiles at the end). If this is problematic, rerun
8247 the make process with n set to 1 to get a clean list of messages.
8249 @item ^-k^/CONTINUE_ON_ERROR^
8250 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
8251 Keep going. Continue as much as possible after a compilation error. To
8252 ease the programmer's task in case of compilation errors, the list of
8253 sources for which the compile fails is given when @code{gnatmake}
8254 terminates.
8256 If @code{gnatmake} is invoked with several @file{file_names} and with this
8257 switch, if there are compilation errors when building an executable,
8258 @code{gnatmake} will not attempt to build the following executables.
8260 @item ^-l^/ACTIONS=LINK^
8261 @cindex @option{^-l^/ACTIONS=LINK^} (@code{gnatmake})
8262 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8263 and linking. Linking will not be performed if combined with
8264 @option{^-c^/ACTIONS=COMPILE^}
8265 but not with @option{^-b^/ACTIONS=BIND^}.
8266 When not combined with @option{^-b^/ACTIONS=BIND^}
8267 all the units in the closure of the main program must have been previously
8268 compiled and must be up to date, and the main program need to have been bound.
8269 The root unit specified by @var{file_name}
8270 may be given without extension, with the source extension or, if no GNAT
8271 Project File is specified, with the ALI file extension.
8273 @item ^-m^/MINIMAL_RECOMPILATION^
8274 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
8275 Specifies that the minimum necessary amount of recompilations
8276 be performed. In this mode @code{gnatmake} ignores time
8277 stamp differences when the only
8278 modifications to a source file consist in adding/removing comments,
8279 empty lines, spaces or tabs. This means that if you have changed the
8280 comments in a source file or have simply reformatted it, using this
8281 switch will tell gnatmake not to recompile files that depend on it
8282 (provided other sources on which these files depend have undergone no
8283 semantic modifications). Note that the debugging information may be
8284 out of date with respect to the sources if the @option{-m} switch causes
8285 a compilation to be switched, so the use of this switch represents a
8286 trade-off between compilation time and accurate debugging information.
8288 @item ^-M^/DEPENDENCIES_LIST^
8289 @cindex Dependencies, producing list
8290 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
8291 Check if all objects are up to date. If they are, output the object
8292 dependences to @file{stdout} in a form that can be directly exploited in
8293 a @file{Makefile}. By default, each source file is prefixed with its
8294 (relative or absolute) directory name. This name is whatever you
8295 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8296 and @option{^-I^/SEARCH^} switches. If you use
8297 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8298 @option{^-q^/QUIET^}
8299 (see below), only the source file names,
8300 without relative paths, are output. If you just specify the
8301 @option{^-M^/DEPENDENCIES_LIST^}
8302 switch, dependencies of the GNAT internal system files are omitted. This
8303 is typically what you want. If you also specify
8304 the @option{^-a^/ALL_FILES^} switch,
8305 dependencies of the GNAT internal files are also listed. Note that
8306 dependencies of the objects in external Ada libraries (see switch
8307 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8308 are never reported.
8310 @item ^-n^/DO_OBJECT_CHECK^
8311 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
8312 Don't compile, bind, or link. Checks if all objects are up to date.
8313 If they are not, the full name of the first file that needs to be
8314 recompiled is printed.
8315 Repeated use of this option, followed by compiling the indicated source
8316 file, will eventually result in recompiling all required units.
8318 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8319 @cindex @option{^-o^/EXECUTABLE^} (@code{gnatmake})
8320 Output executable name. The name of the final executable program will be
8321 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8322 name for the executable will be the name of the input file in appropriate form
8323 for an executable file on the host system.
8325 This switch cannot be used when invoking @code{gnatmake} with several
8326 @file{file_names}.
8328 @item ^-P^/PROJECT_FILE=^@var{project}
8329 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatmake})
8330 Use project file @var{project}. Only one such switch can be used.
8331 See @ref{gnatmake and Project Files}.
8333 @item ^-q^/QUIET^
8334 @cindex @option{^-q^/QUIET^} (@code{gnatmake})
8335 Quiet. When this flag is not set, the commands carried out by
8336 @code{gnatmake} are displayed.
8338 @item ^-s^/SWITCH_CHECK/^
8339 @cindex @option{^-s^/SWITCH_CHECK^} (@code{gnatmake})
8340 Recompile if compiler switches have changed since last compilation.
8341 All compiler switches but -I and -o are taken into account in the
8342 following way:
8343 orders between different ``first letter'' switches are ignored, but
8344 orders between same switches are taken into account. For example,
8345 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8346 is equivalent to @option{-O -g}.
8348 This switch is recommended when Integrated Preprocessing is used.
8350 @item ^-u^/UNIQUE^
8351 @cindex @option{^-u^/UNIQUE^} (@code{gnatmake})
8352 Unique. Recompile at most the main files. It implies -c. Combined with
8353 -f, it is equivalent to calling the compiler directly. Note that using
8354 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8355 (see @ref{Project Files and Main Subprograms}).
8357 @item ^-U^/ALL_PROJECTS^
8358 @cindex @option{^-U^/ALL_PROJECTS^} (@code{gnatmake})
8359 When used without a project file or with one or several mains on the command
8360 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8361 on the command line, all sources of all project files are checked and compiled
8362 if not up to date, and libraries are rebuilt, if necessary.
8364 @item ^-v^/REASONS^
8365 @cindex @option{^-v^/REASONS^} (@code{gnatmake})
8366 Verbose. Displays the reason for all recompilations @code{gnatmake}
8367 decides are necessary.
8369 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8370 Indicates the verbosity of the parsing of GNAT project files.
8371 See @ref{Switches Related to Project Files}.
8373 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8374 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@code{gnatmake})
8375 Indicates that sources that are not part of any Project File may be compiled.
8376 Normally, when using Project Files, only sources that are part of a Project
8377 File may be compile. When this switch is used, a source outside of all Project
8378 Files may be compiled. The ALI file and the object file will be put in the
8379 object directory of the main Project. The compilation switches used will only
8380 be those specified on the command line.
8382 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8383 Indicates that external variable @var{name} has the value @var{value}.
8384 The Project Manager will use this value for occurrences of
8385 @code{external(name)} when parsing the project file.
8386 See @ref{Switches Related to Project Files}.
8388 @item ^-z^/NOMAIN^
8389 @cindex @option{^-z^/NOMAIN^} (@code{gnatmake})
8390 No main subprogram. Bind and link the program even if the unit name
8391 given on the command line is a package name. The resulting executable
8392 will execute the elaboration routines of the package and its closure,
8393 then the finalization routines.
8395 @item ^-g^/DEBUG^
8396 @cindex @option{^-g^/DEBUG^} (@code{gnatmake})
8397 Enable debugging. This switch is simply passed to the compiler and to the
8398 linker.
8400 @end table
8402 @table @asis
8403 @item @code{gcc} @asis{switches}
8404 @ifclear vms
8405 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
8406 is passed to @code{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8407 @end ifclear
8408 @ifset vms
8409 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8410 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8411 automatically treated as a compiler switch, and passed on to all
8412 compilations that are carried out.
8413 @end ifset
8414 @end table
8416 @noindent
8417 Source and library search path switches:
8419 @table @option
8420 @c !sort!
8421 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8422 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8423 When looking for source files also look in directory @var{dir}.
8424 The order in which source files search is undertaken is
8425 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8427 @item ^-aL^/SKIP_MISSING=^@var{dir}
8428 @cindex @option{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8429 Consider @var{dir} as being an externally provided Ada library.
8430 Instructs @code{gnatmake} to skip compilation units whose @file{.ALI}
8431 files have been located in directory @var{dir}. This allows you to have
8432 missing bodies for the units in @var{dir} and to ignore out of date bodies
8433 for the same units. You still need to specify
8434 the location of the specs for these units by using the switches
8435 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8436 or @option{^-I^/SEARCH=^@var{dir}}.
8437 Note: this switch is provided for compatibility with previous versions
8438 of @code{gnatmake}. The easier method of causing standard libraries
8439 to be excluded from consideration is to write-protect the corresponding
8440 ALI files.
8442 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8443 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8444 When searching for library and object files, look in directory
8445 @var{dir}. The order in which library files are searched is described in
8446 @ref{Search Paths for gnatbind}.
8448 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8449 @cindex Search paths, for @code{gnatmake}
8450 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8451 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8452 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8454 @item ^-I^/SEARCH=^@var{dir}
8455 @cindex @option{^-I^/SEARCH^} (@code{gnatmake})
8456 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8457 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8459 @item ^-I-^/NOCURRENT_DIRECTORY^
8460 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8461 @cindex Source files, suppressing search
8462 Do not look for source files in the directory containing the source
8463 file named in the command line.
8464 Do not look for ALI or object files in the directory
8465 where @code{gnatmake} was invoked.
8467 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8468 @cindex @option{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8469 @cindex Linker libraries
8470 Add directory @var{dir} to the list of directories in which the linker
8471 will search for libraries. This is equivalent to
8472 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8473 @ifclear vms
8474 Furthermore, under Windows, the sources pointed to by the libraries path
8475 set in the registry are not searched for.
8476 @end ifclear
8478 @item -nostdinc
8479 @cindex @option{-nostdinc} (@code{gnatmake})
8480 Do not look for source files in the system default directory.
8482 @item -nostdlib
8483 @cindex @option{-nostdlib} (@code{gnatmake})
8484 Do not look for library files in the system default directory.
8486 @item --RTS=@var{rts-path}
8487 @cindex @option{--RTS} (@code{gnatmake})
8488 Specifies the default location of the runtime library. GNAT looks for the
8489 runtime
8490 in the following directories, and stops as soon as a valid runtime is found
8491 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8492 @file{ada_object_path} present):
8494 @itemize @bullet
8495 @item <current directory>/$rts_path
8497 @item <default-search-dir>/$rts_path
8499 @item <default-search-dir>/rts-$rts_path
8500 @end itemize
8502 @noindent
8503 The selected path is handled like a normal RTS path.
8505 @end table
8507 @node Mode Switches for gnatmake
8508 @section Mode Switches for @code{gnatmake}
8510 @noindent
8511 The mode switches (referred to as @code{mode_switches}) allow the
8512 inclusion of switches that are to be passed to the compiler itself, the
8513 binder or the linker. The effect of a mode switch is to cause all
8514 subsequent switches up to the end of the switch list, or up to the next
8515 mode switch, to be interpreted as switches to be passed on to the
8516 designated component of GNAT.
8518 @table @option
8519 @c !sort!
8520 @item -cargs @var{switches}
8521 @cindex @option{-cargs} (@code{gnatmake})
8522 Compiler switches. Here @var{switches} is a list of switches
8523 that are valid switches for @code{gcc}. They will be passed on to
8524 all compile steps performed by @code{gnatmake}.
8526 @item -bargs @var{switches}
8527 @cindex @option{-bargs} (@code{gnatmake})
8528 Binder switches. Here @var{switches} is a list of switches
8529 that are valid switches for @code{gnatbind}. They will be passed on to
8530 all bind steps performed by @code{gnatmake}.
8532 @item -largs @var{switches}
8533 @cindex @option{-largs} (@code{gnatmake})
8534 Linker switches. Here @var{switches} is a list of switches
8535 that are valid switches for @code{gnatlink}. They will be passed on to
8536 all link steps performed by @code{gnatmake}.
8538 @item -margs @var{switches}
8539 @cindex @option{-margs} (@code{gnatmake})
8540 Make switches. The switches are directly interpreted by @code{gnatmake},
8541 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8542 or @option{-largs}.
8543 @end table
8545 @node Notes on the Command Line
8546 @section Notes on the Command Line
8548 @noindent
8549 This section contains some additional useful notes on the operation
8550 of the @code{gnatmake} command.
8552 @itemize @bullet
8553 @item
8554 @cindex Recompilation, by @code{gnatmake}
8555 If @code{gnatmake} finds no ALI files, it recompiles the main program
8556 and all other units required by the main program.
8557 This means that @code{gnatmake}
8558 can be used for the initial compile, as well as during subsequent steps of
8559 the development cycle.
8561 @item
8562 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8563 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8564 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8565 warning.
8567 @item
8568 In @code{gnatmake} the switch @option{^-I^/SEARCH^}
8569 is used to specify both source and
8570 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8571 instead if you just want to specify
8572 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8573 if you want to specify library paths
8574 only.
8576 @item
8577 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8578 This may conveniently be used to exclude standard libraries from
8579 consideration and in particular it means that the use of the
8580 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8581 unless @option{^-a^/ALL_FILES^} is also specified.
8583 @item
8584 @code{gnatmake} has been designed to make the use of Ada libraries
8585 particularly convenient. Assume you have an Ada library organized
8586 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8587 of your Ada compilation units,
8588 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8589 specs of these units, but no bodies. Then to compile a unit
8590 stored in @code{main.adb}, which uses this Ada library you would just type
8592 @smallexample
8593 @ifclear vms
8594 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8595 @end ifclear
8596 @ifset vms
8597 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8598            /SKIP_MISSING=@i{[OBJ_DIR]} main
8599 @end ifset
8600 @end smallexample
8602 @item
8603 Using @code{gnatmake} along with the
8604 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8605 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8606 this switch,
8607 you can update the comments/format of your
8608 source files without having to recompile everything. Note, however, that
8609 adding or deleting lines in a source files may render its debugging
8610 info obsolete. If the file in question is a spec, the impact is rather
8611 limited, as that debugging info will only be useful during the
8612 elaboration phase of your program. For bodies the impact can be more
8613 significant. In all events, your debugger will warn you if a source file
8614 is more recent than the corresponding object, and alert you to the fact
8615 that the debugging information may be out of date.
8616 @end itemize
8618 @node How gnatmake Works
8619 @section How @code{gnatmake} Works
8621 @noindent
8622 Generally @code{gnatmake} automatically performs all necessary
8623 recompilations and you don't need to worry about how it works. However,
8624 it may be useful to have some basic understanding of the @code{gnatmake}
8625 approach and in particular to understand how it uses the results of
8626 previous compilations without incorrectly depending on them.
8628 First a definition: an object file is considered @dfn{up to date} if the
8629 corresponding ALI file exists and if all the source files listed in the
8630 dependency section of this ALI file have time stamps matching those in
8631 the ALI file. This means that neither the source file itself nor any
8632 files that it depends on have been modified, and hence there is no need
8633 to recompile this file.
8635 @code{gnatmake} works by first checking if the specified main unit is up
8636 to date. If so, no compilations are required for the main unit. If not,
8637 @code{gnatmake} compiles the main program to build a new ALI file that
8638 reflects the latest sources. Then the ALI file of the main unit is
8639 examined to find all the source files on which the main program depends,
8640 and @code{gnatmake} recursively applies the above procedure on all these files.
8642 This process ensures that @code{gnatmake} only trusts the dependencies
8643 in an existing ALI file if they are known to be correct. Otherwise it
8644 always recompiles to determine a new, guaranteed accurate set of
8645 dependencies. As a result the program is compiled ``upside down'' from what may
8646 be more familiar as the required order of compilation in some other Ada
8647 systems. In particular, clients are compiled before the units on which
8648 they depend. The ability of GNAT to compile in any order is critical in
8649 allowing an order of compilation to be chosen that guarantees that
8650 @code{gnatmake} will recompute a correct set of new dependencies if
8651 necessary.
8653 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8654 imported by several of the executables, it will be recompiled at most once.
8656 Note: when using non-standard naming conventions
8657 (See @ref{Using Other File Names}), changing through a configuration pragmas
8658 file the version of a source and invoking @code{gnatmake} to recompile may
8659 have no effect, if the previous version of the source is still accessible
8660 by @code{gnatmake}. It may be necessary to use the switch ^-f^/FORCE_COMPILE^.
8662 @node Examples of gnatmake Usage
8663 @section Examples of @code{gnatmake} Usage
8665 @table @code
8666 @item gnatmake hello.adb
8667 Compile all files necessary to bind and link the main program
8668 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8669 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8671 @item gnatmake main1 main2 main3
8672 Compile all files necessary to bind and link the main programs
8673 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8674 (containing unit @code{Main2}) and @file{main3.adb}
8675 (containing unit @code{Main3}) and bind and link the resulting object files
8676 to generate three executable files @file{^main1^MAIN1.EXE^},
8677 @file{^main2^MAIN2.EXE^}
8678 and @file{^main3^MAIN3.EXE^}.
8680 @ifclear vms
8681 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8682 @end ifclear
8684 @ifset vms
8685 @item gnatmake Main_Unit /QUIET
8686    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8687    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8688 @end ifset
8689 Compile all files necessary to bind and link the main program unit
8690 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8691 be done with optimization level 2 and the order of elaboration will be
8692 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8693 displaying commands it is executing.
8694 @end table
8696 @c *************************
8697 @node Improving Performance
8698 @chapter Improving Performance
8699 @cindex Improving performance
8701 @noindent
8702 This chapter presents several topics related to program performance.
8703 It first describes some of the tradeoffs that need to be considered
8704 and some of the techniques for making your program run faster.
8705 It then documents the @command{gnatelim} tool, which can reduce
8706 the size of program executables.
8708 @ifnottex
8709 @menu
8710 * Performance Considerations::
8711 * Reducing the Size of Ada Executables with gnatelim::
8712 @end menu
8713 @end ifnottex
8715 @c *****************************
8716 @node Performance Considerations
8717 @section Performance Considerations
8719 @noindent
8720 The GNAT system provides a number of options that allow a trade-off
8721 between
8723 @itemize @bullet
8724 @item
8725 performance of the generated code
8727 @item
8728 speed of compilation
8730 @item
8731 minimization of dependences and recompilation
8733 @item
8734 the degree of run-time checking.
8735 @end itemize
8737 @noindent
8738 The defaults (if no options are selected) aim at improving the speed
8739 of compilation and minimizing dependences, at the expense of performance
8740 of the generated code:
8742 @itemize @bullet
8743 @item
8744 no optimization
8746 @item
8747 no inlining of subprogram calls
8749 @item
8750 all run-time checks enabled except overflow and elaboration checks
8751 @end itemize
8753 @noindent
8754 These options are suitable for most program development purposes. This
8755 chapter describes how you can modify these choices, and also provides
8756 some guidelines on debugging optimized code.
8758 @menu
8759 * Controlling Run-Time Checks::
8760 * Use of Restrictions::
8761 * Optimization Levels::
8762 * Debugging Optimized Code::
8763 * Inlining of Subprograms::
8764 * Optimization and Strict Aliasing::
8765 @ifset vms
8766 * Coverage Analysis::
8767 @end ifset
8768 @end menu
8770 @node Controlling Run-Time Checks
8771 @subsection Controlling Run-Time Checks
8773 @noindent
8774 By default, GNAT generates all run-time checks, except arithmetic overflow
8775 checking for integer operations and checks for access before elaboration on
8776 subprogram calls. The latter are not required in default mode, because all
8777 necessary checking is done at compile time.
8778 @cindex @option{-gnatp} (@code{gcc})
8779 @cindex @option{-gnato} (@code{gcc})
8780 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8781 be modified. @xref{Run-Time Checks}.
8783 Our experience is that the default is suitable for most development
8784 purposes.
8786 We treat integer overflow specially because these
8787 are quite expensive and in our experience are not as important as other
8788 run-time checks in the development process. Note that division by zero
8789 is not considered an overflow check, and divide by zero checks are
8790 generated where required by default.
8792 Elaboration checks are off by default, and also not needed by default, since
8793 GNAT uses a static elaboration analysis approach that avoids the need for
8794 run-time checking. This manual contains a full chapter discussing the issue
8795 of elaboration checks, and if the default is not satisfactory for your use,
8796 you should read this chapter.
8798 For validity checks, the minimal checks required by the Ada Reference
8799 Manual (for case statements and assignments to array elements) are on
8800 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8801 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8802 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8803 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8804 are also suppressed entirely if @option{-gnatp} is used.
8806 @cindex Overflow checks
8807 @cindex Checks, overflow
8808 @findex Suppress
8809 @findex Unsuppress
8810 @cindex pragma Suppress
8811 @cindex pragma Unsuppress
8812 Note that the setting of the switches controls the default setting of
8813 the checks. They may be modified using either @code{pragma Suppress} (to
8814 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8815 checks) in the program source.
8817 @node Use of Restrictions
8818 @subsection Use of Restrictions
8820 @noindent
8821 The use of pragma Restrictions allows you to control which features are
8822 permitted in your program. Apart from the obvious point that if you avoid
8823 relatively expensive features like finalization (enforceable by the use
8824 of pragma Restrictions (No_Finalization), the use of this pragma does not
8825 affect the generated code in most cases.
8827 One notable exception to this rule is that the possibility of task abort
8828 results in some distributed overhead, particularly if finalization or
8829 exception handlers are used. The reason is that certain sections of code
8830 have to be marked as non-abortable.
8832 If you use neither the @code{abort} statement, nor asynchronous transfer
8833 of control (@code{select .. then abort}), then this distributed overhead
8834 is removed, which may have a general positive effect in improving
8835 overall performance.  Especially code involving frequent use of tasking
8836 constructs and controlled types will show much improved performance.
8837 The relevant restrictions pragmas are
8839 @smallexample
8840    pragma Restrictions (No_Abort_Statements);
8841    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8842 @end smallexample
8844 @noindent
8845 It is recommended that these restriction pragmas be used if possible. Note
8846 that this also means that you can write code without worrying about the
8847 possibility of an immediate abort at any point.
8849 @node Optimization Levels
8850 @subsection Optimization Levels
8851 @cindex @option{^-O^/OPTIMIZE^} (@code{gcc})
8853 @noindent
8854 The default is optimization off. This results in the fastest compile
8855 times, but GNAT makes absolutely no attempt to optimize, and the
8856 generated programs are considerably larger and slower than when
8857 optimization is enabled. You can use the
8858 @ifclear vms
8859 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8860 @end ifclear
8861 @ifset vms
8862 @code{OPTIMIZE} qualifier
8863 @end ifset
8864 to @code{gcc} to control the optimization level:
8866 @table @option
8867 @item ^-O0^/OPTIMIZE=NONE^
8868 No optimization (the default);
8869 generates unoptimized code but has
8870 the fastest compilation time.
8872 @item ^-O1^/OPTIMIZE=SOME^
8873 Medium level optimization;
8874 optimizes reasonably well but does not
8875 degrade compilation time significantly.
8877 @item ^-O2^/OPTIMIZE=ALL^
8878 @ifset vms
8879 @itemx /OPTIMIZE=DEVELOPMENT
8880 @end ifset
8881 Full optimization;
8882 generates highly optimized code and has
8883 the slowest compilation time.
8885 @item ^-O3^/OPTIMIZE=INLINING^
8886 Full optimization as in @option{-O2},
8887 and also attempts automatic inlining of small
8888 subprograms within a unit (@pxref{Inlining of Subprograms}).
8889 @end table
8891 @noindent
8892 Higher optimization levels perform more global transformations on the
8893 program and apply more expensive analysis algorithms in order to generate
8894 faster and more compact code. The price in compilation time, and the
8895 resulting improvement in execution time,
8896 both depend on the particular application and the hardware environment.
8897 You should experiment to find the best level for your application.
8899 Since the precise set of optimizations done at each level will vary from
8900 release to release (and sometime from target to target), it is best to think
8901 of the optimization settings in general terms.
8902 The @cite{Using GNU GCC} manual contains details about
8903 ^the @option{-O} settings and a number of @option{-f} options that^how to^
8904 individually enable or disable specific optimizations.
8906 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8907 been tested extensively at all optimization levels. There are some bugs
8908 which appear only with optimization turned on, but there have also been
8909 bugs which show up only in @emph{unoptimized} code. Selecting a lower
8910 level of optimization does not improve the reliability of the code
8911 generator, which in practice is highly reliable at all optimization
8912 levels.
8914 Note regarding the use of @option{-O3}: The use of this optimization level
8915 is generally discouraged with GNAT, since it often results in larger
8916 executables which run more slowly. See further discussion of this point
8917 in @pxref{Inlining of Subprograms}.
8919 @node Debugging Optimized Code
8920 @subsection Debugging Optimized Code
8921 @cindex Debugging optimized code
8922 @cindex Optimization and debugging
8924 @noindent
8925 Although it is possible to do a reasonable amount of debugging at
8926 @ifclear vms
8927 non-zero optimization levels,
8928 the higher the level the more likely that
8929 @end ifclear
8930 @ifset vms
8931 @option{/OPTIMIZE} settings other than @code{NONE},
8932 such settings will make it more likely that
8933 @end ifset
8934 source-level constructs will have been eliminated by optimization.
8935 For example, if a loop is strength-reduced, the loop
8936 control variable may be completely eliminated and thus cannot be
8937 displayed in the debugger.
8938 This can only happen at @option{-O2} or @option{-O3}.
8939 Explicit temporary variables that you code might be eliminated at
8940 ^level^setting^ @option{-O1} or higher.
8942 The use of the @option{^-g^/DEBUG^} switch,
8943 @cindex @option{^-g^/DEBUG^} (@code{gcc})
8944 which is needed for source-level debugging,
8945 affects the size of the program executable on disk,
8946 and indeed the debugging information can be quite large.
8947 However, it has no effect on the generated code (and thus does not
8948 degrade performance)
8950 Since the compiler generates debugging tables for a compilation unit before
8951 it performs optimizations, the optimizing transformations may invalidate some
8952 of the debugging data.  You therefore need to anticipate certain
8953 anomalous situations that may arise while debugging optimized code.
8954 These are the most common cases:
8956 @enumerate
8957 @item
8958 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
8959 commands show
8960 the PC bouncing back and forth in the code.  This may result from any of
8961 the following optimizations:
8963 @itemize @bullet
8964 @item
8965 @i{Common subexpression elimination:} using a single instance of code for a
8966 quantity that the source computes several times.  As a result you
8967 may not be able to stop on what looks like a statement.
8969 @item
8970 @i{Invariant code motion:} moving an expression that does not change within a
8971 loop, to the beginning of the loop.
8973 @item
8974 @i{Instruction scheduling:} moving instructions so as to
8975 overlap loads and stores (typically) with other code, or in
8976 general to move computations of values closer to their uses. Often
8977 this causes you to pass an assignment statement without the assignment
8978 happening and then later bounce back to the statement when the
8979 value is actually needed.  Placing a breakpoint on a line of code
8980 and then stepping over it may, therefore, not always cause all the
8981 expected side-effects.
8982 @end itemize
8984 @item
8985 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
8986 two identical pieces of code are merged and the program counter suddenly
8987 jumps to a statement that is not supposed to be executed, simply because
8988 it (and the code following) translates to the same thing as the code
8989 that @emph{was} supposed to be executed.  This effect is typically seen in
8990 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
8991 a @code{break} in a C @code{^switch^switch^} statement.
8993 @item
8994 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
8995 There are various reasons for this effect:
8997 @itemize @bullet
8998 @item
8999 In a subprogram prologue, a parameter may not yet have been moved to its
9000 ``home''.
9002 @item
9003 A variable may be dead, and its register re-used.  This is
9004 probably the most common cause.
9006 @item
9007 As mentioned above, the assignment of a value to a variable may
9008 have been moved.
9010 @item
9011 A variable may be eliminated entirely by value propagation or
9012 other means.  In this case, GCC may incorrectly generate debugging
9013 information for the variable
9014 @end itemize
9016 @noindent
9017 In general, when an unexpected value appears for a local variable or parameter
9018 you should first ascertain if that value was actually computed by
9019 your program, as opposed to being incorrectly reported by the debugger.
9020 Record fields or
9021 array elements in an object designated by an access value
9022 are generally less of a problem, once you have ascertained that the access
9023 value is sensible.
9024 Typically, this means checking variables in the preceding code and in the
9025 calling subprogram to verify that the value observed is explainable from other
9026 values (one must apply the procedure recursively to those
9027 other values); or re-running the code and stopping a little earlier
9028 (perhaps before the call) and stepping to better see how the variable obtained
9029 the value in question; or continuing to step @emph{from} the point of the
9030 strange value to see if code motion had simply moved the variable's
9031 assignments later.
9032 @end enumerate
9034 @noindent
9035 In light of such anomalies, a recommended technique is to use @option{-O0}
9036 early in the software development cycle, when extensive debugging capabilities
9037 are most needed, and then move to @option{-O1} and later @option{-O2} as
9038 the debugger becomes less critical.
9039 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9040 a release management issue.
9041 @ifclear vms
9042 Note that if you use @option{-g} you can then use the @command{strip} program
9043 on the resulting executable,
9044 which removes both debugging information and global symbols.
9045 @end ifclear
9047 @node Inlining of Subprograms
9048 @subsection Inlining of Subprograms
9050 @noindent
9051 A call to a subprogram in the current unit is inlined if all the
9052 following conditions are met:
9054 @itemize @bullet
9055 @item
9056 The optimization level is at least @option{-O1}.
9058 @item
9059 The called subprogram is suitable for inlining: It must be small enough
9060 and not contain nested subprograms or anything else that @code{gcc}
9061 cannot support in inlined subprograms.
9063 @item
9064 The call occurs after the definition of the body of the subprogram.
9066 @item
9067 @cindex pragma Inline
9068 @findex Inline
9069 Either @code{pragma Inline} applies to the subprogram or it is
9070 small and automatic inlining (optimization level @option{-O3}) is
9071 specified.
9072 @end itemize
9074 @noindent
9075 Calls to subprograms in @code{with}'ed units are normally not inlined.
9076 To achieve this level of inlining, the following conditions must all be
9077 true:
9079 @itemize @bullet
9080 @item
9081 The optimization level is at least @option{-O1}.
9083 @item
9084 The called subprogram is suitable for inlining: It must be small enough
9085 and not contain nested subprograms or anything else @code{gcc} cannot
9086 support in inlined subprograms.
9088 @item
9089 The call appears in a body (not in a package spec).
9091 @item
9092 There is a @code{pragma Inline} for the subprogram.
9094 @item
9095 @cindex @option{-gnatn} (@code{gcc})
9096 The @option{^-gnatn^/INLINE^} switch
9097 is used in the @code{gcc} command line
9098 @end itemize
9100 Note that specifying the @option{-gnatn} switch causes additional
9101 compilation dependencies. Consider the following:
9103 @smallexample @c ada
9104 @cartouche
9105 package R is
9106    procedure Q;
9107    pragma Inline (Q);
9108 end R;
9109 package body R is
9110    ...
9111 end R;
9113 with R;
9114 procedure Main is
9115 begin
9116    ...
9117    R.Q;
9118 end Main;
9119 @end cartouche
9120 @end smallexample
9122 @noindent
9123 With the default behavior (no @option{-gnatn} switch specified), the
9124 compilation of the @code{Main} procedure depends only on its own source,
9125 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9126 means that editing the body of @code{R} does not require recompiling
9127 @code{Main}.
9129 On the other hand, the call @code{R.Q} is not inlined under these
9130 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9131 is compiled, the call will be inlined if the body of @code{Q} is small
9132 enough, but now @code{Main} depends on the body of @code{R} in
9133 @file{r.adb} as well as on the spec. This means that if this body is edited,
9134 the main program must be recompiled. Note that this extra dependency
9135 occurs whether or not the call is in fact inlined by @code{gcc}.
9137 The use of front end inlining with @option{-gnatN} generates similar
9138 additional dependencies.
9140 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
9141 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9142 can be used to prevent
9143 all inlining. This switch overrides all other conditions and ensures
9144 that no inlining occurs. The extra dependences resulting from
9145 @option{-gnatn} will still be active, even if
9146 this switch is used to suppress the resulting inlining actions.
9148 Note regarding the use of @option{-O3}: There is no difference in inlining
9149 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9150 pragma @code{Inline} assuming the use of @option{-gnatn}
9151 or @option{-gnatN} (the switches that activate inlining). If you have used
9152 pragma @code{Inline} in appropriate cases, then it is usually much better
9153 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9154 in this case only has the effect of inlining subprograms you did not
9155 think should be inlined. We often find that the use of @option{-O3} slows
9156 down code by performing excessive inlining, leading to increased instruction
9157 cache pressure from the increased code size. So the bottom line here is
9158 that you should not automatically assume that @option{-O3} is better than
9159 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9160 it actually improves performance.
9162 @node Optimization and Strict Aliasing
9163 @subsection Optimization and Strict Aliasing
9164 @cindex Aliasing
9165 @cindex Strict Aliasing
9166 @cindex No_Strict_Aliasing
9168 @noindent
9169 The strong typing capabilities of Ada allow an optimizer to generate
9170 efficient code in situations where other languages would be forced to
9171 make worst case assumptions preventing such optimizations. Consider
9172 the following example:
9174 @smallexample @c ada
9175 @cartouche
9176 procedure R is
9177    type Int1 is new Integer;
9178    type Int2 is new Integer;
9179    type Int1A is access Int1;
9180    type Int2A is access Int2;
9181    Int1V : Int1A;
9182    Int2V : Int2A;
9183    ...
9185 begin
9186    ...
9187    for J in Data'Range loop
9188       if Data (J) = Int1V.all then
9189          Int2V.all := Int2V.all + 1;
9190       end if;
9191    end loop;
9192    ...
9193 end R;
9194 @end cartouche
9195 @end smallexample
9197 @noindent
9198 In this example, since the variable @code{Int1V} can only access objects
9199 of type @code{Int1}, and @code{Int2V} can only access objects of type
9200 @code{Int2}, there is no possibility that the assignment to
9201 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9202 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9203 for all iterations of the loop and avoid the extra memory reference
9204 required to dereference it each time through the loop.
9206 This kind of optimziation, called strict aliasing analysis, is
9207 triggered by specifying an optimization level of @option{-O2} or
9208 higher and allows @code{GNAT} to generate more efficient code
9209 when access values are involved.
9211 However, although this optimization is always correct in terms of
9212 the formal semantics of the Ada Reference Manual, difficulties can
9213 arise if features like @code{Unchecked_Conversion} are used to break
9214 the typing system. Consider the following complete program example:
9216 @smallexample @c ada
9217 @cartouche
9218 package p1 is
9219    type int1 is new integer;
9220    type int2 is new integer;
9221    type a1 is access int1;
9222    type a2 is access int2;
9223 end p1;
9225 with p1; use p1;
9226 package p2 is
9227    function to_a2 (Input : a1) return a2;
9228 end p2;
9230 with Unchecked_Conversion;
9231 package body p2 is
9232    function to_a2 (Input : a1) return a2 is
9233       function to_a2u is
9234         new Unchecked_Conversion (a1, a2);
9235    begin
9236       return to_a2u (Input);
9237    end to_a2;
9238 end p2;
9240 with p2; use p2;
9241 with p1; use p1;
9242 with Text_IO; use Text_IO;
9243 procedure m is
9244    v1 : a1 := new int1;
9245    v2 : a2 := to_a2 (v1);
9246 begin
9247    v1.all := 1;
9248    v2.all := 0;
9249    put_line (int1'image (v1.all));
9250 end;
9251 @end cartouche
9252 @end smallexample
9254 @noindent
9255 This program prints out 0 in @code{-O0} or @code{-O1}
9256 mode, but it prints out 1 in @code{-O2} mode. That's
9257 because in strict aliasing mode, the compiler can and
9258 does assume that the assignment to @code{v2.all} could not
9259 affect the value of @code{v1.all}, since different types
9260 are involved.
9262 This behavior is not a case of non-conformance with the standard, since
9263 the Ada RM specifies that an unchecked conversion where the resulting
9264 bit pattern is not a correct value of the target type can result in an
9265 abnormal value and attempting to reference an abnormal value makes the
9266 execution of a program erroneous.  That's the case here since the result
9267 does not point to an object of type @code{int2}.  This means that the
9268 effect is entirely unpredictable.
9270 However, although that explanation may satisfy a language
9271 lawyer, in practice an applications programmer expects an
9272 unchecked conversion involving pointers to create true
9273 aliases and the behavior of printing 1 seems plain wrong.
9274 In this case, the strict aliasing optimization is unwelcome.
9276 Indeed the compiler recognizes this possibility, and the
9277 unchecked conversion generates a warning:
9279 @smallexample
9280 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9281 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9282 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9283 @end smallexample
9285 @noindent
9286 Unfortunately the problem is recognized when compiling the body of
9287 package @code{p2}, but the actual "bad" code is generated while
9288 compiling the body of @code{m} and this latter compilation does not see
9289 the suspicious @code{Unchecked_Conversion}.
9291 As implied by the warning message, there are approaches you can use to
9292 avoid the unwanted strict aliasing optimization in a case like this.
9294 One possibility is to simply avoid the use of @code{-O2}, but
9295 that is a bit drastic, since it throws away a number of useful
9296 optimizations that do not involve strict aliasing assumptions.
9298 A less drastic approach is to compile the program using the
9299 option @code{-fno-strict-aliasing}. Actually it is only the
9300 unit containing the dereferencing of the suspicious pointer
9301 that needs to be compiled. So in this case, if we compile
9302 unit @code{m} with this switch, then we get the expected
9303 value of zero printed. Analyzing which units might need
9304 the switch can be painful, so a more reasonable approach
9305 is to compile the entire program with options @code{-O2}
9306 and @code{-fno-strict-aliasing}. If the performance is
9307 satisfactory with this combination of options, then the
9308 advantage is that the entire issue of possible "wrong"
9309 optimization due to strict aliasing is avoided.
9311 To avoid the use of compiler switches, the configuration
9312 pragma @code{No_Strict_Aliasing} with no parameters may be
9313 used to specify that for all access types, the strict
9314 aliasing optimization should be suppressed.
9316 However, these approaches are still overkill, in that they causes
9317 all manipulations of all access values to be deoptimized. A more
9318 refined approach is to concentrate attention on the specific
9319 access type identified as problematic.
9321 First, if a careful analysis of uses of the pointer shows
9322 that there are no possible problematic references, then
9323 the warning can be suppressed by bracketing the
9324 instantiation of @code{Unchecked_Conversion} to turn
9325 the warning off:
9327 @smallexample @c ada
9328    pragma Warnings (Off);
9329    function to_a2u is
9330      new Unchecked_Conversion (a1, a2);
9331    pragma Warnings (On);
9332 @end smallexample
9334 @noindent
9335 Of course that approach is not appropriate for this particular
9336 example, since indeed there is a problematic reference. In this
9337 case we can take one of two other approaches.
9339 The first possibility is to move the instantiation of unchecked
9340 conversion to the unit in which the type is declared. In
9341 this example, we would move the instantiation of
9342 @code{Unchecked_Conversion} from the body of package
9343 @code{p2} to the spec of package @code{p1}. Now the
9344 warning disappears. That's because any use of the
9345 access type knows there is a suspicious unchecked
9346 conversion, and the strict aliasing optimization
9347 is automatically suppressed for the type.
9349 If it is not practical to move the unchecked conversion to the same unit
9350 in which the destination access type is declared (perhaps because the
9351 source type is not visible in that unit), you may use pragma
9352 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9353 same declarative sequence as the declaration of the access type:
9355 @smallexample @c ada
9356    type a2 is access int2;
9357    pragma No_Strict_Aliasing (a2);
9358 @end smallexample
9360 @noindent
9361 Here again, the compiler now knows that the strict aliasing optimization
9362 should be suppressed for any reference to type @code{a2} and the
9363 expected behavior is obtained.
9365 Finally, note that although the compiler can generate warnings for
9366 simple cases of unchecked conversions, there are tricker and more
9367 indirect ways of creating type incorrect aliases which the compiler
9368 cannot detect. Examples are the use of address overlays and unchecked
9369 conversions involving composite types containing access types as
9370 components. In such cases, no warnings are generated, but there can
9371 still be aliasing problems. One safe coding practice is to forbid the
9372 use of address clauses for type overlaying, and to allow unchecked
9373 conversion only for primitive types. This is not really a significant
9374 restriction since any possible desired effect can be achieved by
9375 unchecked conversion of access values.
9377 @ifset vms
9378 @node Coverage Analysis
9379 @subsection Coverage Analysis
9381 @noindent
9382 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9383 the user to determine the distribution of execution time across a program,
9384 @pxref{Profiling} for details of usage.
9385 @end ifset
9387 @node Reducing the Size of Ada Executables with gnatelim
9388 @section Reducing the Size of Ada Executables with @code{gnatelim}
9389 @findex gnatelim
9391 @noindent
9392 This section describes @command{gnatelim}, a tool which detects unused
9393 subprograms and helps the compiler to create a smaller executable for your
9394 program.
9396 @menu
9397 * About gnatelim::
9398 * Running gnatelim::
9399 * Correcting the List of Eliminate Pragmas::
9400 * Making Your Executables Smaller::
9401 * Summary of the gnatelim Usage Cycle::
9402 @end menu
9404 @node About gnatelim
9405 @subsection About @code{gnatelim}
9407 @noindent
9408 When a program shares a set of Ada
9409 packages with other programs, it may happen that this program uses
9410 only a fraction of the subprograms defined in these packages. The code
9411 created for these unused subprograms increases the size of the executable.
9413 @code{gnatelim} tracks unused subprograms in an Ada program and
9414 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9415 subprograms that are declared but never called. By placing the list of
9416 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9417 recompiling your program, you may decrease the size of its executable,
9418 because the compiler will not generate the code for 'eliminated' subprograms.
9419 See GNAT Reference Manual for more information about this pragma.
9421 @code{gnatelim} needs as its input data the name of the main subprogram
9422 and a bind file for a main subprogram.
9424 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9425 the main subprogram. @code{gnatelim} can work with both Ada and C
9426 bind files; when both are present, it uses the Ada bind file.
9427 The following commands will build the program and create the bind file:
9429 @smallexample
9430 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9431 $ gnatbind main_prog
9432 @end smallexample
9434 Note that @code{gnatelim} needs neither object nor ALI files.
9436 @node Running gnatelim
9437 @subsection Running @code{gnatelim}
9439 @noindent
9440 @code{gnatelim} has the following command-line interface:
9442 @smallexample
9443 $ gnatelim [options] name
9444 @end smallexample
9446 @noindent
9447 @code{name} should be a name of a source file that contains the main subprogram
9448 of a program (partition).
9450 @code{gnatelim} has the following switches:
9452 @table @option
9453 @c !sort!
9454 @item ^-q^/QUIET^
9455 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9456 Quiet mode: by default @code{gnatelim} outputs to the standard error
9457 stream the number of program units left to be processed. This option turns
9458 this trace off.
9460 @item ^-v^/VERBOSE^
9461 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9462 Verbose mode: @code{gnatelim} version information is printed as Ada
9463 comments to the standard output stream. Also, in addition to the number of
9464 program units left @code{gnatelim} will output the name of the current unit
9465 being processed.
9467 @item ^-a^/ALL^
9468 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9469 Also look for subprograms from the GNAT run time that can be eliminated. Note
9470 that when @file{gnat.adc} is produced using this switch, the entire program
9471 must be recompiled with switch @option{^-a^/ALL_FILES^} to @code{gnatmake}.
9473 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9474 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9475 When looking for source files also look in directory @var{dir}. Specifying
9476 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9477 sources in the current directory.
9479 @item ^-b^/BIND_FILE=^@var{bind_file}
9480 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9481 Specifies @var{bind_file} as the bind file to process. If not set, the name
9482 of the bind file is computed from the full expanded Ada name
9483 of a main subprogram.
9485 @item ^-C^/CONFIG_FILE=^@var{config_file}
9486 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9487 Specifies a file @var{config_file} that contains configuration pragmas. The
9488 file must be specified with full path.
9490 @item ^--GCC^/COMPILER^=@var{compiler_name}
9491 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9492 Instructs @code{gnatelim} to use specific @code{gcc} compiler instead of one
9493 available on the path.
9495 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9496 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9497 Instructs @code{gnatelim} to use specific @code{gnatmake} instead of one
9498 available on the path.
9499 @end table
9501 @noindent
9502 @code{gnatelim} sends its output to the standard output stream, and all the
9503 tracing and debug information is sent to the standard error stream.
9504 In order to produce a proper GNAT configuration file
9505 @file{gnat.adc}, redirection must be used:
9507 @smallexample
9508 @ifset vms
9509 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9510 @end ifset
9511 @ifclear vms
9512 $ gnatelim main_prog.adb > gnat.adc
9513 @end ifclear
9514 @end smallexample
9516 @ifclear vms
9517 @noindent
9520 @smallexample
9521 $ gnatelim main_prog.adb >> gnat.adc
9522 @end smallexample
9524 @noindent
9525 in order to append the @code{gnatelim} output to the existing contents of
9526 @file{gnat.adc}.
9527 @end ifclear
9529 @node Correcting the List of Eliminate Pragmas
9530 @subsection Correcting the List of Eliminate Pragmas
9532 @noindent
9533 In some rare cases @code{gnatelim} may try to eliminate
9534 subprograms that are actually called in the program. In this case, the
9535 compiler will generate an error message of the form:
9537 @smallexample
9538 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9539 @end smallexample
9541 @noindent
9542 You will need to manually remove the wrong @code{Eliminate} pragmas from
9543 the @file{gnat.adc} file. You should recompile your program
9544 from scratch after that, because you need a consistent @file{gnat.adc} file
9545 during the entire compilation.
9547 @node Making Your Executables Smaller
9548 @subsection Making Your Executables Smaller
9550 @noindent
9551 In order to get a smaller executable for your program you now have to
9552 recompile the program completely with the new @file{gnat.adc} file
9553 created by @code{gnatelim} in your current directory:
9555 @smallexample
9556 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9557 @end smallexample
9559 @noindent
9560 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9561 recompile everything
9562 with the set of pragmas @code{Eliminate} that you have obtained with
9563 @command{gnatelim}).
9565 Be aware that the set of @code{Eliminate} pragmas is specific to each
9566 program. It is not recommended to merge sets of @code{Eliminate}
9567 pragmas created for different programs in one @file{gnat.adc} file.
9569 @node Summary of the gnatelim Usage Cycle
9570 @subsection Summary of the gnatelim Usage Cycle
9572 @noindent
9573 Here is a quick summary of the steps to be taken in order to reduce
9574 the size of your executables with @code{gnatelim}. You may use
9575 other GNAT options to control the optimization level,
9576 to produce the debugging information, to set search path, etc.
9578 @enumerate
9579 @item
9580 Produce a bind file
9582 @smallexample
9583 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9584 $ gnatbind main_prog
9585 @end smallexample
9587 @item
9588 Generate a list of @code{Eliminate} pragmas
9589 @smallexample
9590 @ifset vms
9591 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9592 @end ifset
9593 @ifclear vms
9594 $ gnatelim main_prog >[>] gnat.adc
9595 @end ifclear
9596 @end smallexample
9598 @item
9599 Recompile the application
9601 @smallexample
9602 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9603 @end smallexample
9605 @end enumerate
9607 @c ********************************
9608 @node Renaming Files Using gnatchop
9609 @chapter Renaming Files Using @code{gnatchop}
9610 @findex gnatchop
9612 @noindent
9613 This chapter discusses how to handle files with multiple units by using
9614 the @code{gnatchop} utility. This utility is also useful in renaming
9615 files to meet the standard GNAT default file naming conventions.
9617 @menu
9618 * Handling Files with Multiple Units::
9619 * Operating gnatchop in Compilation Mode::
9620 * Command Line for gnatchop::
9621 * Switches for gnatchop::
9622 * Examples of gnatchop Usage::
9623 @end menu
9625 @node Handling Files with Multiple Units
9626 @section Handling Files with Multiple Units
9628 @noindent
9629 The basic compilation model of GNAT requires that a file submitted to the
9630 compiler have only one unit and there be a strict correspondence
9631 between the file name and the unit name.
9633 The @code{gnatchop} utility allows both of these rules to be relaxed,
9634 allowing GNAT to process files which contain multiple compilation units
9635 and files with arbitrary file names. @code{gnatchop}
9636 reads the specified file and generates one or more output files,
9637 containing one unit per file. The unit and the file name correspond,
9638 as required by GNAT.
9640 If you want to permanently restructure a set of ``foreign'' files so that
9641 they match the GNAT rules, and do the remaining development using the
9642 GNAT structure, you can simply use @command{gnatchop} once, generate the
9643 new set of files and work with them from that point on.
9645 Alternatively, if you want to keep your files in the ``foreign'' format,
9646 perhaps to maintain compatibility with some other Ada compilation
9647 system, you can set up a procedure where you use @command{gnatchop} each
9648 time you compile, regarding the source files that it writes as temporary
9649 files that you throw away.
9651 @node Operating gnatchop in Compilation Mode
9652 @section Operating gnatchop in Compilation Mode
9654 @noindent
9655 The basic function of @code{gnatchop} is to take a file with multiple units
9656 and split it into separate files. The boundary between files is reasonably
9657 clear, except for the issue of comments and pragmas. In default mode, the
9658 rule is that any pragmas between units belong to the previous unit, except
9659 that configuration pragmas always belong to the following unit. Any comments
9660 belong to the following unit. These rules
9661 almost always result in the right choice of
9662 the split point without needing to mark it explicitly and most users will
9663 find this default to be what they want. In this default mode it is incorrect to
9664 submit a file containing only configuration pragmas, or one that ends in
9665 configuration pragmas, to @code{gnatchop}.
9667 However, using a special option to activate ``compilation mode'',
9668 @code{gnatchop}
9669 can perform another function, which is to provide exactly the semantics
9670 required by the RM for handling of configuration pragmas in a compilation.
9671 In the absence of configuration pragmas (at the main file level), this
9672 option has no effect, but it causes such configuration pragmas to be handled
9673 in a quite different manner.
9675 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9676 only configuration pragmas, then this file is appended to the
9677 @file{gnat.adc} file in the current directory. This behavior provides
9678 the required behavior described in the RM for the actions to be taken
9679 on submitting such a file to the compiler, namely that these pragmas
9680 should apply to all subsequent compilations in the same compilation
9681 environment. Using GNAT, the current directory, possibly containing a
9682 @file{gnat.adc} file is the representation
9683 of a compilation environment. For more information on the
9684 @file{gnat.adc} file, see the section on handling of configuration
9685 pragmas @pxref{Handling of Configuration Pragmas}.
9687 Second, in compilation mode, if @code{gnatchop}
9688 is given a file that starts with
9689 configuration pragmas, and contains one or more units, then these
9690 configuration pragmas are prepended to each of the chopped files. This
9691 behavior provides the required behavior described in the RM for the
9692 actions to be taken on compiling such a file, namely that the pragmas
9693 apply to all units in the compilation, but not to subsequently compiled
9694 units.
9696 Finally, if configuration pragmas appear between units, they are appended
9697 to the previous unit. This results in the previous unit being illegal,
9698 since the compiler does not accept configuration pragmas that follow
9699 a unit. This provides the required RM behavior that forbids configuration
9700 pragmas other than those preceding the first compilation unit of a
9701 compilation.
9703 For most purposes, @code{gnatchop} will be used in default mode. The
9704 compilation mode described above is used only if you need exactly
9705 accurate behavior with respect to compilations, and you have files
9706 that contain multiple units and configuration pragmas. In this
9707 circumstance the use of @code{gnatchop} with the compilation mode
9708 switch provides the required behavior, and is for example the mode
9709 in which GNAT processes the ACVC tests.
9711 @node Command Line for gnatchop
9712 @section Command Line for @code{gnatchop}
9714 @noindent
9715 The @code{gnatchop} command has the form:
9717 @smallexample
9718 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9719       [@var{directory}]
9720 @end smallexample
9722 @noindent
9723 The only required argument is the file name of the file to be chopped.
9724 There are no restrictions on the form of this file name. The file itself
9725 contains one or more Ada units, in normal GNAT format, concatenated
9726 together. As shown, more than one file may be presented to be chopped.
9728 When run in default mode, @code{gnatchop} generates one output file in
9729 the current directory for each unit in each of the files.
9731 @var{directory}, if specified, gives the name of the directory to which
9732 the output files will be written. If it is not specified, all files are
9733 written to the current directory.
9735 For example, given a
9736 file called @file{hellofiles} containing
9738 @smallexample @c ada
9739 @group
9740 @cartouche
9741 procedure hello;
9743 with Text_IO; use Text_IO;
9744 procedure hello is
9745 begin
9746    Put_Line ("Hello");
9747 end hello;
9748 @end cartouche
9749 @end group
9750 @end smallexample
9752 @noindent
9753 the command
9755 @smallexample
9756 $ gnatchop ^hellofiles^HELLOFILES.^
9757 @end smallexample
9759 @noindent
9760 generates two files in the current directory, one called
9761 @file{hello.ads} containing the single line that is the procedure spec,
9762 and the other called @file{hello.adb} containing the remaining text. The
9763 original file is not affected. The generated files can be compiled in
9764 the normal manner.
9766 @noindent
9767 When gnatchop is invoked on a file that is empty or that contains only empty
9768 lines and/or comments, gnatchop will not fail, but will not produce any
9769 new sources.
9771 For example, given a
9772 file called @file{toto.txt} containing
9774 @smallexample @c ada
9775 @group
9776 @cartouche
9777 --  Just a comment
9778 @end cartouche
9779 @end group
9780 @end smallexample
9782 @noindent
9783 the command
9785 @smallexample
9786 $ gnatchop ^toto.txt^TOT.TXT^
9787 @end smallexample
9789 @noindent
9790 will not produce any new file and will result in the following warnings:
9792 @smallexample
9793 toto.txt:1:01: warning: empty file, contains no compilation units
9794 no compilation units found
9795 no source files written
9796 @end smallexample
9798 @node Switches for gnatchop
9799 @section Switches for @code{gnatchop}
9801 @noindent
9802 @command{gnatchop} recognizes the following switches:
9804 @table @option
9805 @c !sort!
9807 @item ^-c^/COMPILATION^
9808 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9809 Causes @code{gnatchop} to operate in compilation mode, in which
9810 configuration pragmas are handled according to strict RM rules. See
9811 previous section for a full description of this mode.
9813 @ifclear vms
9814 @item -gnatxxx
9815 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9816 used to parse the given file. Not all @code{xxx} options make sense,
9817 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9818 process a source file that uses Latin-2 coding for identifiers.
9819 @end ifclear
9821 @item ^-h^/HELP^
9822 Causes @code{gnatchop} to generate a brief help summary to the standard
9823 output file showing usage information.
9825 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9826 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9827 Limit generated file names to the specified number @code{mm}
9828 of characters.
9829 This is useful if the
9830 resulting set of files is required to be interoperable with systems
9831 which limit the length of file names.
9832 @ifset vms
9833 If no value is given, or
9834 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9835 a default of 39, suitable for OpenVMS Alpha
9836 Systems, is assumed
9837 @end ifset
9838 @ifclear vms
9839 No space is allowed between the @option{-k} and the numeric value. The numeric
9840 value may be omitted in which case a default of @option{-k8},
9841 suitable for use
9842 with DOS-like file systems, is used. If no @option{-k} switch
9843 is present then
9844 there is no limit on the length of file names.
9845 @end ifclear
9847 @item ^-p^/PRESERVE^
9848 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9849 Causes the file ^modification^creation^ time stamp of the input file to be
9850 preserved and used for the time stamp of the output file(s). This may be
9851 useful for preserving coherency of time stamps in an environment where
9852 @code{gnatchop} is used as part of a standard build process.
9854 @item ^-q^/QUIET^
9855 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
9856 Causes output of informational messages indicating the set of generated
9857 files to be suppressed. Warnings and error messages are unaffected.
9859 @item ^-r^/REFERENCE^
9860 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9861 @findex Source_Reference
9862 Generate @code{Source_Reference} pragmas. Use this switch if the output
9863 files are regarded as temporary and development is to be done in terms
9864 of the original unchopped file. This switch causes
9865 @code{Source_Reference} pragmas to be inserted into each of the
9866 generated files to refers back to the original file name and line number.
9867 The result is that all error messages refer back to the original
9868 unchopped file.
9869 In addition, the debugging information placed into the object file (when
9870 the @option{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified)
9871 also refers back to this original file so that tools like profilers and
9872 debuggers will give information in terms of the original unchopped file.
9874 If the original file to be chopped itself contains
9875 a @code{Source_Reference}
9876 pragma referencing a third file, then gnatchop respects
9877 this pragma, and the generated @code{Source_Reference} pragmas
9878 in the chopped file refer to the original file, with appropriate
9879 line numbers. This is particularly useful when @code{gnatchop}
9880 is used in conjunction with @code{gnatprep} to compile files that
9881 contain preprocessing statements and multiple units.
9883 @item ^-v^/VERBOSE^
9884 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9885 Causes @code{gnatchop} to operate in verbose mode. The version
9886 number and copyright notice are output, as well as exact copies of
9887 the gnat1 commands spawned to obtain the chop control information.
9889 @item ^-w^/OVERWRITE^
9890 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9891 Overwrite existing file names. Normally @code{gnatchop} regards it as a
9892 fatal error if there is already a file with the same name as a
9893 file it would otherwise output, in other words if the files to be
9894 chopped contain duplicated units. This switch bypasses this
9895 check, and causes all but the last instance of such duplicated
9896 units to be skipped.
9898 @ifclear vms
9899 @item --GCC=xxxx
9900 @cindex @option{--GCC=} (@code{gnatchop})
9901 Specify the path of the GNAT parser to be used. When this switch is used,
9902 no attempt is made to add the prefix to the GNAT parser executable.
9903 @end ifclear
9904 @end table
9906 @node Examples of gnatchop Usage
9907 @section Examples of @code{gnatchop} Usage
9909 @table @code
9910 @ifset vms
9911 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
9912 @end ifset
9913 @ifclear vms
9914 @item gnatchop -w hello_s.ada prerelease/files
9915 @end ifclear
9917 Chops the source file @file{hello_s.ada}. The output files will be
9918 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
9919 overwriting any
9920 files with matching names in that directory (no files in the current
9921 directory are modified).
9923 @item gnatchop ^archive^ARCHIVE.^
9924 Chops the source file @file{^archive^ARCHIVE.^}
9925 into the current directory. One
9926 useful application of @code{gnatchop} is in sending sets of sources
9927 around, for example in email messages. The required sources are simply
9928 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
9929 command), and then
9930 @code{gnatchop} is used at the other end to reconstitute the original
9931 file names.
9933 @item gnatchop file1 file2 file3 direc
9934 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
9935 the resulting files in the directory @file{direc}. Note that if any units
9936 occur more than once anywhere within this set of files, an error message
9937 is generated, and no files are written. To override this check, use the
9938 @option{^-w^/OVERWRITE^} switch,
9939 in which case the last occurrence in the last file will
9940 be the one that is output, and earlier duplicate occurrences for a given
9941 unit will be skipped.
9942 @end table
9944 @node Configuration Pragmas
9945 @chapter Configuration Pragmas
9946 @cindex Configuration pragmas
9947 @cindex Pragmas, configuration
9949 @noindent
9950 In Ada 95, configuration pragmas include those pragmas described as
9951 such in the Ada 95 Reference Manual, as well as
9952 implementation-dependent pragmas that are configuration pragmas. See the
9953 individual descriptions of pragmas in the GNAT Reference Manual for
9954 details on these additional GNAT-specific configuration pragmas. Most
9955 notably, the pragma @code{Source_File_Name}, which allows
9956 specifying non-default names for source files, is a configuration
9957 pragma. The following is a complete list of configuration pragmas
9958 recognized by @code{GNAT}:
9960 @smallexample
9961    Ada_83
9962    Ada_95
9963    C_Pass_By_Copy
9964    Component_Alignment
9965    Detect_Blocking
9966    Discard_Names
9967    Elaboration_Checks
9968    Eliminate
9969    Extend_System
9970    Extensions_Allowed
9971    External_Name_Casing
9972    Float_Representation
9973    Initialize_Scalars
9974    License
9975    Locking_Policy
9976    Long_Float
9977    Normalize_Scalars
9978    Polling
9979    Profile
9980    Profile_Warnings
9981    Propagate_Exceptions
9982    Queuing_Policy
9983    Ravenscar
9984    Restricted_Run_Time
9985    Restrictions
9986    Restrictions_Warnings
9987    Reviewable
9988    Source_File_Name
9989    Style_Checks
9990    Suppress
9991    Task_Dispatching_Policy
9992    Universal_Data
9993    Unsuppress
9994    Use_VADS_Size
9995    Warnings
9996    Validity_Checks
9997 @end smallexample
9999 @menu
10000 * Handling of Configuration Pragmas::
10001 * The Configuration Pragmas Files::
10002 @end menu
10004 @node Handling of Configuration Pragmas
10005 @section Handling of Configuration Pragmas
10007 Configuration pragmas may either appear at the start of a compilation
10008 unit, in which case they apply only to that unit, or they may apply to
10009 all compilations performed in a given compilation environment.
10011 GNAT also provides the @code{gnatchop} utility to provide an automatic
10012 way to handle configuration pragmas following the semantics for
10013 compilations (that is, files with multiple units), described in the RM.
10014 See section @pxref{Operating gnatchop in Compilation Mode} for details.
10015 However, for most purposes, it will be more convenient to edit the
10016 @file{gnat.adc} file that contains configuration pragmas directly,
10017 as described in the following section.
10019 @node The Configuration Pragmas Files
10020 @section The Configuration Pragmas Files
10021 @cindex @file{gnat.adc}
10023 @noindent
10024 In GNAT a compilation environment is defined by the current
10025 directory at the time that a compile command is given. This current
10026 directory is searched for a file whose name is @file{gnat.adc}. If
10027 this file is present, it is expected to contain one or more
10028 configuration pragmas that will be applied to the current compilation.
10029 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10030 considered.
10032 Configuration pragmas may be entered into the @file{gnat.adc} file
10033 either by running @code{gnatchop} on a source file that consists only of
10034 configuration pragmas, or more conveniently  by
10035 direct editing of the @file{gnat.adc} file, which is a standard format
10036 source file.
10038 In addition to @file{gnat.adc}, one additional file containing configuration
10039 pragmas may be applied to the current compilation using the switch
10040 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10041 contains only configuration pragmas. These configuration pragmas are
10042 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10043 is present and switch @option{-gnatA} is not used).
10045 It is allowed to specify several switches @option{-gnatec}, however only
10046 the last one on the command line will be taken into account.
10048 If you are using project file, a separate mechanism is provided using
10049 project attributes, see @ref{Specifying Configuration Pragmas} for more
10050 details.
10052 @ifset vms
10053 Of special interest to GNAT OpenVMS Alpha is the following
10054 configuration pragma:
10056 @smallexample @c ada
10057 @cartouche
10058 pragma Extend_System (Aux_DEC);
10059 @end cartouche
10060 @end smallexample
10062 @noindent
10063 In the presence of this pragma, GNAT adds to the definition of the
10064 predefined package SYSTEM all the additional types and subprograms that are
10065 defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
10066 @end ifset
10068 @node Handling Arbitrary File Naming Conventions Using gnatname
10069 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10070 @cindex Arbitrary File Naming Conventions
10072 @menu
10073 * Arbitrary File Naming Conventions::
10074 * Running gnatname::
10075 * Switches for gnatname::
10076 * Examples of gnatname Usage::
10077 @end menu
10079 @node Arbitrary File Naming Conventions
10080 @section Arbitrary File Naming Conventions
10082 @noindent
10083 The GNAT compiler must be able to know the source file name of a compilation
10084 unit.  When using the standard GNAT default file naming conventions
10085 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10086 does not need additional information.
10088 @noindent
10089 When the source file names do not follow the standard GNAT default file naming
10090 conventions, the GNAT compiler must be given additional information through
10091 a configuration pragmas file (see @ref{Configuration Pragmas})
10092 or a project file.
10093 When the non standard file naming conventions are well-defined,
10094 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10095 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
10096 if the file naming conventions are irregular or arbitrary, a number
10097 of pragma @code{Source_File_Name} for individual compilation units
10098 must be defined.
10099 To help maintain the correspondence between compilation unit names and
10100 source file names within the compiler,
10101 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10102 set of files.
10104 @node Running gnatname
10105 @section Running @code{gnatname}
10107 @noindent
10108 The usual form of the @code{gnatname} command is
10110 @smallexample
10111 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10112 @end smallexample
10114 @noindent
10115 All of the arguments are optional. If invoked without any argument,
10116 @code{gnatname} will display its usage.
10118 @noindent
10119 When used with at least one naming pattern, @code{gnatname} will attempt to
10120 find all the compilation units in files that follow at least one of the
10121 naming patterns. To find these compilation units,
10122 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10123 regular files.
10125 @noindent
10126 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10127 Each Naming Pattern is enclosed between double quotes.
10128 A Naming Pattern is a regular expression similar to the wildcard patterns
10129 used in file names by the Unix shells or the DOS prompt.
10131 @noindent
10132 Examples of Naming Patterns are
10134 @smallexample
10135    "*.[12].ada"
10136    "*.ad[sb]*"
10137    "body_*"    "spec_*"
10138 @end smallexample
10140 @noindent
10141 For a more complete description of the syntax of Naming Patterns,
10142 see the second kind of regular expressions described in @file{g-regexp.ads}
10143 (the ``Glob'' regular expressions).
10145 @noindent
10146 When invoked with no switches, @code{gnatname} will create a configuration
10147 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10148 @code{Source_File_Name} for each file that contains a valid Ada unit.
10150 @node Switches for gnatname
10151 @section Switches for @code{gnatname}
10153 @noindent
10154 Switches for @code{gnatname} must precede any specified Naming Pattern.
10156 @noindent
10157 You may specify any of the following switches to @code{gnatname}:
10159 @table @option
10160 @c !sort!
10162 @item ^-c^/CONFIG_FILE=^@file{file}
10163 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10164 Create a configuration pragmas file @file{file} (instead of the default
10165 @file{gnat.adc}).
10166 @ifclear vms
10167 There may be zero, one or more space between @option{-c} and
10168 @file{file}.
10169 @end ifclear
10170 @file{file} may include directory information. @file{file} must be
10171 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10172 When a switch @option{^-c^/CONFIG_FILE^} is
10173 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10175 @item ^-d^/SOURCE_DIRS=^@file{dir}
10176 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10177 Look for source files in directory @file{dir}. There may be zero, one or more
10178 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10179 When a switch @option{^-d^/SOURCE_DIRS^}
10180 is specified, the current working directory will not be searched for source
10181 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10182 or @option{^-D^/DIR_FILES^} switch.
10183 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10184 If @file{dir} is a relative path, it is relative to the directory of
10185 the configuration pragmas file specified with switch
10186 @option{^-c^/CONFIG_FILE^},
10187 or to the directory of the project file specified with switch
10188 @option{^-P^/PROJECT_FILE^} or,
10189 if neither switch @option{^-c^/CONFIG_FILE^}
10190 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10191 current working directory. The directory
10192 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10194 @item ^-D^/DIRS_FILE=^@file{file}
10195 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10196 Look for source files in all directories listed in text file @file{file}.
10197 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10198 and @file{file}.
10199 @file{file} must be an existing, readable text file.
10200 Each non empty line in @file{file} must be a directory.
10201 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10202 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10203 @file{file}.
10205 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10206 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10207 Foreign patterns. Using this switch, it is possible to add sources of languages
10208 other than Ada to the list of sources of a project file.
10209 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10210 For example,
10211 @smallexample
10212 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10213 @end smallexample
10214 @noindent
10215 will look for Ada units in all files with the @file{.ada} extension,
10216 and will add to the list of file for project @file{prj.gpr} the C files
10217 with extension ".^c^C^".
10219 @item ^-h^/HELP^
10220 @cindex @option{^-h^/HELP^} (@code{gnatname})
10221 Output usage (help) information. The output is written to @file{stdout}.
10223 @item ^-P^/PROJECT_FILE=^@file{proj}
10224 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10225 Create or update project file @file{proj}. There may be zero, one or more space
10226 between @option{-P} and @file{proj}. @file{proj} may include directory
10227 information. @file{proj} must be writable.
10228 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10229 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10230 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10232 @item ^-v^/VERBOSE^
10233 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10234 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10235 This includes name of the file written, the name of the directories to search
10236 and, for each file in those directories whose name matches at least one of
10237 the Naming Patterns, an indication of whether the file contains a unit,
10238 and if so the name of the unit.
10240 @item ^-v -v^/VERBOSE /VERBOSE^
10241 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10242 Very Verbose mode. In addition to the output produced in verbose mode,
10243 for each file in the searched directories whose name matches none of
10244 the Naming Patterns, an indication is given that there is no match.
10246 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10247 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10248 Excluded patterns. Using this switch, it is possible to exclude some files
10249 that would match the name patterns. For example,
10250 @smallexample
10251 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10252 @end smallexample
10253 @noindent
10254 will look for Ada units in all files with the @file{.ada} extension,
10255 except those whose names end with @file{_nt.ada}.
10257 @end table
10259 @node Examples of gnatname Usage
10260 @section Examples of @code{gnatname} Usage
10262 @ifset vms
10263 @smallexample
10264 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10265 @end smallexample
10266 @end ifset
10268 @ifclear vms
10269 @smallexample
10270 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10271 @end smallexample
10272 @end ifclear
10274 @noindent
10275 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10276 and be writable. In addition, the directory
10277 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10278 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10280 @ifclear vms
10281 Note the optional spaces after @option{-c} and @option{-d}.
10282 @end ifclear
10284 @smallexample
10285 @ifclear vms
10286 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10287   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10288 @end ifclear
10289 @ifset vms
10290 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10291   /EXCLUDED_PATTERN=*_nt_body.ada
10292   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10293   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10294 @end ifset
10295 @end smallexample
10297 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10298 even in conjunction with one or several switches
10299 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10300 are used in this example.
10302 @c *****************************************
10303 @c * G N A T  P r o j e c t  M a n a g e r *
10304 @c *****************************************
10305 @node GNAT Project Manager
10306 @chapter GNAT Project Manager
10308 @menu
10309 * Introduction::
10310 * Examples of Project Files::
10311 * Project File Syntax::
10312 * Objects and Sources in Project Files::
10313 * Importing Projects::
10314 * Project Extension::
10315 * Project Hierarchy Extension::
10316 * External References in Project Files::
10317 * Packages in Project Files::
10318 * Variables from Imported Projects::
10319 * Naming Schemes::
10320 * Library Projects::
10321 * Using Third-Party Libraries through Projects::
10322 * Stand-alone Library Projects::
10323 * Switches Related to Project Files::
10324 * Tools Supporting Project Files::
10325 * An Extended Example::
10326 * Project File Complete Syntax::
10327 @end menu
10329 @c ****************
10330 @c * Introduction *
10331 @c ****************
10333 @node Introduction
10334 @section Introduction
10336 @noindent
10337 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10338 you to manage complex builds involving a number of source files, directories,
10339 and compilation options for different system configurations. In particular,
10340 project files allow you to specify:
10341 @itemize @bullet
10342 @item
10343 The directory or set of directories containing the source files, and/or the
10344 names of the specific source files themselves
10345 @item
10346 The directory in which the compiler's output
10347 (@file{ALI} files, object files, tree files) is to be placed
10348 @item
10349 The directory in which the executable programs is to be placed
10350 @item
10351 ^Switch^Switch^ settings for any of the project-enabled tools
10352 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10353 @code{gnatfind}); you can apply these settings either globally or to individual
10354 compilation units.
10355 @item
10356 The source files containing the main subprogram(s) to be built
10357 @item
10358 The source programming language(s) (currently Ada and/or C)
10359 @item
10360 Source file naming conventions; you can specify these either globally or for
10361 individual compilation units
10362 @end itemize
10364 @menu
10365 * Project Files::
10366 @end menu
10368 @node Project Files
10369 @subsection Project Files
10371 @noindent
10372 Project files are written in a syntax close to that of Ada, using  familiar
10373 notions such as packages, context clauses, declarations, default values,
10374 assignments, and inheritance. Finally, project files can be built
10375 hierarchically from other project files, simplifying complex system
10376 integration and project reuse.
10378 A @dfn{project} is a specific set of values for various compilation properties.
10379 The settings for a given project are described by means of
10380 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10381 Property values in project files are either strings or lists of strings.
10382 Properties that are not explicitly set receive default values.  A project
10383 file may interrogate the values of @dfn{external variables} (user-defined
10384 command-line switches or environment variables), and it may specify property
10385 settings conditionally, based on the value of such variables.
10387 In simple cases, a project's source files depend only on other source files
10388 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10389 used in
10390 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10391 the Project Manager also allows more sophisticated arrangements,
10392 where the source files in one project depend on source files in other
10393 projects:
10394 @itemize @bullet
10395 @item
10396 One project can @emph{import} other projects containing needed source files.
10397 @item
10398 You can organize GNAT projects in a hierarchy: a @emph{child} project
10399 can extend a @emph{parent} project, inheriting the parent's source files and
10400 optionally overriding any of them with alternative versions
10401 @end itemize
10403 @noindent
10404 More generally, the Project Manager lets you structure large development
10405 efforts into hierarchical subsystems, where build decisions are delegated
10406 to the subsystem level, and thus different compilation environments
10407 (^switch^switch^ settings) used for different subsystems.
10409 The Project Manager is invoked through the
10410 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10411 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10412 @ifclear vms
10413 There may be zero, one or more spaces between @option{-P} and
10414 @option{@emph{projectfile}}.
10415 @end ifclear
10416 If you want to define (on the command line) an external variable that is
10417 queried by the project file, you must use the
10418 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10419 The Project Manager parses and interprets the project file, and drives the
10420 invoked tool based on the project settings.
10422 The Project Manager supports a wide range of development strategies,
10423 for systems of all sizes.  Here are some typical practices that are
10424 easily handled:
10425 @itemize @bullet
10426 @item
10427 Using a common set of source files, but generating object files in different
10428 directories via different ^switch^switch^ settings
10429 @item
10430 Using a mostly-shared set of source files, but with different versions of
10431 some unit or units
10432 @end itemize
10434 @noindent
10435 The destination of an executable can be controlled inside a project file
10436 using the @option{^-o^-o^}
10437 ^switch^switch^.
10438 In the absence of such a ^switch^switch^ either inside
10439 the project file or on the command line, any executable files generated by
10440 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10441 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10442 in the object directory of the project.
10444 You can use project files to achieve some of the effects of a source
10445 versioning system (for example, defining separate projects for
10446 the different sets of sources that comprise different releases) but the
10447 Project Manager is independent of any source configuration management tools
10448 that might be used by the developers.
10450 The next section introduces the main features of GNAT's project facility
10451 through a sequence of examples; subsequent sections will present the syntax
10452 and semantics in more detail. A more formal description of the project
10453 facility appears in the GNAT Reference Manual.
10455 @c *****************************
10456 @c * Examples of Project Files *
10457 @c *****************************
10459 @node Examples of Project Files
10460 @section Examples of Project Files
10461 @noindent
10462 This section illustrates some of the typical uses of project files and
10463 explains their basic structure and behavior.
10465 @menu
10466 * Common Sources with Different ^Switches^Switches^ and Directories::
10467 * Using External Variables::
10468 * Importing Other Projects::
10469 * Extending a Project::
10470 @end menu
10472 @node Common Sources with Different ^Switches^Switches^ and Directories
10473 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10475 @menu
10476 * Source Files::
10477 * Specifying the Object Directory::
10478 * Specifying the Exec Directory::
10479 * Project File Packages::
10480 * Specifying ^Switch^Switch^ Settings::
10481 * Main Subprograms::
10482 * Executable File Names::
10483 * Source File Naming Conventions::
10484 * Source Language(s)::
10485 @end menu
10487 @noindent
10488 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10489 @file{proc.adb} are in the @file{/common} directory.  The file
10490 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10491 package @code{Pack}.  We want to compile these source files under two sets
10492 of ^switches^switches^:
10493 @itemize @bullet
10494 @item
10495 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10496 and the @option{^-gnata^-gnata^},
10497 @option{^-gnato^-gnato^},
10498 and @option{^-gnatE^-gnatE^} switches to the
10499 compiler; the compiler's output is to appear in @file{/common/debug}
10500 @item
10501 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10502 to the compiler; the compiler's output is to appear in @file{/common/release}
10503 @end itemize
10505 @noindent
10506 The GNAT project files shown below, respectively @file{debug.gpr} and
10507 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10509 Schematically:
10510 @smallexample
10511 @group
10512 ^/common^[COMMON]^
10513   debug.gpr
10514   release.gpr
10515   pack.ads
10516   pack.adb
10517   proc.adb
10518 @end group
10519 @group
10520 ^/common/debug^[COMMON.DEBUG]^
10521   proc.ali, proc.o
10522   pack.ali, pack.o
10523 @end group
10524 @group
10525 ^/common/release^[COMMON.RELEASE]^
10526   proc.ali, proc.o
10527   pack.ali, pack.o
10528 @end group
10529 @end smallexample
10530 Here are the corresponding project files:
10532 @smallexample @c projectfile
10533 @group
10534 project Debug is
10535   for Object_Dir use "debug";
10536   for Main use ("proc");
10538   package Builder is
10539     for ^Default_Switches^Default_Switches^ ("Ada")
10540         use ("^-g^-g^");
10541     for Executable ("proc.adb") use "proc1";
10542   end Builder;
10543 @end group
10545 @group
10546   package Compiler is
10547     for ^Default_Switches^Default_Switches^ ("Ada")
10548        use ("-fstack-check",
10549             "^-gnata^-gnata^",
10550             "^-gnato^-gnato^",
10551             "^-gnatE^-gnatE^");
10552   end Compiler;
10553 end Debug;
10554 @end group
10555 @end smallexample
10557 @smallexample @c projectfile
10558 @group
10559 project Release is
10560   for Object_Dir use "release";
10561   for Exec_Dir use ".";
10562   for Main use ("proc");
10564   package Compiler is
10565     for ^Default_Switches^Default_Switches^ ("Ada")
10566         use ("^-O2^-O2^");
10567   end Compiler;
10568 end Release;
10569 @end group
10570 @end smallexample
10572 @noindent
10573 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10574 insensitive), and analogously the project defined by @file{release.gpr} is
10575 @code{"Release"}.  For consistency the file should have the same name as the
10576 project, and the project file's extension should be @code{"gpr"}. These
10577 conventions are not required, but a warning is issued if they are not followed.
10579 If the current directory is @file{^/temp^[TEMP]^}, then the command
10580 @smallexample
10581 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10582 @end smallexample
10584 @noindent
10585 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10586 as well as the @code{^proc1^PROC1.EXE^} executable,
10587 using the ^switch^switch^ settings defined in the project file.
10589 Likewise, the command
10590 @smallexample
10591 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10592 @end smallexample
10594 @noindent
10595 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10596 and the @code{^proc^PROC.EXE^}
10597 executable in @file{^/common^[COMMON]^},
10598 using the ^switch^switch^ settings from the project file.
10600 @node Source Files
10601 @unnumberedsubsubsec Source Files
10603 @noindent
10604 If a project file does not explicitly specify a set of source directories or
10605 a set of source files, then by default the project's source files are the
10606 Ada source files in the project file directory.  Thus @file{pack.ads},
10607 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10609 @node Specifying the Object Directory
10610 @unnumberedsubsubsec Specifying the Object Directory
10612 @noindent
10613 Several project properties are modeled by Ada-style @emph{attributes};
10614 a property is defined by supplying the equivalent of an Ada attribute
10615 definition clause in the project file.
10616 A project's object directory is another such a property; the corresponding
10617 attribute is @code{Object_Dir}, and its value is also a string expression,
10618 specified either as absolute or relative. In the later case,
10619 it is relative to the project file directory. Thus the compiler's
10620 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10621 (for the @code{Debug} project)
10622 and to @file{^/common/release^[COMMON.RELEASE]^}
10623 (for the @code{Release} project).
10624 If @code{Object_Dir} is not specified, then the default is the project file
10625 directory itself.
10627 @node Specifying the Exec Directory
10628 @unnumberedsubsubsec Specifying the Exec Directory
10630 @noindent
10631 A project's exec directory is another property; the corresponding
10632 attribute is @code{Exec_Dir}, and its value is also a string expression,
10633 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10634 then the default is the object directory (which may also be the project file
10635 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10636 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10637 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10638 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10640 @node Project File Packages
10641 @unnumberedsubsubsec Project File Packages
10643 @noindent
10644 A GNAT tool that is integrated with the Project Manager is modeled by a
10645 corresponding package in the project file. In the example above,
10646 The @code{Debug} project defines the packages @code{Builder}
10647 (for @command{gnatmake}) and @code{Compiler};
10648 the @code{Release} project defines only the @code{Compiler} package.
10650 The Ada-like package syntax is not to be taken literally.  Although packages in
10651 project files bear a surface resemblance to packages in Ada source code, the
10652 notation is simply a way to convey a grouping of properties for a named
10653 entity.  Indeed, the package names permitted in project files are restricted
10654 to a predefined set, corresponding to the project-aware tools, and the contents
10655 of packages are limited to a small set of constructs.
10656 The packages in the example above contain attribute definitions.
10658 @node Specifying ^Switch^Switch^ Settings
10659 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10661 @noindent
10662 ^Switch^Switch^ settings for a project-aware tool can be specified through
10663 attributes in the package that corresponds to the tool.
10664 The example above illustrates one of the relevant attributes,
10665 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10666 in both project files.
10667 Unlike simple attributes like @code{Source_Dirs},
10668 @code{^Default_Switches^Default_Switches^} is
10669 known as an @emph{associative array}.  When you define this attribute, you must
10670 supply an ``index'' (a literal string), and the effect of the attribute
10671 definition is to set the value of the array at the specified index.
10672 For the @code{^Default_Switches^Default_Switches^} attribute,
10673 the index is a programming language (in our case, Ada),
10674 and the value specified (after @code{use}) must be a list
10675 of string expressions.
10677 The attributes permitted in project files are restricted to a predefined set.
10678 Some may appear at project level, others in packages.
10679 For any attribute that is an associative array, the index must always be a
10680 literal string, but the restrictions on this string (e.g., a file name or a
10681 language name) depend on the individual attribute.
10682 Also depending on the attribute, its specified value will need to be either a
10683 string or a string list.
10685 In the @code{Debug} project, we set the switches for two tools,
10686 @command{gnatmake} and the compiler, and thus we include the two corresponding
10687 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10688 attribute with index @code{"Ada"}.
10689 Note that the package corresponding to
10690 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10691 similar, but only includes the @code{Compiler} package.
10693 In project @code{Debug} above, the ^switches^switches^ starting with
10694 @option{-gnat} that are specified in package @code{Compiler}
10695 could have been placed in package @code{Builder}, since @command{gnatmake}
10696 transmits all such ^switches^switches^ to the compiler.
10698 @node Main Subprograms
10699 @unnumberedsubsubsec Main Subprograms
10701 @noindent
10702 One of the specifiable properties of a project is a list of files that contain
10703 main subprograms.  This property is captured in the @code{Main} attribute,
10704 whose value is a list of strings.  If a project defines the @code{Main}
10705 attribute, it is not necessary to identify the main subprogram(s) when
10706 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
10708 @node Executable File Names
10709 @unnumberedsubsubsec Executable File Names
10711 @noindent
10712 By default, the executable file name corresponding to a main source is
10713 deduced from the main source file name. Through the attributes
10714 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10715 it is possible to change this default.
10716 In project @code{Debug} above, the executable file name
10717 for main source @file{^proc.adb^PROC.ADB^} is
10718 @file{^proc1^PROC1.EXE^}.
10719 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10720 of the the executable files, when no attribute @code{Executable} applies:
10721 its value replace the platform-specific executable suffix.
10722 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10723 specify a non default executable file name when several mains are built at once
10724 in a single @command{gnatmake} command.
10726 @node Source File Naming Conventions
10727 @unnumberedsubsubsec Source File Naming Conventions
10729 @noindent
10730 Since the project files above do not specify any source file naming
10731 conventions, the GNAT defaults are used.  The mechanism for defining source
10732 file naming conventions -- a package named @code{Naming} --
10733 is described below (@pxref{Naming Schemes}).
10735 @node Source Language(s)
10736 @unnumberedsubsubsec Source Language(s)
10738 @noindent
10739 Since the project files do not specify a @code{Languages} attribute, by
10740 default the GNAT tools assume that the language of the project file is Ada.
10741 More generally, a project can comprise source files
10742 in Ada, C, and/or other languages.
10744 @node Using External Variables
10745 @subsection Using External Variables
10747 @noindent
10748 Instead of supplying different project files for debug and release, we can
10749 define a single project file that queries an external variable (set either
10750 on the command line or via an ^environment variable^logical name^) in order to
10751 conditionally define the appropriate settings.  Again, assume that the
10752 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10753 located in directory @file{^/common^[COMMON]^}.  The following project file,
10754 @file{build.gpr}, queries the external variable named @code{STYLE} and
10755 defines an object directory and ^switch^switch^ settings based on whether
10756 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10757 the default is @code{"deb"}.
10759 @smallexample @c projectfile
10760 @group
10761 project Build is
10762   for Main use ("proc");
10764   type Style_Type is ("deb", "rel");
10765   Style : Style_Type := external ("STYLE", "deb");
10767   case Style is
10768     when "deb" =>
10769       for Object_Dir use "debug";
10771     when "rel" =>
10772       for Object_Dir use "release";
10773       for Exec_Dir use ".";
10774   end case;
10775 @end group
10777 @group
10778   package Builder is
10780     case Style is
10781       when "deb" =>
10782         for ^Default_Switches^Default_Switches^ ("Ada")
10783             use ("^-g^-g^");
10784         for Executable ("proc") use "proc1";
10785       when others =>
10786         null;
10787     end case;
10789   end Builder;
10790 @end group
10792 @group
10793   package Compiler is
10795     case Style is
10796       when "deb" =>
10797         for ^Default_Switches^Default_Switches^ ("Ada")
10798             use ("^-gnata^-gnata^",
10799                  "^-gnato^-gnato^",
10800                  "^-gnatE^-gnatE^");
10802       when "rel" =>
10803         for ^Default_Switches^Default_Switches^ ("Ada")
10804             use ("^-O2^-O2^");
10805     end case;
10807   end Compiler;
10809 end Build;
10810 @end group
10811 @end smallexample
10813 @noindent
10814 @code{Style_Type} is an example of a @emph{string type}, which is the project
10815 file analog of an Ada enumeration type but whose components are string literals
10816 rather than identifiers.  @code{Style} is declared as a variable of this type.
10818 The form @code{external("STYLE", "deb")} is known as an
10819 @emph{external reference}; its first argument is the name of an
10820 @emph{external variable}, and the second argument is a default value to be
10821 used if the external variable doesn't exist.  You can define an external
10822 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10823 or you can use ^an environment variable^a logical name^
10824 as an external variable.
10826 Each @code{case} construct is expanded by the Project Manager based on the
10827 value of @code{Style}. Thus the command
10828 @ifclear vms
10829 @smallexample
10830 gnatmake -P/common/build.gpr -XSTYLE=deb
10831 @end smallexample
10832 @end ifclear
10834 @ifset vms
10835 @smallexample
10836 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10837 @end smallexample
10838 @end ifset
10840 @noindent
10841 is equivalent to the @command{gnatmake} invocation using the project file
10842 @file{debug.gpr} in the earlier example.  So is the command
10843 @smallexample
10844 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10845 @end smallexample
10847 @noindent
10848 since @code{"deb"} is the default for @code{STYLE}.
10850 Analogously,
10852 @ifclear vms
10853 @smallexample
10854 gnatmake -P/common/build.gpr -XSTYLE=rel
10855 @end smallexample
10856 @end ifclear
10858 @ifset vms
10859 @smallexample
10860 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10861 @end smallexample
10862 @end ifset
10864 @noindent
10865 is equivalent to the @command{gnatmake} invocation using the project file
10866 @file{release.gpr} in the earlier example.
10868 @node Importing Other Projects
10869 @subsection Importing Other Projects
10871 @noindent
10872 A compilation unit in a source file in one project may depend on compilation
10873 units in source files in other projects.  To compile this unit under
10874 control of a project file, the
10875 dependent project must @emph{import} the projects containing the needed source
10876 files.
10877 This effect is obtained using syntax similar to an Ada @code{with} clause,
10878 but where @code{with}ed entities are strings that denote project files.
10880 As an example, suppose that the two projects @code{GUI_Proj} and
10881 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10882 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10883 and @file{^/comm^[COMM]^}, respectively.
10884 Suppose that the source files for @code{GUI_Proj} are
10885 @file{gui.ads} and @file{gui.adb}, and that the source files for
10886 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10887 files is located in its respective project file directory.  Schematically:
10889 @smallexample
10890 @group
10891 ^/gui^[GUI]^
10892   gui_proj.gpr
10893   gui.ads
10894   gui.adb
10895 @end group
10897 @group
10898 ^/comm^[COMM]^
10899   comm_proj.gpr
10900   comm.ads
10901   comm.adb
10902 @end group
10903 @end smallexample
10905 @noindent
10906 We want to develop an application in directory @file{^/app^[APP]^} that
10907 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
10908 the corresponding project files (e.g. the ^switch^switch^ settings
10909 and object directory).
10910 Skeletal code for a main procedure might be something like the following:
10912 @smallexample @c ada
10913 @group
10914 with GUI, Comm;
10915 procedure App_Main is
10916    ...
10917 begin
10918    ...
10919 end App_Main;
10920 @end group
10921 @end smallexample
10923 @noindent
10924 Here is a project file, @file{app_proj.gpr}, that achieves the desired
10925 effect:
10927 @smallexample @c projectfile
10928 @group
10929 with "/gui/gui_proj", "/comm/comm_proj";
10930 project App_Proj is
10931    for Main use ("app_main");
10932 end App_Proj;
10933 @end group
10934 @end smallexample
10936 @noindent
10937 Building an executable is achieved through the command:
10938 @smallexample
10939 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
10940 @end smallexample
10941 @noindent
10942 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
10943 in the directory where @file{app_proj.gpr} resides.
10945 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
10946 (as illustrated above) the @code{with} clause can omit the extension.
10948 Our example specified an absolute path for each imported project file.
10949 Alternatively, the directory name of an imported object can be omitted
10950 if either
10951 @itemize @bullet
10952 @item
10953 The imported project file is in the same directory as the importing project
10954 file, or
10955 @item
10956 You have defined ^an environment variable^a logical name^
10957 that includes the directory containing
10958 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
10959 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
10960 directory names separated by colons (semicolons on Windows).
10961 @end itemize
10963 @noindent
10964 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
10965 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
10966 as follows:
10968 @smallexample @c projectfile
10969 @group
10970 with "gui_proj", "comm_proj";
10971 project App_Proj is
10972    for Main use ("app_main");
10973 end App_Proj;
10974 @end group
10975 @end smallexample
10977 @noindent
10978 Importing other projects can create ambiguities.
10979 For example, the same unit might be present in different imported projects, or
10980 it might be present in both the importing project and in an imported project.
10981 Both of these conditions are errors.  Note that in the current version of
10982 the Project Manager, it is illegal to have an ambiguous unit even if the
10983 unit is never referenced by the importing project.  This restriction may be
10984 relaxed in a future release.
10986 @node Extending a Project
10987 @subsection Extending a Project
10989 @noindent
10990 In large software systems it is common to have multiple
10991 implementations of a common interface; in Ada terms, multiple versions of a
10992 package body for the same specification.  For example, one implementation
10993 might be safe for use in tasking programs, while another might only be used
10994 in sequential applications.  This can be modeled in GNAT using the concept
10995 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
10996 another project (the ``parent'') then by default all source files of the
10997 parent project are inherited by the child, but the child project can
10998 override any of the parent's source files with new versions, and can also
10999 add new files.  This facility is the project analog of a type extension in
11000 Object-Oriented Programming.  Project hierarchies are permitted (a child
11001 project may be the parent of yet another project), and a project that
11002 inherits one project can also import other projects.
11004 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11005 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11006 @file{pack.adb}, and @file{proc.adb}:
11008 @smallexample
11009 @group
11010 ^/seq^[SEQ]^
11011   pack.ads
11012   pack.adb
11013   proc.adb
11014   seq_proj.gpr
11015 @end group
11016 @end smallexample
11018 @noindent
11019 Note that the project file can simply be empty (that is, no attribute or
11020 package is defined):
11022 @smallexample @c projectfile
11023 @group
11024 project Seq_Proj is
11025 end Seq_Proj;
11026 @end group
11027 @end smallexample
11029 @noindent
11030 implying that its source files are all the Ada source files in the project
11031 directory.
11033 Suppose we want to supply an alternate version of @file{pack.adb}, in
11034 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11035 @file{pack.ads} and @file{proc.adb}.  We can define a project
11036 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11038 @smallexample
11039 @group
11040 ^/tasking^[TASKING]^
11041   pack.adb
11042   tasking_proj.gpr
11043 @end group
11045 @group
11046 project Tasking_Proj extends "/seq/seq_proj" is
11047 end Tasking_Proj;
11048 @end group
11049 @end smallexample
11051 @noindent
11052 The version of @file{pack.adb} used in a build depends on which project file
11053 is specified.
11055 Note that we could have obtained the desired behavior using project import
11056 rather than project inheritance; a @code{base} project would contain the
11057 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11058 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11059 would import @code{base} and add a different version of @file{pack.adb}.  The
11060 choice depends on whether other sources in the original project need to be
11061 overridden.  If they do, then project extension is necessary, otherwise,
11062 importing is sufficient.
11064 @noindent
11065 In a project file that extends another project file, it is possible to
11066 indicate that an inherited source is not part of the sources of the extending
11067 project. This is necessary sometimes when a package spec has been overloaded
11068 and no longer requires a body: in this case, it is necessary to indicate that
11069 the inherited body is not part of the sources of the project, otherwise there
11070 will be a compilation error when compiling the spec.
11072 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11073 Its value is a string list: a list of file names.
11075 @smallexample @c @projectfile
11076 project B extends "a" is
11077    for Source_Files use ("pkg.ads");
11078    --  New spec of Pkg does not need a completion
11079    for Locally_Removed_Files use ("pkg.adb");
11080 end B;
11081 @end smallexample
11083 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11084 is still needed: if it is possible to build using @code{gnatmake} when such
11085 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11086 it is possible to remove the source completely from a system that includes
11087 project P.
11089 @c ***********************
11090 @c * Project File Syntax *
11091 @c ***********************
11093 @node Project File Syntax
11094 @section Project File Syntax
11096 @menu
11097 * Basic Syntax::
11098 * Packages::
11099 * Expressions::
11100 * String Types::
11101 * Variables::
11102 * Attributes::
11103 * Associative Array Attributes::
11104 * case Constructions::
11105 @end menu
11107 @noindent
11108 This section describes the structure of project files.
11110 A project may be an @emph{independent project}, entirely defined by a single
11111 project file. Any Ada source file in an independent project depends only
11112 on the predefined library and other Ada source files in the same project.
11114 @noindent
11115 A project may also @dfn{depend on} other projects, in either or both of
11116 the following ways:
11117 @itemize @bullet
11118 @item It may import any number of projects
11119 @item It may extend at most one other project
11120 @end itemize
11122 @noindent
11123 The dependence relation is a directed acyclic graph (the subgraph reflecting
11124 the ``extends'' relation is a tree).
11126 A project's @dfn{immediate sources} are the source files directly defined by
11127 that project, either implicitly by residing in the project file's directory,
11128 or explicitly through any of the source-related attributes described below.
11129 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11130 of @var{proj} together with the immediate sources (unless overridden) of any
11131 project on which @var{proj} depends (either directly or indirectly).
11133 @node Basic Syntax
11134 @subsection Basic Syntax
11136 @noindent
11137 As seen in the earlier examples, project files have an Ada-like syntax.
11138 The minimal project file is:
11139 @smallexample @c projectfile
11140 @group
11141 project Empty is
11143 end Empty;
11144 @end group
11145 @end smallexample
11147 @noindent
11148 The identifier @code{Empty} is the name of the project.
11149 This project name must be present after the reserved
11150 word @code{end} at the end of the project file, followed by a semi-colon.
11152 Any name in a project file, such as the project name or a variable name,
11153 has the same syntax as an Ada identifier.
11155 The reserved words of project files are the Ada reserved words plus
11156 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11157 reserved words currently used in project file syntax are:
11159 @itemize @bullet
11160 @item
11161 @code{case}
11162 @item
11163 @code{end}
11164 @item
11165 @code{for}
11166 @item
11167 @code{is}
11168 @item
11169 @code{others}
11170 @item
11171 @code{package}
11172 @item
11173 @code{renames}
11174 @item
11175 @code{type}
11176 @item
11177 @code{use}
11178 @item
11179 @code{when}
11180 @item
11181 @code{with}
11182 @end itemize
11184 @noindent
11185 Comments in project files have the same syntax as in Ada, two consecutives
11186 hyphens through the end of the line.
11188 @node Packages
11189 @subsection Packages
11191 @noindent
11192 A project file may contain @emph{packages}. The name of a package must be one
11193 of the identifiers from the following list. A package
11194 with a given name may only appear once in a project file. Package names are
11195 case insensitive. The following package names are legal:
11197 @itemize @bullet
11198 @item
11199 @code{Naming}
11200 @item
11201 @code{Builder}
11202 @item
11203 @code{Compiler}
11204 @item
11205 @code{Binder}
11206 @item
11207 @code{Linker}
11208 @item
11209 @code{Finder}
11210 @item
11211 @code{Cross_Reference}
11212 @item
11213 @code{Eliminate}
11214 @item
11215 @code{Pretty_Printer}
11216 @item
11217 @code{Metrics}
11218 @item
11219 @code{gnatls}
11220 @item
11221 @code{gnatstub}
11222 @item
11223 @code{IDE}
11224 @item
11225 @code{Language_Processing}
11226 @end itemize
11228 @noindent
11229 In its simplest form, a package may be empty:
11231 @smallexample @c projectfile
11232 @group
11233 project Simple is
11234   package Builder is
11235   end Builder;
11236 end Simple;
11237 @end group
11238 @end smallexample
11240 @noindent
11241 A package may contain @emph{attribute declarations},
11242 @emph{variable declarations} and @emph{case constructions}, as will be
11243 described below.
11245 When there is ambiguity between a project name and a package name,
11246 the name always designates the project. To avoid possible confusion, it is
11247 always a good idea to avoid naming a project with one of the
11248 names allowed for packages or any name that starts with @code{gnat}.
11250 @node Expressions
11251 @subsection Expressions
11253 @noindent
11254 An @emph{expression} is either a @emph{string expression} or a
11255 @emph{string list expression}.
11257 A @emph{string expression} is either a @emph{simple string expression} or a
11258 @emph{compound string expression}.
11260 A @emph{simple string expression} is one of the following:
11261 @itemize @bullet
11262 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11263 @item A string-valued variable reference (see @ref{Variables})
11264 @item A string-valued attribute reference (see @ref{Attributes})
11265 @item An external reference (see @ref{External References in Project Files})
11266 @end itemize
11268 @noindent
11269 A @emph{compound string expression} is a concatenation of string expressions,
11270 using the operator @code{"&"}
11271 @smallexample
11272        Path & "/" & File_Name & ".ads"
11273 @end smallexample
11275 @noindent
11276 A @emph{string list expression} is either a
11277 @emph{simple string list expression} or a
11278 @emph{compound string list expression}.
11280 A @emph{simple string list expression} is one of the following:
11281 @itemize @bullet
11282 @item A parenthesized list of zero or more string expressions,
11283 separated by commas
11284 @smallexample
11285    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11286    Empty_List := ();
11287 @end smallexample
11288 @item A string list-valued variable reference
11289 @item A string list-valued attribute reference
11290 @end itemize
11292 @noindent
11293 A @emph{compound string list expression} is the concatenation (using
11294 @code{"&"}) of a simple string list expression and an expression.  Note that
11295 each term in a compound string list expression, except the first, may be
11296 either a string expression or a string list expression.
11298 @smallexample @c projectfile
11299 @group
11300    File_Name_List := () & File_Name; --  One string in this list
11301    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11302    --  Two strings
11303    Big_List := File_Name_List & Extended_File_Name_List;
11304    --  Concatenation of two string lists: three strings
11305    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11306    --  Illegal: must start with a string list
11307 @end group
11308 @end smallexample
11310 @node String Types
11311 @subsection String Types
11313 @noindent
11314 A @emph{string type declaration} introduces a discrete set of string literals.
11315 If a string variable is declared to have this type, its value
11316 is restricted to the given set of literals.
11318 Here is an example of a string type declaration:
11320 @smallexample @c projectfile
11321    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11322 @end smallexample
11324 @noindent
11325 Variables of a string type are called @emph{typed variables}; all other
11326 variables are called @emph{untyped variables}. Typed variables are
11327 particularly useful in @code{case} constructions, to support conditional
11328 attribute declarations.
11329 (see @ref{case Constructions}).
11331 The string literals in the list are case sensitive and must all be different.
11332 They may include any graphic characters allowed in Ada, including spaces.
11334 A string type may only be declared at the project level, not inside a package.
11336 A string type may be referenced by its name if it has been declared in the same
11337 project file, or by an expanded name whose prefix is the name of the project
11338 in which it is declared.
11340 @node Variables
11341 @subsection Variables
11343 @noindent
11344 A variable may be declared at the project file level, or within a package.
11345 Here are some examples of variable declarations:
11347 @smallexample @c projectfile
11348 @group
11349    This_OS : OS := external ("OS"); --  a typed variable declaration
11350    That_OS := "GNU/Linux";          --  an untyped variable declaration
11351 @end group
11352 @end smallexample
11354 @noindent
11355 The syntax of a @emph{typed variable declaration} is identical to the Ada
11356 syntax for an object declaration. By contrast, the syntax of an untyped
11357 variable declaration is identical to an Ada assignment statement. In fact,
11358 variable declarations in project files have some of the characteristics of
11359 an assignment, in that successive declarations for the same variable are
11360 allowed. Untyped variable declarations do establish the expected kind of the
11361 variable (string or string list), and successive declarations for it must
11362 respect the initial kind.
11364 @noindent
11365 A string variable declaration (typed or untyped) declares a variable
11366 whose value is a string. This variable may be used as a string expression.
11367 @smallexample @c projectfile
11368    File_Name       := "readme.txt";
11369    Saved_File_Name := File_Name & ".saved";
11370 @end smallexample
11372 @noindent
11373 A string list variable declaration declares a variable whose value is a list
11374 of strings. The list may contain any number (zero or more) of strings.
11376 @smallexample @c projectfile
11377    Empty_List := ();
11378    List_With_One_Element := ("^-gnaty^-gnaty^");
11379    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11380    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11381                  "pack2.ada", "util_.ada", "util.ada");
11382 @end smallexample
11384 @noindent
11385 The same typed variable may not be declared more than once at project level,
11386 and it may not be declared more than once in any package; it is in effect
11387 a constant.
11389 The same untyped variable may be declared several times. Declarations are
11390 elaborated in the order in which they appear, so  the new value replaces
11391 the old one, and any subsequent reference to the variable uses the new value.
11392 However, as noted above, if a variable has been declared as a string, all
11393 subsequent
11394 declarations must give it a string value. Similarly, if a variable has
11395 been declared as a string list, all subsequent declarations
11396 must give it a string list value.
11398 A @emph{variable reference} may take several forms:
11400 @itemize @bullet
11401 @item The simple variable name, for a variable in the current package (if any)
11402 or in the current project
11403 @item An expanded name, whose prefix is a context name.
11404 @end itemize
11406 @noindent
11407 A @emph{context} may be one of the following:
11409 @itemize @bullet
11410 @item The name of an existing package in the current project
11411 @item The name of an imported project of the current project
11412 @item The name of an ancestor project (i.e., a project extended by the current
11413 project, either directly or indirectly)
11414 @item An expanded name whose prefix is an imported/parent project name, and
11415 whose selector is a package name in that project.
11416 @end itemize
11418 @noindent
11419 A variable reference may be used in an expression.
11421 @node Attributes
11422 @subsection Attributes
11424 @noindent
11425 A project (and its packages) may have @emph{attributes} that define
11426 the project's properties.  Some attributes have values that are strings;
11427 others have values that are string lists.
11429 There are two categories of attributes: @emph{simple attributes}
11430 and @emph{associative arrays} (see @ref{Associative Array Attributes}).
11432 Legal project attribute names, and attribute names for each legal package are
11433 listed below. Attributes names are case-insensitive.
11435 The following attributes are defined on projects (all are simple attributes):
11437 @multitable @columnfractions .4 .3
11438 @item @emph{Attribute Name}
11439 @tab @emph{Value}
11440 @item @code{Source_Files}
11441 @tab string list
11442 @item @code{Source_Dirs}
11443 @tab string list
11444 @item @code{Source_List_File}
11445 @tab string
11446 @item @code{Object_Dir}
11447 @tab string
11448 @item @code{Exec_Dir}
11449 @tab string
11450 @item @code{Locally_Removed_Files}
11451 @tab string list
11452 @item @code{Main}
11453 @tab string list
11454 @item @code{Languages}
11455 @tab string list
11456 @item @code{Main_Language}
11457 @tab string
11458 @item @code{Library_Dir}
11459 @tab string
11460 @item @code{Library_Name}
11461 @tab string
11462 @item @code{Library_Kind}
11463 @tab string
11464 @item @code{Library_Version}
11465 @tab string
11466 @item @code{Library_Interface}
11467 @tab string
11468 @item @code{Library_Auto_Init}
11469 @tab string
11470 @item @code{Library_Options}
11471 @tab string list
11472 @item @code{Library_GCC}
11473 @tab string
11474 @end multitable
11476 @noindent
11477 The following attributes are defined for package  @code{Naming}
11478 (see @ref{Naming Schemes}):
11480 @multitable @columnfractions .4 .2 .2 .2
11481 @item Attribute Name @tab Category @tab Index @tab Value
11482 @item @code{Spec_Suffix}
11483 @tab associative array
11484 @tab language name
11485 @tab string
11486 @item @code{Body_Suffix}
11487 @tab associative array
11488 @tab language name
11489 @tab string
11490 @item @code{Separate_Suffix}
11491 @tab simple attribute
11492 @tab n/a
11493 @tab string
11494 @item @code{Casing}
11495 @tab simple attribute
11496 @tab n/a
11497 @tab string
11498 @item @code{Dot_Replacement}
11499 @tab simple attribute
11500 @tab n/a
11501 @tab string
11502 @item @code{Spec}
11503 @tab associative array
11504 @tab Ada unit name
11505 @tab string
11506 @item @code{Body}
11507 @tab associative array
11508 @tab Ada unit name
11509 @tab string
11510 @item @code{Specification_Exceptions}
11511 @tab associative array
11512 @tab language name
11513 @tab string list
11514 @item @code{Implementation_Exceptions}
11515 @tab associative array
11516 @tab language name
11517 @tab string list
11518 @end multitable
11520 @noindent
11521 The following attributes are defined for packages @code{Builder},
11522 @code{Compiler}, @code{Binder},
11523 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11524 (see @ref{^Switches^Switches^ and Project Files}).
11526 @multitable @columnfractions .4 .2 .2 .2
11527 @item Attribute Name @tab Category @tab Index @tab Value
11528 @item @code{^Default_Switches^Default_Switches^}
11529 @tab associative array
11530 @tab language name
11531 @tab string list
11532 @item @code{^Switches^Switches^}
11533 @tab associative array
11534 @tab file name
11535 @tab string list
11536 @end multitable
11538 @noindent
11539 In addition, package @code{Compiler} has a single string attribute
11540 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11541 string attribute @code{Global_Configuration_Pragmas}.
11543 @noindent
11544 Each simple attribute has a default value: the empty string (for string-valued
11545 attributes) and the empty list (for string list-valued attributes).
11547 An attribute declaration defines a new value for an attribute.
11549 Examples of simple attribute declarations:
11551 @smallexample @c projectfile
11552    for Object_Dir use "objects";
11553    for Source_Dirs use ("units", "test/drivers");
11554 @end smallexample
11556 @noindent
11557 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11558 attribute definition clause in Ada.
11560 Attributes references may be appear in expressions.
11561 The general form for such a reference is @code{<entity>'<attribute>}:
11562 Associative array attributes are functions. Associative
11563 array attribute references must have an argument that is a string literal.
11565 Examples are:
11567 @smallexample @c projectfile
11568   project'Object_Dir
11569   Naming'Dot_Replacement
11570   Imported_Project'Source_Dirs
11571   Imported_Project.Naming'Casing
11572   Builder'^Default_Switches^Default_Switches^("Ada")
11573 @end smallexample
11575 @noindent
11576 The prefix of an attribute may be:
11577 @itemize @bullet
11578 @item @code{project} for an attribute of the current project
11579 @item The name of an existing package of the current project
11580 @item The name of an imported project
11581 @item The name of a parent project that is extended by the current project
11582 @item An expanded name whose prefix is imported/parent project name,
11583       and whose selector is a package name
11584 @end itemize
11586 @noindent
11587 Example:
11588 @smallexample @c projectfile
11589 @group
11590    project Prj is
11591      for Source_Dirs use project'Source_Dirs & "units";
11592      for Source_Dirs use project'Source_Dirs & "test/drivers"
11593    end Prj;
11594 @end group
11595 @end smallexample
11597 @noindent
11598 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11599 has the default value: an empty string list. After this declaration,
11600 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11601 After the second attribute declaration @code{Source_Dirs} is a string list of
11602 two elements: @code{"units"} and @code{"test/drivers"}.
11604 Note: this example is for illustration only. In practice,
11605 the project file would contain only one attribute declaration:
11607 @smallexample @c projectfile
11608    for Source_Dirs use ("units", "test/drivers");
11609 @end smallexample
11611 @node Associative Array Attributes
11612 @subsection Associative Array Attributes
11614 @noindent
11615 Some attributes are defined as @emph{associative arrays}. An associative
11616 array may be regarded as a function that takes a string as a parameter
11617 and delivers a string or string list value as its result.
11619 Here are some examples of single associative array attribute associations:
11621 @smallexample @c projectfile
11622    for Body ("main") use "Main.ada";
11623    for ^Switches^Switches^ ("main.ada")
11624        use ("^-v^-v^",
11625             "^-gnatv^-gnatv^");
11626    for ^Switches^Switches^ ("main.ada")
11627             use Builder'^Switches^Switches^ ("main.ada")
11628               & "^-g^-g^";
11629 @end smallexample
11631 @noindent
11632 Like untyped variables and simple attributes, associative array attributes
11633 may be declared several times. Each declaration supplies a new value for the
11634 attribute, and replaces the previous setting.
11636 @noindent
11637 An associative array attribute may be declared as a full associative array
11638 declaration, with the value of the same attribute in an imported or extended
11639 project.
11641 @smallexample @c projectfile
11642    package Builder is
11643       for Default_Switches use Default.Builder'Default_Switches;
11644    end Builder;
11645 @end smallexample
11647 @noindent
11648 In this example, @code{Default} must be either an project imported by the
11649 current project, or the project that the current project extends. If the
11650 attribute is in a package (in this case, in package @code{Builder}), the same
11651 package needs to be specified.
11653 @noindent
11654 A full associative array declaration replaces any other declaration for the
11655 attribute, including other full associative array declaration. Single
11656 associative array associations may be declare after a full associative
11657 declaration, modifying the value for a single association of the attribute.
11659 @node case Constructions
11660 @subsection @code{case} Constructions
11662 @noindent
11663 A @code{case} construction is used in a project file to effect conditional
11664 behavior.
11665 Here is a typical example:
11667 @smallexample @c projectfile
11668 @group
11669 project MyProj is
11670    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11672    OS : OS_Type := external ("OS", "GNU/Linux");
11673 @end group
11675 @group
11676    package Compiler is
11677      case OS is
11678        when "GNU/Linux" | "Unix" =>
11679          for ^Default_Switches^Default_Switches^ ("Ada")
11680              use ("^-gnath^-gnath^");
11681        when "NT" =>
11682          for ^Default_Switches^Default_Switches^ ("Ada")
11683              use ("^-gnatP^-gnatP^");
11684        when others =>
11685      end case;
11686    end Compiler;
11687 end MyProj;
11688 @end group
11689 @end smallexample
11691 @noindent
11692 The syntax of a @code{case} construction is based on the Ada case statement
11693 (although there is no @code{null} construction for empty alternatives).
11695 The case expression must a typed string variable.
11696 Each alternative comprises the reserved word @code{when}, either a list of
11697 literal strings separated by the @code{"|"} character or the reserved word
11698 @code{others},  and the @code{"=>"} token.
11699 Each literal string must belong to the string type that is the type of the
11700 case variable.
11701 An @code{others} alternative, if present, must occur last.
11703 After each @code{=>}, there are zero or more constructions.  The only
11704 constructions allowed in a case construction are other case constructions and
11705 attribute declarations. String type declarations, variable declarations and
11706 package declarations are not allowed.
11708 The value of the case variable is often given by an external reference
11709 (see @ref{External References in Project Files}).
11711 @c ****************************************
11712 @c * Objects and Sources in Project Files *
11713 @c ****************************************
11715 @node Objects and Sources in Project Files
11716 @section Objects and Sources in Project Files
11718 @menu
11719 * Object Directory::
11720 * Exec Directory::
11721 * Source Directories::
11722 * Source File Names::
11723 @end menu
11725 @noindent
11726 Each project has exactly one object directory and one or more source
11727 directories. The source directories must contain at least one source file,
11728 unless  the project file explicitly specifies that no source files are present
11729 (see @ref{Source File Names}).
11731 @node Object Directory
11732 @subsection Object Directory
11734 @noindent
11735 The object directory for a project is the directory containing the compiler's
11736 output (such as @file{ALI} files and object files) for the project's immediate
11737 sources.
11739 The object directory is given by the value of the attribute @code{Object_Dir}
11740 in the project file.
11742 @smallexample @c projectfile
11743    for Object_Dir use "objects";
11744 @end smallexample
11746 @noindent
11747 The attribute @var{Object_Dir} has a string value, the path name of the object
11748 directory. The path name may be absolute or relative to the directory of the
11749 project file. This directory must already exist, and be readable and writable.
11751 By default, when the attribute @code{Object_Dir} is not given an explicit value
11752 or when its value is the empty string, the object directory is the same as the
11753 directory containing the project file.
11755 @node Exec Directory
11756 @subsection Exec Directory
11758 @noindent
11759 The exec directory for a project is the directory containing the executables
11760 for the project's main subprograms.
11762 The exec directory is given by the value of the attribute @code{Exec_Dir}
11763 in the project file.
11765 @smallexample @c projectfile
11766    for Exec_Dir use "executables";
11767 @end smallexample
11769 @noindent
11770 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11771 directory. The path name may be absolute or relative to the directory of the
11772 project file. This directory must already exist, and be writable.
11774 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11775 or when its value is the empty string, the exec directory is the same as the
11776 object directory of the project file.
11778 @node Source Directories
11779 @subsection Source Directories
11781 @noindent
11782 The source directories of a project are specified by the project file
11783 attribute @code{Source_Dirs}.
11785 This attribute's value is a string list. If the attribute is not given an
11786 explicit value, then there is only one source directory, the one where the
11787 project file resides.
11789 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11790 as in
11792 @smallexample @c projectfile
11793     for Source_Dirs use ();
11794 @end smallexample
11796 @noindent
11797 indicates that the project contains no source files.
11799 Otherwise, each string in the string list designates one or more
11800 source directories.
11802 @smallexample @c projectfile
11803    for Source_Dirs use ("sources", "test/drivers");
11804 @end smallexample
11806 @noindent
11807 If a string in the list ends with @code{"/**"},  then the directory whose path
11808 name precedes the two asterisks, as well as all its subdirectories
11809 (recursively), are source directories.
11811 @smallexample @c projectfile
11812    for Source_Dirs use ("/system/sources/**");
11813 @end smallexample
11815 @noindent
11816 Here the directory @code{/system/sources} and all of its subdirectories
11817 (recursively) are source directories.
11819 To specify that the source directories are the directory of the project file
11820 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11821 @smallexample @c projectfile
11822    for Source_Dirs use ("./**");
11823 @end smallexample
11825 @noindent
11826 Each of the source directories must exist and be readable.
11828 @node Source File Names
11829 @subsection Source File Names
11831 @noindent
11832 In a project that contains source files, their names may be specified by the
11833 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11834 (a string). Source file names never include any directory information.
11836 If the attribute @code{Source_Files} is given an explicit value, then each
11837 element of the list is a source file name.
11839 @smallexample @c projectfile
11840    for Source_Files use ("main.adb");
11841    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11842 @end smallexample
11844 @noindent
11845 If the attribute @code{Source_Files} is not given an explicit value,
11846 but the attribute @code{Source_List_File} is given a string value,
11847 then the source file names are contained in the text file whose path name
11848 (absolute or relative to the directory of the project file) is the
11849 value of the attribute @code{Source_List_File}.
11851 Each line in the file that is not empty or is not a comment
11852 contains a source file name.
11854 @smallexample @c projectfile
11855    for Source_List_File use "source_list.txt";
11856 @end smallexample
11858 @noindent
11859 By default, if neither the attribute @code{Source_Files} nor the attribute
11860 @code{Source_List_File} is given an explicit value, then each file in the
11861 source directories that conforms to the project's naming scheme
11862 (see @ref{Naming Schemes}) is an immediate source of the project.
11864 A warning is issued if both attributes @code{Source_Files} and
11865 @code{Source_List_File} are given explicit values. In this case, the attribute
11866 @code{Source_Files} prevails.
11868 Each source file name must be the name of one existing source file
11869 in one of the source directories.
11871 A @code{Source_Files} attribute whose value is an empty list
11872 indicates that there are no source files in the project.
11874 If the order of the source directories is known statically, that is if
11875 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11876 be several files with the same source file name. In this case, only the file
11877 in the first directory is considered as an immediate source of the project
11878 file. If the order of the source directories is not known statically, it is
11879 an error to have several files with the same source file name.
11881 Projects can be specified to have no Ada source
11882 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11883 list, or the @code{"Ada"} may be absent from @code{Languages}:
11885 @smallexample @c projectfile
11886    for Source_Dirs use ();
11887    for Source_Files use ();
11888    for Languages use ("C", "C++");
11889 @end smallexample
11891 @noindent
11892 Otherwise, a project must contain at least one immediate source.
11894 Projects with no source files are useful as template packages
11895 (see @ref{Packages in Project Files}) for other projects; in particular to
11896 define a package @code{Naming} (see @ref{Naming Schemes}).
11898 @c ****************************
11899 @c * Importing Projects *
11900 @c ****************************
11902 @node  Importing Projects
11903 @section Importing Projects
11905 @noindent
11906 An immediate source of a project P may depend on source files that
11907 are neither immediate sources of P nor in the predefined library.
11908 To get this effect, P must @emph{import} the projects that contain the needed
11909 source files.
11911 @smallexample @c projectfile
11912 @group
11913   with "project1", "utilities.gpr";
11914   with "/namings/apex.gpr";
11915   project Main is
11916     ...
11917 @end group
11918 @end smallexample
11920 @noindent
11921 As can be seen in this example, the syntax for importing projects is similar
11922 to the syntax for importing compilation units in Ada. However, project files
11923 use literal strings instead of names, and the @code{with} clause identifies
11924 project files rather than packages.
11926 Each literal string is the file name or path name (absolute or relative) of a
11927 project file. If a string is simply a file name, with no path, then its
11928 location is determined by the @emph{project path}:
11930 @itemize @bullet
11931 @item
11932 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
11933 then the project path includes all the directories in this
11934 ^environment variable^logical name^, plus the directory of the project file.
11936 @item
11937 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
11938 exist, then the project path contains only one directory, namely the one where
11939 the project file is located.
11940 @end itemize
11942 @noindent
11943 If a relative pathname is used, as in
11945 @smallexample @c projectfile
11946   with "tests/proj";
11947 @end smallexample
11949 @noindent
11950 then the path is relative to the directory where the importing project file is
11951 located. Any symbolic link will be fully resolved in the directory
11952 of the importing project file before the imported project file is examined.
11954 If the @code{with}'ed project file name does not have an extension,
11955 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
11956 then the file name as specified in the @code{with} clause (no extension) will
11957 be used. In the above example, if a file @code{project1.gpr} is found, then it
11958 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
11959 then it will be used; if neither file exists, this is an error.
11961 A warning is issued if the name of the project file does not match the
11962 name of the project; this check is case insensitive.
11964 Any source file that is an immediate source of the imported project can be
11965 used by the immediate sources of the importing project, transitively. Thus
11966 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
11967 sources of @code{A} may depend on the immediate sources of @code{C}, even if
11968 @code{A} does not import @code{C} explicitly. However, this is not recommended,
11969 because if and when @code{B} ceases to import @code{C}, some sources in
11970 @code{A} will no longer compile.
11972 A side effect of this capability is that normally cyclic dependencies are not
11973 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
11974 is not allowed to import @code{A}. However, there are cases when cyclic
11975 dependencies would be beneficial. For these cases, another form of import
11976 between projects exists, the @code{limited with}: a project @code{A} that
11977 imports a project @code{B} with a straigh @code{with} may also be imported,
11978 directly or indirectly, by @code{B} on the condition that imports from @code{B}
11979 to @code{A} include at least one @code{limited with}.
11981 @smallexample @c 0projectfile
11982 with "../b/b.gpr";
11983 with "../c/c.gpr";
11984 project A is
11985 end A;
11987 limited with "../a/a.gpr";
11988 project B is
11989 end B;
11991 with "../d/d.gpr";
11992 project C is
11993 end C;
11995 limited with "../a/a.gpr";
11996 project D is
11997 end D;
11998 @end smallexample
12000 @noindent
12001 In the above legal example, there are two project cycles:
12002 @itemize @bullet
12003 @item A-> B-> A
12004 @item A -> C -> D -> A
12005 @end itemize
12007 @noindent
12008 In each of these cycle there is one @code{limited with}: import of @code{A}
12009 from @code{B} and import of @code{A} from @code{D}.
12011 The difference between straight @code{with} and @code{limited with} is that
12012 the name of a project imported with a @code{limited with} cannot be used in the
12013 project that imports it. In particular, its packages cannot be renamed and
12014 its variables cannot be referred to.
12016 An exception to the above rules for @code{limited with} is that for the main
12017 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12018 @code{limited with} is equivalent to a straight @code{with}. For example,
12019 in the example above, projects @code{B} and @code{D} could not be main
12020 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12021 each have a @code{limited with} that is the only one in a cycle of importing
12022 projects.
12024 @c *********************
12025 @c * Project Extension *
12026 @c *********************
12028 @node Project Extension
12029 @section Project Extension
12031 @noindent
12032 During development of a large system, it is sometimes necessary to use
12033 modified versions of some of the source files, without changing the original
12034 sources. This can be achieved through the @emph{project extension} facility.
12036 @smallexample @c projectfile
12037    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12038 @end smallexample
12040 @noindent
12041 A project extension declaration introduces an extending project
12042 (the @emph{child}) and a project being extended (the @emph{parent}).
12044 By default, a child project inherits all the sources of its parent.
12045 However, inherited sources can be overridden: a unit in a parent is hidden
12046 by a unit of the same name in the child.
12048 Inherited sources are considered to be sources (but not immediate sources)
12049 of the child project; see @ref{Project File Syntax}.
12051 An inherited source file retains any switches specified in the parent project.
12053 For example if the project @code{Utilities} contains the specification and the
12054 body of an Ada package @code{Util_IO}, then the project
12055 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12056 The original body of @code{Util_IO} will not be considered in program builds.
12057 However, the package specification will still be found in the project
12058 @code{Utilities}.
12060 A child project can have only one parent but it may import any number of other
12061 projects.
12063 A project is not allowed to import directly or indirectly at the same time a
12064 child project and any of its ancestors.
12066 @c *******************************
12067 @c * Project Hierarchy Extension *
12068 @c *******************************
12070 @node Project Hierarchy Extension
12071 @section Project Hierarchy Extension
12073 @noindent
12074 When extending a large system spanning multiple projects, it is often
12075 inconvenient to extend every project in the hierarchy that is impacted by a
12076 small change introduced. In such cases, it is possible to create a virtual
12077 extension of entire hierarchy using @code{extends all} relationship.
12079 When the project is extended using @code{extends all} inheritance, all projects
12080 that are imported by it, both directly and indirectly, are considered virtually
12081 extended. That is, the Project Manager creates "virtual projects"
12082 that extend every project in the hierarchy; all these virtual projects have
12083 no sources of their own and have as object directory the object directory of
12084 the root of "extending all" project.
12086 It is possible to explicitly extend one or more projects in the hierarchy
12087 in order to modify the sources. These extending projects must be imported by
12088 the "extending all" project, which will replace the corresponding virtual
12089 projects with the explicit ones.
12091 When building such a project hierarchy extension, the Project Manager will
12092 ensure that both modified sources and sources in virtual extending projects
12093 that depend on them, are recompiled.
12095 By means of example, consider the following hierarchy of projects.
12097 @enumerate
12098 @item
12099 project A, containing package P1
12100 @item
12101 project B importing A and containing package P2 which depends on P1
12102 @item
12103 project C importing B and containing package P3 which depends on P2
12104 @end enumerate
12106 @noindent
12107 We want to modify packages P1 and P3.
12109 This project hierarchy will need to be extended as follows:
12111 @enumerate
12112 @item
12113 Create project A1 that extends A, placing modified P1 there:
12115 @smallexample @c 0projectfile
12116 project A1 extends "(...)/A" is
12117 end A1;
12118 @end smallexample
12120 @item
12121 Create project C1 that "extends all" C and imports A1, placing modified
12122 P3 there:
12124 @smallexample @c 0projectfile
12125 with "(...)/A1";
12126 project C1 extends all "(...)/C" is
12127 end C1;
12128 @end smallexample
12129 @end enumerate
12131 When you build project C1, your entire modified project space will be
12132 recompiled, including the virtual project B1 that has been impacted by the
12133 "extending all" inheritance of project C.
12135 Note that if a Library Project in the hierarchy is virtually extended,
12136 the virtual project that extends the Library Project is not a Library Project.
12138 @c ****************************************
12139 @c * External References in Project Files *
12140 @c ****************************************
12142 @node  External References in Project Files
12143 @section External References in Project Files
12145 @noindent
12146 A project file may contain references to external variables; such references
12147 are called @emph{external references}.
12149 An external variable is either defined as part of the environment (an
12150 environment variable in Unix, for example) or else specified on the command
12151 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12152 If both, then the command line value is used.
12154 The value of an external reference is obtained by means of the built-in
12155 function @code{external}, which returns a string value.
12156 This function has two forms:
12157 @itemize @bullet
12158 @item @code{external (external_variable_name)}
12159 @item @code{external (external_variable_name, default_value)}
12160 @end itemize
12162 @noindent
12163 Each parameter must be a string literal.  For example:
12165 @smallexample @c projectfile
12166    external ("USER")
12167    external ("OS", "GNU/Linux")
12168 @end smallexample
12170 @noindent
12171 In the form with one parameter, the function returns the value of
12172 the external variable given as parameter. If this name is not present in the
12173 environment, the function returns an empty string.
12175 In the form with two string parameters, the second argument is
12176 the value returned when the variable given as the first argument is not
12177 present in the environment. In the example above, if @code{"OS"} is not
12178 the name of ^an environment variable^a logical name^ and is not passed on
12179 the command line, then the returned value is @code{"GNU/Linux"}.
12181 An external reference may be part of a string expression or of a string
12182 list expression, and can therefore appear in a variable declaration or
12183 an attribute declaration.
12185 @smallexample @c projectfile
12186 @group
12187    type Mode_Type is ("Debug", "Release");
12188    Mode : Mode_Type := external ("MODE");
12189    case Mode is
12190      when "Debug" =>
12191         ...
12192 @end group
12193 @end smallexample
12195 @c *****************************
12196 @c * Packages in Project Files *
12197 @c *****************************
12199 @node  Packages in Project Files
12200 @section Packages in Project Files
12202 @noindent
12203 A @emph{package} defines the settings for project-aware tools within a
12204 project.
12205 For each such tool one can declare a package; the names for these
12206 packages are preset (see @ref{Packages}).
12207 A package may contain variable declarations, attribute declarations, and case
12208 constructions.
12210 @smallexample @c projectfile
12211 @group
12212    project Proj is
12213       package Builder is  -- used by gnatmake
12214          for ^Default_Switches^Default_Switches^ ("Ada")
12215              use ("^-v^-v^",
12216                   "^-g^-g^");
12217       end Builder;
12218    end Proj;
12219 @end group
12220 @end smallexample
12222 @noindent
12223 The syntax of package declarations mimics that of package in Ada.
12225 Most of the packages have an attribute
12226 @code{^Default_Switches^Default_Switches^}.
12227 This attribute is an associative array, and its value is a string list.
12228 The index of the associative array is the name of a programming language (case
12229 insensitive). This attribute indicates the ^switch^switch^
12230 or ^switches^switches^ to be used
12231 with the corresponding tool.
12233 Some packages also have another attribute, @code{^Switches^Switches^},
12234 an associative array whose value is a string list.
12235 The index is the name of a source file.
12236 This attribute indicates the ^switch^switch^
12237 or ^switches^switches^ to be used by the corresponding
12238 tool when dealing with this specific file.
12240 Further information on these ^switch^switch^-related attributes is found in
12241 @ref{^Switches^Switches^ and Project Files}.
12243 A package may be declared as a @emph{renaming} of another package; e.g., from
12244 the project file for an imported project.
12246 @smallexample @c projectfile
12247 @group
12248   with "/global/apex.gpr";
12249   project Example is
12250     package Naming renames Apex.Naming;
12251     ...
12252   end Example;
12253 @end group
12254 @end smallexample
12256 @noindent
12257 Packages that are renamed in other project files often come from project files
12258 that have no sources: they are just used as templates. Any modification in the
12259 template will be reflected automatically in all the project files that rename
12260 a package from the template.
12262 In addition to the tool-oriented packages, you can also declare a package
12263 named @code{Naming} to establish specialized source file naming conventions
12264 (see @ref{Naming Schemes}).
12266 @c ************************************
12267 @c * Variables from Imported Projects *
12268 @c ************************************
12270 @node Variables from Imported Projects
12271 @section Variables from Imported Projects
12273 @noindent
12274 An attribute or variable defined in an imported or parent project can
12275 be used in expressions in the importing / extending project.
12276 Such an attribute or variable is denoted by an expanded name whose prefix
12277 is either the name of the project or the expanded name of a package within
12278 a project.
12280 @smallexample @c projectfile
12281 @group
12282   with "imported";
12283   project Main extends "base" is
12284      Var1 := Imported.Var;
12285      Var2 := Base.Var & ".new";
12286 @end group
12288 @group
12289      package Builder is
12290         for ^Default_Switches^Default_Switches^ ("Ada")
12291             use Imported.Builder.Ada_^Switches^Switches^ &
12292                 "^-gnatg^-gnatg^" &
12293                 "^-v^-v^";
12294      end Builder;
12295 @end group
12297 @group
12298      package Compiler is
12299         for ^Default_Switches^Default_Switches^ ("Ada")
12300             use Base.Compiler.Ada_^Switches^Switches^;
12301      end Compiler;
12302   end Main;
12303 @end group
12304 @end smallexample
12306 @noindent
12307 In this example:
12309 @itemize @bullet
12310 @item
12311 The value of @code{Var1} is a copy of the variable @code{Var} defined
12312 in the project file @file{"imported.gpr"}
12313 @item
12314 the value of @code{Var2} is a copy of the value of variable @code{Var}
12315 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12316 @item
12317 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12318 @code{Builder} is a string list that includes in its value a copy of the value
12319 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12320 in project file @file{imported.gpr} plus two new elements:
12321 @option{"^-gnatg^-gnatg^"}
12322 and @option{"^-v^-v^"};
12323 @item
12324 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12325 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12326 defined in the @code{Compiler} package in project file @file{base.gpr},
12327 the project being extended.
12328 @end itemize
12330 @c ******************
12331 @c * Naming Schemes *
12332 @c ******************
12334 @node  Naming Schemes
12335 @section Naming Schemes
12337 @noindent
12338 Sometimes an Ada software system is ported from a foreign compilation
12339 environment to GNAT, and the file names do not use the default GNAT
12340 conventions. Instead of changing all the file names (which for a variety
12341 of reasons might not be possible), you can define the relevant file
12342 naming scheme in the @code{Naming} package in your project file.
12344 @noindent
12345 Note that the use of pragmas described in @ref{Alternative
12346 File Naming Schemes} by mean of a configuration pragmas file is not
12347 supported when using project files. You must use the features described
12348 in this paragraph. You can however use specify other configuration
12349 pragmas (see @ref{Specifying Configuration Pragmas}).
12351 @ifclear vms
12352 For example, the following
12353 package models the Apex file naming rules:
12355 @smallexample @c projectfile
12356 @group
12357   package Naming is
12358     for Casing               use "lowercase";
12359     for Dot_Replacement      use ".";
12360     for Spec_Suffix ("Ada")  use ".1.ada";
12361     for Body_Suffix ("Ada")  use ".2.ada";
12362   end Naming;
12363 @end group
12364 @end smallexample
12365 @end ifclear
12367 @ifset vms
12368 For example, the following package models the DEC Ada file naming rules:
12370 @smallexample @c projectfile
12371 @group
12372   package Naming is
12373     for Casing               use "lowercase";
12374     for Dot_Replacement      use "__";
12375     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12376     for Body_Suffix ("Ada")  use ".^ada^ada^";
12377   end Naming;
12378 @end group
12379 @end smallexample
12381 @noindent
12382 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12383 names in lower case)
12384 @end ifset
12386 @noindent
12387 You can define the following attributes in package @code{Naming}:
12389 @table @code
12391 @item @var{Casing}
12392 This must be a string with one of the three values @code{"lowercase"},
12393 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12395 @noindent
12396 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12398 @item @var{Dot_Replacement}
12399 This must be a string whose value satisfies the following conditions:
12401 @itemize @bullet
12402 @item It must not be empty
12403 @item It cannot start or end with an alphanumeric character
12404 @item It cannot be a single underscore
12405 @item It cannot start with an underscore followed by an alphanumeric
12406 @item It cannot contain a dot @code{'.'} except if the entire string
12407 is @code{"."}
12408 @end itemize
12410 @noindent
12411 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12413 @item @var{Spec_Suffix}
12414 This is an associative array (indexed by the programming language name, case
12415 insensitive) whose value is a string that must satisfy the following
12416 conditions:
12418 @itemize @bullet
12419 @item It must not be empty
12420 @item It must include at least one dot
12421 @end itemize
12422 @noindent
12423 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12424 @code{"^.ads^.ADS^"}.
12426 @item @var{Body_Suffix}
12427 This is an associative array (indexed by the programming language name, case
12428 insensitive) whose value is a string that must satisfy the following
12429 conditions:
12431 @itemize @bullet
12432 @item It must not be empty
12433 @item It must include at least one dot
12434 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12435 @end itemize
12436 @noindent
12437 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12438 @code{"^.adb^.ADB^"}.
12440 @item @var{Separate_Suffix}
12441 This must be a string whose value satisfies the same conditions as
12442 @code{Body_Suffix}.
12444 @noindent
12445 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12446 value as @code{Body_Suffix ("Ada")}.
12448 @item @var{Spec}
12449 @noindent
12450 You can use the associative array attribute @code{Spec}  to define
12451 the source file name for an individual Ada compilation unit's spec. The array
12452 index must be a string literal that identifies the Ada unit (case insensitive).
12453 The value of this attribute must be a string that identifies the file that
12454 contains this unit's spec (case sensitive or insensitive depending on the
12455 operating system).
12457 @smallexample @c projectfile
12458    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12459 @end smallexample
12461 @item @var{Body}
12463 You can use the associative array attribute @code{Body} to
12464 define the source file name for an individual Ada compilation unit's body
12465 (possibly a subunit).  The array index must be a string literal that identifies
12466 the Ada unit (case insensitive).  The value of this attribute must be a string
12467 that identifies the file that contains this unit's body or subunit (case
12468 sensitive or insensitive depending on the operating system).
12470 @smallexample @c projectfile
12471    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12472 @end smallexample
12473 @end table
12475 @c ********************
12476 @c * Library Projects *
12477 @c ********************
12479 @node Library Projects
12480 @section Library Projects
12482 @noindent
12483 @emph{Library projects} are projects whose object code is placed in a library.
12484 (Note that this facility is not yet supported on all platforms)
12486 To create a library project, you need to define in its project file
12487 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12488 Additionally, you may define the library-related attributes
12489 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12490 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12492 The @code{Library_Name} attribute has a string value. There is no restriction
12493 on the name of a library. It is the responsability of the developer to
12494 choose a name that will be accepted by the platform. It is recommanded to
12495 choose names that could be Ada identifiers; such names are almost guaranteed
12496 to be acceptable on all platforms.
12498 The @code{Library_Dir} attribute has a string value that designates the path
12499 (absolute or relative) of the directory where the library will reside.
12500 It must designate an existing directory, and this directory must be
12501 different from the project's object directory. It also needs to be writable.
12502 The directory should only be used for one library; the reason is that all
12503 files contained in this directory may be deleted by the Project Manager.
12505 If both @code{Library_Name} and @code{Library_Dir} are specified and
12506 are legal, then the project file defines a library project.  The optional
12507 library-related attributes are checked only for such project files.
12509 The @code{Library_Kind} attribute has a string value that must be one of the
12510 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12511 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
12512 attribute is not specified, the library is a static library, that is
12513 an archive of object files that can be potentially linked into an
12514 static executable. Otherwise, the library may be dynamic or
12515 relocatable, that is a library that is loaded only at the start of execution.
12517 If you need to build both a static and a dynamic library, you should use two
12518 different object directories, since in some cases some extra code needs to
12519 be generated for the latter. For such cases, it is recommended to either use
12520 two different project files, or a single one which uses external variables
12521 to indicate what kind of library should be build.
12523 The @code{Library_Version} attribute has a string value whose interpretation
12524 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12525 used only for dynamic/relocatable libraries as the internal name of the
12526 library (the @code{"soname"}). If the library file name (built from the
12527 @code{Library_Name}) is different from the @code{Library_Version}, then the
12528 library file will be a symbolic link to the actual file whose name will be
12529 @code{Library_Version}.
12531 Example (on Unix):
12533 @smallexample @c projectfile
12534 @group
12535 project Plib is
12537    Version := "1";
12539    for Library_Dir use "lib_dir";
12540    for Library_Name use "dummy";
12541    for Library_Kind use "relocatable";
12542    for Library_Version use "libdummy.so." & Version;
12544 end Plib;
12545 @end group
12546 @end smallexample
12548 @noindent
12549 Directory @file{lib_dir} will contain the internal library file whose name
12550 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12551 @file{libdummy.so.1}.
12553 When @command{gnatmake} detects that a project file
12554 is a library project file, it will check all immediate sources of the project
12555 and rebuild the library if any of the sources have been recompiled.
12557 Standard project files can import library project files. In such cases,
12558 the libraries will only be rebuild if some of its sources are recompiled
12559 because they are in the closure of some other source in an importing project.
12560 Sources of the library project files that are not in such a closure will
12561 not be checked, unless the full library is checked, because one of its sources
12562 needs to be recompiled.
12564 For instance, assume the project file @code{A} imports the library project file
12565 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12566 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12567 @file{l2.ads}, @file{l2.adb}.
12569 If @file{l1.adb} has been modified, then the library associated with @code{L}
12570 will be rebuild when compiling all the immediate sources of @code{A} only
12571 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12572 @code{"with L1;"}.
12574 To be sure that all the sources in the library associated with @code{L} are
12575 up to date, and that all the sources of parject @code{A} are also up to date,
12576 the following two commands needs to be used:
12578 @smallexample
12579 gnatmake -Pl.gpr
12580 gnatmake -Pa.gpr
12581 @end smallexample
12583 When a library is built or rebuilt, an attempt is made first to delete all
12584 files in the library directory.
12585 All @file{ALI} files will also be copied from the object directory to the
12586 library directory. To build executables, @command{gnatmake} will use the
12587 library rather than the individual object files.
12589 @c **********************************************
12590 @c * Using Third-Party Libraries through Projects
12591 @c **********************************************
12592 @node Using Third-Party Libraries through Projects
12593 @section Using Third-Party Libraries through Projects
12595 Whether you are exporting your own library to make it available to
12596 clients, or you are using a library provided by a third party, it is
12597 convenient to have project files that automatically set the correct
12598 command line switches for the compiler and linker.
12600 Such project files are very similar to the library project files;
12601 @xref{Library Projects}. The only difference is that you set the
12602 @code{Source_Dirs} and @code{Object_Dir} attribute so that they point to the
12603 directories where, respectively, the sources and the read-only ALI files have
12604 been installed.
12606 If you need to interface with a set of libraries, as opposed to a
12607 single one, you need to create one library project for each of the
12608 libraries. In addition, a top-level project that imports all these
12609 library projects should be provided, so that the user of your library
12610 has a single @code{with} clause to add to his own projects.
12612 For instance, let's assume you are providing two static libraries
12613 @file{liba.a} and @file{libb.a}. The user needs to link with
12614 both of these libraries. Each of these is associated with its
12615 own set of header files. Let's assume furthermore that all the
12616 header files for the two libraries have been installed in the same
12617 directory @file{headers}. The @file{ALI} files are found in the same
12618 @file{headers} directory.
12620 In this case, you should provide the following three projects:
12622 @smallexample @c projectfile
12623 @group
12624 with "liba", "libb";
12625 project My_Library is
12626   for Source_Dirs use ("headers");
12627   for Object_Dir  use "headers";
12628 end My_Library;
12629 @end group
12631 @group
12632 project Liba is
12633    for Source_Dirs use ();
12634    for Library_Dir use "lib";
12635    for Library_Name use "a";
12636    for Library_Kind use "static";
12637 end Liba;
12638 @end group
12640 @group
12641 project Libb is
12642    for Source_Dirs use ();
12643    for Library_Dir use "lib";
12644    for Library_Name use "b";
12645    for Library_Kind use "static";
12646 end Libb;
12647 @end group
12648 @end smallexample
12650 @c *******************************
12651 @c * Stand-alone Library Projects *
12652 @c *******************************
12654 @node Stand-alone Library Projects
12655 @section Stand-alone Library Projects
12657 @noindent
12658 A Stand-alone Library is a library that contains the necessary code to
12659 elaborate the Ada units that are included in the library. A Stand-alone
12660 Library is suitable to be used in an executable when the main is not
12661 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12662 subprogram.
12664 A Stand-alone Library Project is a Library Project where the library is
12665 a Stand-alone Library.
12667 To be a Stand-alone Library Project, in addition to the two attributes
12668 that make a project a Library Project (@code{Library_Name} and
12669 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12670 @code{Library_Interface} must be defined.
12672 @smallexample @c projectfile
12673 @group
12674    for Library_Dir use "lib_dir";
12675    for Library_Name use "dummy";
12676    for Library_Interface use ("int1", "int1.child");
12677 @end group
12678 @end smallexample
12680 Attribute @code{Library_Interface} has a non empty string list value,
12681 each string in the list designating a unit contained in an immediate source
12682 of the project file.
12684 When a Stand-alone Library is built, first the binder is invoked to build
12685 a package whose name depends on the library name
12686 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12687 This binder-generated package includes initialization and
12688 finalization procedures whose
12689 names depend on the library name (dummyinit and dummyfinal in the example
12690 above). The object corresponding to this package is included in the library.
12692 A dynamic or relocatable Stand-alone Library is automatically initialized
12693 if automatic initialization of Stand-alone Libraries is supported on the
12694 platform and if attribute @code{Library_Auto_Init} is not specified or
12695 is specified with the value "true". A static Stand-alone Library is never
12696 automatically initialized.
12698 Single string attribute @code{Library_Auto_Init} may be specified with only
12699 two possible values: "false" or "true" (case-insensitive). Specifying
12700 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12701 initialization of dynamic or relocatable libraries.
12703 When a non automatically initialized Stand-alone Library is used
12704 in an executable, its initialization procedure must be called before
12705 any service of the library is used.
12706 When the main subprogram is in Ada, it may mean that the initialization
12707 procedure has to be called during elaboration of another package.
12709 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12710 (those that are listed in attribute @code{Library_Interface}) are copied to
12711 the Library Directory. As a consequence, only the Interface Units may be
12712 imported from Ada units outside of the library. If other units are imported,
12713 the binding phase will fail.
12715 When a Stand-Alone Library is bound, the switches that are specified in
12716 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12717 used in the call to @command{gnatbind}.
12719 The string list attribute @code{Library_Options} may be used to specified
12720 additional switches to the call to @command{gcc} to link the library.
12722 The attribute @code{Library_Src_Dir}, may be specified for a
12723 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12724 single string value. Its value must be the path (absolute or relative to the
12725 project directory) of an existing directory. This directory cannot be the
12726 object directory or one of the source directories, but it can be the same as
12727 the library directory. The sources of the Interface
12728 Units of the library, necessary to an Ada client of the library, will be
12729 copied to the designated directory, called Interface Copy directory.
12730 These sources includes the specs of the Interface Units, but they may also
12731 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12732 are used, or when there is a generic units in the spec. Before the sources
12733 are copied to the Interface Copy directory, an attempt is made to delete all
12734 files in the Interface Copy directory.
12736 @c *************************************
12737 @c * Switches Related to Project Files *
12738 @c *************************************
12739 @node Switches Related to Project Files
12740 @section Switches Related to Project Files
12742 @noindent
12743 The following switches are used by GNAT tools that support project files:
12745 @table @option
12747 @item ^-P^/PROJECT_FILE=^@var{project}
12748 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12749 Indicates the name of a project file. This project file will be parsed with
12750 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12751 if any, and using the external references indicated
12752 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12753 @ifclear vms
12754 There may zero, one or more spaces between @option{-P} and @var{project}.
12755 @end ifclear
12757 @noindent
12758 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12760 @noindent
12761 Since the Project Manager parses the project file only after all the switches
12762 on the command line are checked, the order of the switches
12763 @option{^-P^/PROJECT_FILE^},
12764 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12765 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12767 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12768 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12769 Indicates that external variable @var{name} has the value @var{value}.
12770 The Project Manager will use this value for occurrences of
12771 @code{external(name)} when parsing the project file.
12773 @ifclear vms
12774 @noindent
12775 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12776 put between quotes.
12777 @smallexample
12778   -XOS=NT
12779   -X"user=John Doe"
12780 @end smallexample
12781 @end ifclear
12783 @noindent
12784 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12785 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12786 @var{name}, only the last one is used.
12788 @noindent
12789 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12790 takes precedence over the value of the same name in the environment.
12792 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12793 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12794 @c Previous line uses code vs option command, to stay less than 80 chars
12795 Indicates the verbosity of the parsing of GNAT project files.
12797 @ifclear vms
12798 @option{-vP0} means Default;
12799 @option{-vP1} means Medium;
12800 @option{-vP2} means High.
12801 @end ifclear
12803 @ifset vms
12804 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12805 HIGH.
12806 @end ifset
12808 @noindent
12809 The default is ^Default^DEFAULT^: no output for syntactically correct
12810 project files.
12811 @noindent
12812 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12813 only the last one is used.
12815 @end table
12817 @c **********************************
12818 @c * Tools Supporting Project Files *
12819 @c **********************************
12821 @node  Tools Supporting Project Files
12822 @section Tools Supporting Project Files
12824 @menu
12825 * gnatmake and Project Files::
12826 * The GNAT Driver and Project Files::
12827 @ifclear vms
12828 * Glide and Project Files::
12829 @end ifclear
12830 @end menu
12832 @node gnatmake and Project Files
12833 @subsection gnatmake and Project Files
12835 @noindent
12836 This section covers several topics related to @command{gnatmake} and
12837 project files: defining ^switches^switches^ for @command{gnatmake}
12838 and for the tools that it invokes; specifying configuration pragmas;
12839 the use of the @code{Main} attribute; building and rebuilding library project
12840 files.
12842 @menu
12843 * ^Switches^Switches^ and Project Files::
12844 * Specifying Configuration Pragmas::
12845 * Project Files and Main Subprograms::
12846 * Library Project Files::
12847 @end menu
12849 @node ^Switches^Switches^ and Project Files
12850 @subsubsection ^Switches^Switches^ and Project Files
12852 @ifset vms
12853 It is not currently possible to specify VMS style qualifiers in the project
12854 files; only Unix style ^switches^switches^ may be specified.
12855 @end ifset
12857 @noindent
12858 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12859 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12860 attribute, a @code{^Switches^Switches^} attribute, or both;
12861 as their names imply, these ^switch^switch^-related
12862 attributes affect the ^switches^switches^ that are used for each of these GNAT
12863 components when
12864 @command{gnatmake} is invoked.  As will be explained below, these
12865 component-specific ^switches^switches^ precede
12866 the ^switches^switches^ provided on the @command{gnatmake} command line.
12868 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12869 array indexed by language name (case insensitive) whose value is a string list.
12870 For example:
12872 @smallexample @c projectfile
12873 @group
12874 package Compiler is
12875   for ^Default_Switches^Default_Switches^ ("Ada")
12876       use ("^-gnaty^-gnaty^",
12877            "^-v^-v^");
12878 end Compiler;
12879 @end group
12880 @end smallexample
12882 @noindent
12883 The @code{^Switches^Switches^} attribute is also an associative array,
12884 indexed by a file name (which may or may not be case sensitive, depending
12885 on the operating system) whose value is a string list.  For example:
12887 @smallexample @c projectfile
12888 @group
12889 package Builder is
12890    for ^Switches^Switches^ ("main1.adb")
12891        use ("^-O2^-O2^");
12892    for ^Switches^Switches^ ("main2.adb")
12893        use ("^-g^-g^");
12894 end Builder;
12895 @end group
12896 @end smallexample
12898 @noindent
12899 For the @code{Builder} package, the file names must designate source files
12900 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12901 file names must designate @file{ALI} or source files for main subprograms.
12902 In each case just the file name without an explicit extension is acceptable.
12904 For each tool used in a program build (@command{gnatmake}, the compiler, the
12905 binder, and the linker), the corresponding package @dfn{contributes} a set of
12906 ^switches^switches^ for each file on which the tool is invoked, based on the
12907 ^switch^switch^-related attributes defined in the package.
12908 In particular, the ^switches^switches^
12909 that each of these packages contributes for a given file @var{f} comprise:
12911 @itemize @bullet
12912 @item
12913 the value of attribute @code{^Switches^Switches^ (@var{f})},
12914 if it is specified in the package for the given file,
12915 @item
12916 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12917 if it is specified in the package.
12918 @end itemize
12920 @noindent
12921 If neither of these attributes is defined in the package, then the package does
12922 not contribute any ^switches^switches^ for the given file.
12924 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12925 two sets, in the following order: those contributed for the file
12926 by the @code{Builder} package;
12927 and the switches passed on the command line.
12929 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12930 the ^switches^switches^ passed to the tool comprise three sets,
12931 in the following order:
12933 @enumerate
12934 @item
12935 the applicable ^switches^switches^ contributed for the file
12936 by the @code{Builder} package in the project file supplied on the command line;
12938 @item
12939 those contributed for the file by the package (in the relevant project file --
12940 see below) corresponding to the tool; and
12942 @item
12943 the applicable switches passed on the command line.
12944 @end enumerate
12946 @noindent
12947 The term @emph{applicable ^switches^switches^} reflects the fact that
12948 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12949 tools, depending on the individual ^switch^switch^.
12951 @command{gnatmake} may invoke the compiler on source files from different
12952 projects. The Project Manager will use the appropriate project file to
12953 determine the @code{Compiler} package for each source file being compiled.
12954 Likewise for the @code{Binder} and @code{Linker} packages.
12956 As an example, consider the following package in a project file:
12958 @smallexample @c projectfile
12959 @group
12960 project Proj1 is
12961    package Compiler is
12962       for ^Default_Switches^Default_Switches^ ("Ada")
12963           use ("^-g^-g^");
12964       for ^Switches^Switches^ ("a.adb")
12965           use ("^-O1^-O1^");
12966       for ^Switches^Switches^ ("b.adb")
12967           use ("^-O2^-O2^",
12968                "^-gnaty^-gnaty^");
12969    end Compiler;
12970 end Proj1;
12971 @end group
12972 @end smallexample
12974 @noindent
12975 If @command{gnatmake} is invoked with this project file, and it needs to
12976 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12977 @file{a.adb} will be compiled with the ^switch^switch^
12978 @option{^-O1^-O1^},
12979 @file{b.adb} with ^switches^switches^
12980 @option{^-O2^-O2^}
12981 and @option{^-gnaty^-gnaty^},
12982 and @file{c.adb} with @option{^-g^-g^}.
12984 The following example illustrates the ordering of the ^switches^switches^
12985 contributed by different packages:
12987 @smallexample @c projectfile
12988 @group
12989 project Proj2 is
12990    package Builder is
12991       for ^Switches^Switches^ ("main.adb")
12992           use ("^-g^-g^",
12993                "^-O1^-)1^",
12994                "^-f^-f^");
12995    end Builder;
12996 @end group
12998 @group
12999    package Compiler is
13000       for ^Switches^Switches^ ("main.adb")
13001           use ("^-O2^-O2^");
13002    end Compiler;
13003 end Proj2;
13004 @end group
13005 @end smallexample
13007 @noindent
13008 If you issue the command:
13010 @smallexample
13011     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13012 @end smallexample
13014 @noindent
13015 then the compiler will be invoked on @file{main.adb} with the following
13016 sequence of ^switches^switches^
13018 @smallexample
13019    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13020 @end smallexample
13022 with the last @option{^-O^-O^}
13023 ^switch^switch^ having precedence over the earlier ones;
13024 several other ^switches^switches^
13025 (such as @option{^-c^-c^}) are added implicitly.
13027 The ^switches^switches^
13028 @option{^-g^-g^}
13029 and @option{^-O1^-O1^} are contributed by package
13030 @code{Builder},  @option{^-O2^-O2^} is contributed
13031 by the package @code{Compiler}
13032 and @option{^-O0^-O0^} comes from the command line.
13034 The @option{^-g^-g^}
13035 ^switch^switch^ will also be passed in the invocation of
13036 @command{Gnatlink.}
13038 A final example illustrates switch contributions from packages in different
13039 project files:
13041 @smallexample @c projectfile
13042 @group
13043 project Proj3 is
13044    for Source_Files use ("pack.ads", "pack.adb");
13045    package Compiler is
13046       for ^Default_Switches^Default_Switches^ ("Ada")
13047           use ("^-gnata^-gnata^");
13048    end Compiler;
13049 end Proj3;
13050 @end group
13052 @group
13053 with "Proj3";
13054 project Proj4 is
13055    for Source_Files use ("foo_main.adb", "bar_main.adb");
13056    package Builder is
13057       for ^Switches^Switches^ ("foo_main.adb")
13058           use ("^-s^-s^",
13059                "^-g^-g^");
13060    end Builder;
13061 end Proj4;
13062 @end group
13064 @group
13065 -- Ada source file:
13066 with Pack;
13067 procedure Foo_Main is
13068    ...
13069 end Foo_Main;
13070 @end group
13071 @end smallexample
13073 If the command is
13074 @smallexample
13075 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13076 @end smallexample
13078 @noindent
13079 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13080 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13081 @option{^-gnato^-gnato^} (passed on the command line).
13082 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13083 are @option{^-g^-g^} from @code{Proj4.Builder},
13084 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13085 and @option{^-gnato^-gnato^} from the command line.
13087 @noindent
13088 When using @command{gnatmake} with project files, some ^switches^switches^ or
13089 arguments may be expressed as relative paths. As the working directory where
13090 compilation occurs may change, these relative paths are converted to absolute
13091 paths. For the ^switches^switches^ found in a project file, the relative paths
13092 are relative to the project file directory, for the switches on the command
13093 line, they are relative to the directory where @command{gnatmake} is invoked.
13094 The ^switches^switches^ for which this occurs are:
13095 ^-I^-I^,
13096 ^-A^-A^,
13097 ^-L^-L^,
13098 ^-aO^-aO^,
13099 ^-aL^-aL^,
13100 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13101 ^switch^switch^
13102 ^-o^-o^, object files specified in package @code{Linker} or after
13103 -largs on the command line). The exception to this rule is the ^switch^switch^
13104 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13106 @node Specifying Configuration Pragmas
13107 @subsubsection Specifying Configuration Pragmas
13109 When using @command{gnatmake} with project files, if there exists a file
13110 @file{gnat.adc} that contains configuration pragmas, this file will be
13111 ignored.
13113 Configuration pragmas can be defined by means of the following attributes in
13114 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13115 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13117 Both these attributes are single string attributes. Their values is the path
13118 name of a file containing configuration pragmas. If a path name is relative,
13119 then it is relative to the project directory of the project file where the
13120 attribute is defined.
13122 When compiling a source, the configuration pragmas used are, in order,
13123 those listed in the file designated by attribute
13124 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13125 project file, if it is specified, and those listed in the file designated by
13126 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13127 the project file of the source, if it exists.
13129 @node Project Files and Main Subprograms
13130 @subsubsection Project Files and Main Subprograms
13132 @noindent
13133 When using a project file, you can invoke @command{gnatmake}
13134 with one or several main subprograms, by specifying their source files on the
13135 command line.
13137 @smallexample
13138     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13139 @end smallexample
13141 @noindent
13142 Each of these needs to be a source file of the same project, except
13143 when the switch ^-u^/UNIQUE^ is used.
13145 @noindent
13146 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13147 same project, one of the project in the tree rooted at the project specified
13148 on the command line. The package @code{Builder} of this common project, the
13149 "main project" is the one that is considered by @command{gnatmake}.
13151 @noindent
13152 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13153 imported directly or indirectly by the project specified on the command line.
13154 Note that if such a source file is not part of the project specified on the
13155 command line, the ^switches^switches^ found in package @code{Builder} of the
13156 project specified on the command line, if any, that are transmitted
13157 to the compiler will still be used, not those found in the project file of
13158 the source file.
13160 @noindent
13161 When using a project file, you can also invoke @command{gnatmake} without
13162 explicitly specifying any main, and the effect depends on whether you have
13163 defined the @code{Main} attribute.  This attribute has a string list value,
13164 where each element in the list is the name of a source file (the file
13165 extension is optional) that contains a unit that can be a main subprogram.
13167 If the @code{Main} attribute is defined in a project file as a non-empty
13168 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13169 line, then invoking @command{gnatmake} with this project file but without any
13170 main on the command line is equivalent to invoking @command{gnatmake} with all
13171 the file names in the @code{Main} attribute on the command line.
13173 Example:
13174 @smallexample @c projectfile
13175 @group
13176    project Prj is
13177       for Main use ("main1", "main2", "main3");
13178    end Prj;
13179 @end group
13180 @end smallexample
13182 @noindent
13183 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13184 is equivalent to
13185 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13187 When the project attribute @code{Main} is not specified, or is specified
13188 as an empty string list, or when the switch @option{-u} is used on the command
13189 line, then invoking @command{gnatmake} with no main on the command line will
13190 result in all immediate sources of the project file being checked, and
13191 potentially recompiled. Depending on the presence of the switch @option{-u},
13192 sources from other project files on which the immediate sources of the main
13193 project file depend are also checked and potentially recompiled. In other
13194 words, the @option{-u} switch is applied to all of the immediate sources of the
13195 main project file.
13197 When no main is specified on the command line and attribute @code{Main} exists
13198 and includes several mains, or when several mains are specified on the
13199 command line, the default ^switches^switches^ in package @code{Builder} will
13200 be used for all mains, even if there are specific ^switches^switches^
13201 specified for one or several mains.
13203 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13204 the specific ^switches^switches^ for each main, if they are specified.
13206 @node Library Project Files
13207 @subsubsection Library Project Files
13209 @noindent
13210 When @command{gnatmake} is invoked with a main project file that is a library
13211 project file, it is not allowed to specify one or more mains on the command
13212 line.
13214 @noindent
13215 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13216 ^-l^/ACTION=LINK^ have special meanings.
13218 @itemize @bullet
13219 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13220 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13221 library.
13223 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13224 to @command{gnatmake} that the binder generated file should be compiled
13225 (in the case of a stand-alone library) and that the library should be built.
13227 @end itemize
13229 @node The GNAT Driver and Project Files
13230 @subsection The GNAT Driver and Project Files
13232 @noindent
13233 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13234 are project-aware:
13235 @command{^gnatbind^gnatbind^},
13236 @command{^gnatfind^gnatfind^},
13237 @command{^gnatlink^gnatlink^},
13238 @command{^gnatls^gnatls^},
13239 @command{^gnatelim^gnatelim^},
13240 @command{^gnatpp^gnatpp^},
13241 @command{^gnatmetric^gnatmetric^},
13242 @command{^gnatstub^gnatstub^},
13243 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13244 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13245 They must be invoked through the @command{gnat} driver.
13247 The @command{gnat} driver is a front-end that accepts a number of commands and
13248 call the corresponding tool. It has been designed initially for VMS to convert
13249 VMS style qualifiers to Unix style switches, but it is now available to all
13250 the GNAT supported platforms.
13252 On non VMS platforms, the @command{gnat} driver accepts the following commands
13253 (case insensitive):
13255 @itemize @bullet
13256 @item
13257 BIND to invoke @command{^gnatbind^gnatbind^}
13258 @item
13259 CHOP to invoke @command{^gnatchop^gnatchop^}
13260 @item
13261 CLEAN to invoke @command{^gnatclean^gnatclean^}
13262 @item
13263 COMP or COMPILE to invoke the compiler
13264 @item
13265 ELIM to invoke @command{^gnatelim^gnatelim^}
13266 @item
13267 FIND to invoke @command{^gnatfind^gnatfind^}
13268 @item
13269 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13270 @item
13271 LINK to invoke @command{^gnatlink^gnatlink^}
13272 @item
13273 LS or LIST to invoke @command{^gnatls^gnatls^}
13274 @item
13275 MAKE to invoke @command{^gnatmake^gnatmake^}
13276 @item
13277 NAME to invoke @command{^gnatname^gnatname^}
13278 @item
13279 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13280 @item
13281 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13282 @item
13283 METRIC to invoke @command{^gnatmetric^gnatmetric^}
13284 @item
13285 STUB to invoke @command{^gnatstub^gnatstub^}
13286 @item
13287 XREF to invoke @command{^gnatxref^gnatxref^}
13288 @end itemize
13290 @noindent
13291 (note that the compiler is invoked using the command
13292 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13294 @noindent
13295 On non VMS platforms, between @command{gnat} and the command, two
13296 special switches may be used:
13298 @itemize @bullet
13299 @item
13300 @command{-v} to display the invocation of the tool.
13301 @item
13302 @command{-dn} to prevent the @command{gnat} driver from removing
13303 the temporary files it has created. These temporary files are
13304 configuration files and temporary file list files.
13305 @end itemize
13307 @noindent
13308 The command may be followed by switches and arguments for the invoked
13309 tool.
13311 @smallexample
13312   gnat bind -C main.ali
13313   gnat ls -a main
13314   gnat chop foo.txt
13315 @end smallexample
13317 @noindent
13318 Switches may also be put in text files, one switch per line, and the text
13319 files may be specified with their path name preceded by '@@'.
13321 @smallexample
13322    gnat bind @@args.txt main.ali
13323 @end smallexample
13325 @noindent
13326 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13327 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13328 (@option{^-P^/PROJECT_FILE^},
13329 @option{^-X^/EXTERNAL_REFERENCE^} and
13330 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13331 the switches of the invoking tool.
13333 @noindent
13334 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13335 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13336 the immediate sources of the specified project file.
13338 @noindent
13339 When GNAT METRIC is used with a project file, but with no source
13340 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13341 with all the immediate sources of the specified project file and with
13342 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13343 of the project.
13345 @noindent
13346 For each of the following commands, there is optionally a corresponding
13347 package in the main project.
13349 @itemize @bullet
13350 @item
13351 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13353 @item
13354 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13356 @item
13357 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13359 @item
13360 package @code{Eliminate} for command ELIM (invoking
13361 @code{^gnatelim^gnatelim^})
13363 @item
13364 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13366 @item
13367 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13369 @item
13370 package @code{Metrics} for command METRIC
13371 (invoking @code{^gnatmetric^gnatmetric^})
13373 @item
13374 package @code{Pretty_Printer} for command PP or PRETTY
13375 (invoking @code{^gnatpp^gnatpp^})
13377 @item
13378 package @code{Gnatstub} for command STUB
13379 (invoking @code{^gnatstub^gnatstub^})
13381 @item
13382 package @code{Cross_Reference} for command XREF (invoking
13383 @code{^gnatxref^gnatxref^})
13385 @end itemize
13387 @noindent
13388 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13389 a simple variable with a string list value. It contains ^switches^switches^
13390 for the invocation of @code{^gnatls^gnatls^}.
13392 @smallexample @c projectfile
13393 @group
13394 project Proj1 is
13395    package gnatls is
13396       for ^Switches^Switches^
13397           use ("^-a^-a^",
13398                "^-v^-v^");
13399    end gnatls;
13400 end Proj1;
13401 @end group
13402 @end smallexample
13404 @noindent
13405 All other packages have two attribute @code{^Switches^Switches^} and
13406 @code{^Default_Switches^Default_Switches^}.
13408 @noindent
13409 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13410 source file name, that has a string list value: the ^switches^switches^ to be
13411 used when the tool corresponding to the package is invoked for the specific
13412 source file.
13414 @noindent
13415 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13416 indexed by  the programming language that has a string list value.
13417 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13418 ^switches^switches^ for the invocation of the tool corresponding
13419 to the package, except if a specific @code{^Switches^Switches^} attribute
13420 is specified for the source file.
13422 @smallexample @c projectfile
13423 @group
13424 project Proj is
13426    for Source_Dirs use ("./**");
13428    package gnatls is
13429       for ^Switches^Switches^ use
13430           ("^-a^-a^",
13431            "^-v^-v^");
13432    end gnatls;
13433 @end group
13434 @group
13436    package Compiler is
13437       for ^Default_Switches^Default_Switches^ ("Ada")
13438           use ("^-gnatv^-gnatv^",
13439                "^-gnatwa^-gnatwa^");
13440    end Binder;
13441 @end group
13442 @group
13444    package Binder is
13445       for ^Default_Switches^Default_Switches^ ("Ada")
13446           use ("^-C^-C^",
13447                "^-e^-e^");
13448    end Binder;
13449 @end group
13450 @group
13452    package Linker is
13453       for ^Default_Switches^Default_Switches^ ("Ada")
13454           use ("^-C^-C^");
13455       for ^Switches^Switches^ ("main.adb")
13456           use ("^-C^-C^",
13457                "^-v^-v^",
13458                "^-v^-v^");
13459    end Linker;
13460 @end group
13461 @group
13463    package Finder is
13464       for ^Default_Switches^Default_Switches^ ("Ada")
13465            use ("^-a^-a^",
13466                 "^-f^-f^");
13467    end Finder;
13468 @end group
13469 @group
13471    package Cross_Reference is
13472       for ^Default_Switches^Default_Switches^ ("Ada")
13473           use ("^-a^-a^",
13474                "^-f^-f^",
13475                "^-d^-d^",
13476                "^-u^-u^");
13477    end Cross_Reference;
13478 end Proj;
13479 @end group
13480 @end smallexample
13482 @noindent
13483 With the above project file, commands such as
13485 @smallexample
13486    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13487    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13488    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13489    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13490    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13491 @end smallexample
13493 @noindent
13494 will set up the environment properly and invoke the tool with the switches
13495 found in the package corresponding to the tool:
13496 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13497 except @code{^Switches^Switches^ ("main.adb")}
13498 for @code{^gnatlink^gnatlink^}.
13500 @ifclear vms
13501 @node Glide and Project Files
13502 @subsection Glide and Project Files
13504 @noindent
13505 Glide will automatically recognize the @file{.gpr} extension for
13506 project files, and will
13507 convert them to its own internal format automatically. However, it
13508 doesn't provide a syntax-oriented editor for modifying these
13509 files.
13510 The project file will be loaded as text when you select the menu item
13511 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13512 You can edit this text and save the @file{gpr} file;
13513 when you next select this project file in Glide it
13514 will be automatically reloaded.
13515 @end ifclear
13517 @c **********************
13518 @node An Extended Example
13519 @section An Extended Example
13521 @noindent
13522 Suppose that we have two programs, @var{prog1} and @var{prog2},
13523 whose sources are in corresponding directories. We would like
13524 to build them with a single @command{gnatmake} command, and we want to place
13525 their object files into @file{build} subdirectories of the source directories.
13526 Furthermore, we want to have to have two separate subdirectories
13527 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13528 the object files compiled with different set of compilation flags.
13530 In other words, we have the following structure:
13532 @smallexample
13533 @group
13534    main
13535      |- prog1
13536      |    |- build
13537      |         | debug
13538      |         | release
13539      |- prog2
13540           |- build
13541                | debug
13542                | release
13543 @end group
13544 @end smallexample
13546 @noindent
13547 Here are the project files that we must place in a directory @file{main}
13548 to maintain this structure:
13550 @enumerate
13552 @item We create a @code{Common} project with a package @code{Compiler} that
13553 specifies the compilation ^switches^switches^:
13555 @smallexample
13556 File "common.gpr":
13557 @group
13558 @b{project} Common @b{is}
13560    @b{for} Source_Dirs @b{use} (); -- No source files
13561 @end group
13563 @group
13564    @b{type} Build_Type @b{is} ("release", "debug");
13565    Build : Build_Type := External ("BUILD", "debug");
13566 @end group
13567 @group
13568    @b{package} Compiler @b{is}
13569       @b{case} Build @b{is}
13570          @b{when} "release" =>
13571            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13572                    @b{use} ("^-O2^-O2^");
13573          @b{when} "debug"   =>
13574            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13575                    @b{use} ("^-g^-g^");
13576       @b{end case};
13577    @b{end} Compiler;
13579 @b{end} Common;
13580 @end group
13581 @end smallexample
13583 @item We create separate projects for the two programs:
13585 @smallexample
13586 @group
13587 File "prog1.gpr":
13589 @b{with} "common";
13590 @b{project} Prog1 @b{is}
13592     @b{for} Source_Dirs @b{use} ("prog1");
13593     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13595     @b{package} Compiler @b{renames} Common.Compiler;
13597 @b{end} Prog1;
13598 @end group
13599 @end smallexample
13601 @smallexample
13602 @group
13603 File "prog2.gpr":
13605 @b{with} "common";
13606 @b{project} Prog2 @b{is}
13608     @b{for} Source_Dirs @b{use} ("prog2");
13609     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13611     @b{package} Compiler @b{renames} Common.Compiler;
13613 @end group
13614 @b{end} Prog2;
13615 @end smallexample
13617 @item We create a wrapping project @code{Main}:
13619 @smallexample
13620 @group
13621 File "main.gpr":
13623 @b{with} "common";
13624 @b{with} "prog1";
13625 @b{with} "prog2";
13626 @b{project} Main @b{is}
13628    @b{package} Compiler @b{renames} Common.Compiler;
13630 @b{end} Main;
13631 @end group
13632 @end smallexample
13634 @item Finally we need to create a dummy procedure that @code{with}s (either
13635 explicitly or implicitly) all the sources of our two programs.
13637 @end enumerate
13639 @noindent
13640 Now we can build the programs using the command
13642 @smallexample
13643    gnatmake ^-P^/PROJECT_FILE=^main dummy
13644 @end smallexample
13646 @noindent
13647 for the Debug mode, or
13649 @ifclear vms
13650 @smallexample
13651    gnatmake -Pmain -XBUILD=release
13652 @end smallexample
13653 @end ifclear
13655 @ifset vms
13656 @smallexample
13657    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13658 @end smallexample
13659 @end ifset
13661 @noindent
13662 for the Release mode.
13664 @c ********************************
13665 @c * Project File Complete Syntax *
13666 @c ********************************
13668 @node Project File Complete Syntax
13669 @section Project File Complete Syntax
13671 @smallexample
13672 project ::=
13673   context_clause project_declaration
13675 context_clause ::=
13676   @{with_clause@}
13678 with_clause ::=
13679   @b{with} path_name @{ , path_name @} ;
13681 path_name ::=
13682    string_literal
13684 project_declaration ::=
13685   simple_project_declaration | project_extension
13687 simple_project_declaration ::=
13688   @b{project} <project_>simple_name @b{is}
13689     @{declarative_item@}
13690   @b{end} <project_>simple_name;
13692 project_extension ::=
13693   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13694     @{declarative_item@}
13695   @b{end} <project_>simple_name;
13697 declarative_item ::=
13698   package_declaration |
13699   typed_string_declaration |
13700   other_declarative_item
13702 package_declaration ::=
13703   package_specification | package_renaming
13705 package_specification ::=
13706   @b{package} package_identifier @b{is}
13707     @{simple_declarative_item@}
13708   @b{end} package_identifier ;
13710 package_identifier ::=
13711   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13712   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13713   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13715 package_renaming ::==
13716   @b{package} package_identifier @b{renames}
13717        <project_>simple_name.package_identifier ;
13719 typed_string_declaration ::=
13720   @b{type} <typed_string_>_simple_name @b{is}
13721    ( string_literal @{, string_literal@} );
13723 other_declarative_item ::=
13724   attribute_declaration |
13725   typed_variable_declaration |
13726   variable_declaration |
13727   case_construction
13729 attribute_declaration ::=
13730   full_associative_array_declaration |
13731   @b{for} attribute_designator @b{use} expression ;
13733 full_associative_array_declaration ::=
13734   @b{for} <associative_array_attribute_>simple_name @b{use}
13735   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13737 attribute_designator ::=
13738   <simple_attribute_>simple_name |
13739   <associative_array_attribute_>simple_name ( string_literal )
13741 typed_variable_declaration ::=
13742   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13744 variable_declaration ::=
13745   <variable_>simple_name := expression;
13747 expression ::=
13748   term @{& term@}
13750 term ::=
13751   literal_string |
13752   string_list |
13753   <variable_>name |
13754   external_value |
13755   attribute_reference
13757 string_literal ::=
13758   (same as Ada)
13760 string_list ::=
13761   ( <string_>expression @{ , <string_>expression @} )
13763 external_value ::=
13764   @b{external} ( string_literal [, string_literal] )
13766 attribute_reference ::=
13767   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13769 attribute_prefix ::=
13770   @b{project} |
13771   <project_>simple_name | package_identifier |
13772   <project_>simple_name . package_identifier
13774 case_construction ::=
13775   @b{case} <typed_variable_>name @b{is}
13776     @{case_item@}
13777   @b{end case} ;
13779 case_item ::=
13780   @b{when} discrete_choice_list =>
13781       @{case_construction | attribute_declaration@}
13783 discrete_choice_list ::=
13784   string_literal @{| string_literal@} |
13785   @b{others}
13787 name ::=
13788   simple_name @{. simple_name@}
13790 simple_name ::=
13791   identifier (same as Ada)
13793 @end smallexample
13795 @node The Cross-Referencing Tools gnatxref and gnatfind
13796 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13797 @findex gnatxref
13798 @findex gnatfind
13800 @noindent
13801 The compiler generates cross-referencing information (unless
13802 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13803 This information indicates where in the source each entity is declared and
13804 referenced. Note that entities in package Standard are not included, but
13805 entities in all other predefined units are included in the output.
13807 Before using any of these two tools, you need to compile successfully your
13808 application, so that GNAT gets a chance to generate the cross-referencing
13809 information.
13811 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13812 information to provide the user with the capability to easily locate the
13813 declaration and references to an entity. These tools are quite similar,
13814 the difference being that @code{gnatfind} is intended for locating
13815 definitions and/or references to a specified entity or entities, whereas
13816 @code{gnatxref} is oriented to generating a full report of all
13817 cross-references.
13819 To use these tools, you must not compile your application using the
13820 @option{-gnatx} switch on the @file{gnatmake} command line
13821 (see @ref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13822 information will not be generated.
13824 @menu
13825 * gnatxref Switches::
13826 * gnatfind Switches::
13827 * Project Files for gnatxref and gnatfind::
13828 * Regular Expressions in gnatfind and gnatxref::
13829 * Examples of gnatxref Usage::
13830 * Examples of gnatfind Usage::
13831 @end menu
13833 @node gnatxref Switches
13834 @section @code{gnatxref} Switches
13836 @noindent
13837 The command invocation for @code{gnatxref} is:
13838 @smallexample
13839 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13840 @end smallexample
13842 @noindent
13843 where
13845 @table @code
13846 @item sourcefile1, sourcefile2
13847 identifies the source files for which a report is to be generated. The
13848 ``with''ed units will be processed too. You must provide at least one file.
13850 These file names are considered to be regular expressions, so for instance
13851 specifying @file{source*.adb} is the same as giving every file in the current
13852 directory whose name starts with @file{source} and whose extension is
13853 @file{adb}.
13855 You shouldn't specify any directory name, just base names. @command{gnatxref}
13856 and @command{gnatfind} will be able to locate these files by themselves using
13857 the source path. If you specify directories, no result is produced.
13859 @end table
13861 @noindent
13862 The switches can be :
13863 @table @option
13864 @c !sort!
13865 @item ^-a^/ALL_FILES^
13866 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13867 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13868 the read-only files found in the library search path. Otherwise, these files
13869 will be ignored. This option can be used to protect Gnat sources or your own
13870 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13871 much faster, and their output much smaller. Read-only here refers to access
13872 or permissions status in the file system for the current user.
13874 @item -aIDIR
13875 @cindex @option{-aIDIR} (@command{gnatxref})
13876 When looking for source files also look in directory DIR. The order in which
13877 source file search is undertaken is the same as for @file{gnatmake}.
13879 @item -aODIR
13880 @cindex @option{-aODIR} (@command{gnatxref})
13881 When searching for library and object files, look in directory
13882 DIR. The order in which library files are searched is the same as for
13883 @file{gnatmake}.
13885 @item -nostdinc
13886 @cindex @option{-nostdinc} (@command{gnatxref})
13887 Do not look for sources in the system default directory.
13889 @item -nostdlib
13890 @cindex @option{-nostdlib} (@command{gnatxref})
13891 Do not look for library files in the system default directory.
13893 @item --RTS=@var{rts-path}
13894 @cindex @option{--RTS} (@command{gnatxref})
13895 Specifies the default location of the runtime library. Same meaning as the
13896 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13898 @item ^-d^/DERIVED_TYPES^
13899 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13900 If this switch is set @code{gnatxref} will output the parent type
13901 reference for each matching derived types.
13903 @item ^-f^/FULL_PATHNAME^
13904 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13905 If this switch is set, the output file names will be preceded by their
13906 directory (if the file was found in the search path). If this switch is
13907 not set, the directory will not be printed.
13909 @item ^-g^/IGNORE_LOCALS^
13910 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13911 If this switch is set, information is output only for library-level
13912 entities, ignoring local entities. The use of this switch may accelerate
13913 @code{gnatfind} and @code{gnatxref}.
13915 @item -IDIR
13916 @cindex @option{-IDIR} (@command{gnatxref})
13917 Equivalent to @samp{-aODIR -aIDIR}.
13919 @item -pFILE
13920 @cindex @option{-pFILE} (@command{gnatxref})
13921 Specify a project file to use @xref{Project Files}. These project files are
13922 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13923 project files, you should use gnatxref through the GNAT driver
13924 (@command{gnat xref -Pproject}).
13926 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13927 project file in the current directory.
13929 If a project file is either specified or found by the tools, then the content
13930 of the source directory and object directory lines are added as if they
13931 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13932 and @samp{^-aO^OBJECT_SEARCH^}.
13933 @item ^-u^/UNUSED^
13934 Output only unused symbols. This may be really useful if you give your
13935 main compilation unit on the command line, as @code{gnatxref} will then
13936 display every unused entity and 'with'ed package.
13938 @ifclear vms
13939 @item -v
13940 Instead of producing the default output, @code{gnatxref} will generate a
13941 @file{tags} file that can be used by vi. For examples how to use this
13942 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13943 to the standard output, thus you will have to redirect it to a file.
13944 @end ifclear
13946 @end table
13948 @noindent
13949 All these switches may be in any order on the command line, and may even
13950 appear after the file names. They need not be separated by spaces, thus
13951 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13952 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13954 @node gnatfind Switches
13955 @section @code{gnatfind} Switches
13957 @noindent
13958 The command line for @code{gnatfind} is:
13960 @smallexample
13961 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13962       [file1 file2 ...]
13963 @end smallexample
13965 @noindent
13966 where
13968 @table @code
13969 @item pattern
13970 An entity will be output only if it matches the regular expression found
13971 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13973 Omitting the pattern is equivalent to specifying @samp{*}, which
13974 will match any entity. Note that if you do not provide a pattern, you
13975 have to provide both a sourcefile and a line.
13977 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13978 for matching purposes. At the current time there is no support for
13979 8-bit codes other than Latin-1, or for wide characters in identifiers.
13981 @item sourcefile
13982 @code{gnatfind} will look for references, bodies or declarations
13983 of symbols referenced in @file{sourcefile}, at line @samp{line}
13984 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13985 for syntax examples.
13987 @item line
13988 is a decimal integer identifying the line number containing
13989 the reference to the entity (or entities) to be located.
13991 @item column
13992 is a decimal integer identifying the exact location on the
13993 line of the first character of the identifier for the
13994 entity reference. Columns are numbered from 1.
13996 @item file1 file2 ...
13997 The search will be restricted to these source files. If none are given, then
13998 the search will be done for every library file in the search path.
13999 These file must appear only after the pattern or sourcefile.
14001 These file names are considered to be regular expressions, so for instance
14002 specifying 'source*.adb' is the same as giving every file in the current
14003 directory whose name starts with 'source' and whose extension is 'adb'.
14005 The location of the spec of the entity will always be displayed, even if it
14006 isn't in one of file1, file2,... The occurrences of the entity in the
14007 separate units of the ones given on the command line will also be displayed.
14009 Note that if you specify at least one file in this part, @code{gnatfind} may
14010 sometimes not be able to find the body of the subprograms...
14012 @end table
14014 @noindent
14015 At least one of 'sourcefile' or 'pattern' has to be present on
14016 the command line.
14018 The following switches are available:
14019 @table @option
14020 @c !sort!
14022 @item ^-a^/ALL_FILES^
14023 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14024 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14025 the read-only files found in the library search path. Otherwise, these files
14026 will be ignored. This option can be used to protect Gnat sources or your own
14027 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14028 much faster, and their output much smaller. Read-only here refers to access
14029 or permission status in the file system for the current user.
14031 @item -aIDIR
14032 @cindex @option{-aIDIR} (@command{gnatfind})
14033 When looking for source files also look in directory DIR. The order in which
14034 source file search is undertaken is the same as for @file{gnatmake}.
14036 @item -aODIR
14037 @cindex @option{-aODIR} (@command{gnatfind})
14038 When searching for library and object files, look in directory
14039 DIR. The order in which library files are searched is the same as for
14040 @file{gnatmake}.
14042 @item -nostdinc
14043 @cindex @option{-nostdinc} (@command{gnatfind})
14044 Do not look for sources in the system default directory.
14046 @item -nostdlib
14047 @cindex @option{-nostdlib} (@command{gnatfind})
14048 Do not look for library files in the system default directory.
14050 @item --RTS=@var{rts-path}
14051 @cindex @option{--RTS} (@command{gnatfind})
14052 Specifies the default location of the runtime library. Same meaning as the
14053 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
14055 @item ^-d^/DERIVED_TYPE_INFORMATION^
14056 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14057 If this switch is set, then @code{gnatfind} will output the parent type
14058 reference for each matching derived types.
14060 @item ^-e^/EXPRESSIONS^
14061 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14062 By default, @code{gnatfind} accept the simple regular expression set for
14063 @samp{pattern}. If this switch is set, then the pattern will be
14064 considered as full Unix-style regular expression.
14066 @item ^-f^/FULL_PATHNAME^
14067 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14068 If this switch is set, the output file names will be preceded by their
14069 directory (if the file was found in the search path). If this switch is
14070 not set, the directory will not be printed.
14072 @item ^-g^/IGNORE_LOCALS^
14073 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14074 If this switch is set, information is output only for library-level
14075 entities, ignoring local entities. The use of this switch may accelerate
14076 @code{gnatfind} and @code{gnatxref}.
14078 @item -IDIR
14079 @cindex @option{-IDIR} (@command{gnatfind})
14080 Equivalent to @samp{-aODIR -aIDIR}.
14082 @item -pFILE
14083 @cindex @option{-pFILE} (@command{gnatfind})
14084 Specify a project file (@pxref{Project Files}) to use.
14085 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14086 project file in the current directory.
14088 If a project file is either specified or found by the tools, then the content
14089 of the source directory and object directory lines are added as if they
14090 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14091 @samp{^-aO^/OBJECT_SEARCH^}.
14093 @item ^-r^/REFERENCES^
14094 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14095 By default, @code{gnatfind} will output only the information about the
14096 declaration, body or type completion of the entities. If this switch is
14097 set, the @code{gnatfind} will locate every reference to the entities in
14098 the files specified on the command line (or in every file in the search
14099 path if no file is given on the command line).
14101 @item ^-s^/PRINT_LINES^
14102 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14103 If this switch is set, then @code{gnatfind} will output the content
14104 of the Ada source file lines were the entity was found.
14106 @item ^-t^/TYPE_HIERARCHY^
14107 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14108 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14109 the specified type. It act like -d option but recursively from parent
14110 type to parent type. When this switch is set it is not possible to
14111 specify more than one file.
14113 @end table
14115 @noindent
14116 All these switches may be in any order on the command line, and may even
14117 appear after the file names. They need not be separated by spaces, thus
14118 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14119 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14121 As stated previously, gnatfind will search in every directory in the
14122 search path. You can force it to look only in the current directory if
14123 you specify @code{*} at the end of the command line.
14125 @node Project Files for gnatxref and gnatfind
14126 @section Project Files for @command{gnatxref} and @command{gnatfind}
14128 @noindent
14129 Project files allow a programmer to specify how to compile its
14130 application, where to find sources, etc.  These files are used
14131 @ifclear vms
14132 primarily by the Glide Ada mode, but they can also be used
14133 @end ifclear
14134 by the two tools
14135 @code{gnatxref} and @code{gnatfind}.
14137 A project file name must end with @file{.gpr}. If a single one is
14138 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14139 extract the information from it. If multiple project files are found, none of
14140 them is read, and you have to use the @samp{-p} switch to specify the one
14141 you want to use.
14143 The following lines can be included, even though most of them have default
14144 values which can be used in most cases.
14145 The lines can be entered in any order in the file.
14146 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14147 each line. If you have multiple instances, only the last one is taken into
14148 account.
14150 @table @code
14151 @item src_dir=DIR
14152 [default: @code{"^./^[]^"}]
14153 specifies a directory where to look for source files. Multiple @code{src_dir}
14154 lines can be specified and they will be searched in the order they
14155 are specified.
14157 @item obj_dir=DIR
14158 [default: @code{"^./^[]^"}]
14159 specifies a directory where to look for object and library files. Multiple
14160 @code{obj_dir} lines can be specified, and they will be searched in the order
14161 they are specified
14163 @item comp_opt=SWITCHES
14164 [default: @code{""}]
14165 creates a variable which can be referred to subsequently by using
14166 the @code{$@{comp_opt@}} notation. This is intended to store the default
14167 switches given to @command{gnatmake} and @command{gcc}.
14169 @item bind_opt=SWITCHES
14170 [default: @code{""}]
14171 creates a variable which can be referred to subsequently by using
14172 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14173 switches given to @command{gnatbind}.
14175 @item link_opt=SWITCHES
14176 [default: @code{""}]
14177 creates a variable which can be referred to subsequently by using
14178 the @samp{$@{link_opt@}} notation. This is intended to store the default
14179 switches given to @command{gnatlink}.
14181 @item main=EXECUTABLE
14182 [default: @code{""}]
14183 specifies the name of the executable for the application. This variable can
14184 be referred to in the following lines by using the @samp{$@{main@}} notation.
14186 @ifset vms
14187 @item comp_cmd=COMMAND
14188 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14189 @end ifset
14190 @ifclear vms
14191 @item comp_cmd=COMMAND
14192 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14193 @end ifclear
14194 specifies the command used to compile a single file in the application.
14196 @ifset vms
14197 @item make_cmd=COMMAND
14198 [default: @code{"GNAT MAKE $@{main@}
14199 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14200 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14201 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14202 @end ifset
14203 @ifclear vms
14204 @item make_cmd=COMMAND
14205 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14206  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14207  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14208 @end ifclear
14209 specifies the command used to recompile the whole application.
14211 @item run_cmd=COMMAND
14212 [default: @code{"$@{main@}"}]
14213 specifies the command used to run the application.
14215 @item debug_cmd=COMMAND
14216 [default: @code{"gdb $@{main@}"}]
14217 specifies the command used to debug the application
14219 @end table
14221 @noindent
14222 @command{gnatxref} and @command{gnatfind} only take into account the
14223 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14225 @node Regular Expressions in gnatfind and gnatxref
14226 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14228 @noindent
14229 As specified in the section about @command{gnatfind}, the pattern can be a
14230 regular expression. Actually, there are to set of regular expressions
14231 which are recognized by the program :
14233 @table @code
14234 @item globbing patterns
14235 These are the most usual regular expression. They are the same that you
14236 generally used in a Unix shell command line, or in a DOS session.
14238 Here is a more formal grammar :
14239 @smallexample
14240 @group
14241 @iftex
14242 @leftskip=.5cm
14243 @end iftex
14244 regexp ::= term
14245 term   ::= elmt            -- matches elmt
14246 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14247 term   ::= *               -- any string of 0 or more characters
14248 term   ::= ?               -- matches any character
14249 term   ::= [char @{char@}] -- matches any character listed
14250 term   ::= [char - char]   -- matches any character in range
14251 @end group
14252 @end smallexample
14254 @item full regular expression
14255 The second set of regular expressions is much more powerful. This is the
14256 type of regular expressions recognized by utilities such a @file{grep}.
14258 The following is the form of a regular expression, expressed in Ada
14259 reference manual style BNF is as follows
14261 @smallexample
14262 @iftex
14263 @leftskip=.5cm
14264 @end iftex
14265 @group
14266 regexp ::= term @{| term@} -- alternation (term or term ...)
14268 term ::= item @{item@}     -- concatenation (item then item)
14270 item ::= elmt              -- match elmt
14271 item ::= elmt *            -- zero or more elmt's
14272 item ::= elmt +            -- one or more elmt's
14273 item ::= elmt ?            -- matches elmt or nothing
14274 @end group
14275 @group
14276 elmt ::= nschar            -- matches given character
14277 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14278 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14279 elmt ::= [char - char]     -- matches chars in given range
14280 elmt ::= \ char            -- matches given character
14281 elmt ::= .                 -- matches any single character
14282 elmt ::= ( regexp )        -- parens used for grouping
14284 char ::= any character, including special characters
14285 nschar ::= any character except ()[].*+?^^^
14286 @end group
14287 @end smallexample
14289 Following are a few examples :
14291 @table @samp
14292 @item abcde|fghi
14293 will match any of the two strings 'abcde' and 'fghi'.
14295 @item abc*d
14296 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14298 @item [a-z]+
14299 will match any string which has only lowercase characters in it (and at
14300 least one character
14302 @end table
14303 @end table
14305 @node Examples of gnatxref Usage
14306 @section Examples of @code{gnatxref} Usage
14308 @subsection General Usage
14310 @noindent
14311 For the following examples, we will consider the following units :
14313 @smallexample @c ada
14314 @group
14315 @cartouche
14316 main.ads:
14317 1: with Bar;
14318 2: package Main is
14319 3:     procedure Foo (B : in Integer);
14320 4:     C : Integer;
14321 5: private
14322 6:     D : Integer;
14323 7: end Main;
14325 main.adb:
14326 1: package body Main is
14327 2:     procedure Foo (B : in Integer) is
14328 3:     begin
14329 4:        C := B;
14330 5:        D := B;
14331 6:        Bar.Print (B);
14332 7:        Bar.Print (C);
14333 8:     end Foo;
14334 9: end Main;
14336 bar.ads:
14337 1: package Bar is
14338 2:     procedure Print (B : Integer);
14339 3: end bar;
14340 @end cartouche
14341 @end group
14342 @end smallexample
14344 @table @code
14346 @noindent
14347 The first thing to do is to recompile your application (for instance, in
14348 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14349 the cross-referencing information.
14350 You can then issue any of the following commands:
14352 @item gnatxref main.adb
14353 @code{gnatxref} generates cross-reference information for main.adb
14354 and every unit 'with'ed by main.adb.
14356 The output would be:
14357 @smallexample
14358 @iftex
14359 @leftskip=0cm
14360 @end iftex
14361 B                                                      Type: Integer
14362   Decl: bar.ads           2:22
14363 B                                                      Type: Integer
14364   Decl: main.ads          3:20
14365   Body: main.adb          2:20
14366   Ref:  main.adb          4:13     5:13     6:19
14367 Bar                                                    Type: Unit
14368   Decl: bar.ads           1:9
14369   Ref:  main.adb          6:8      7:8
14370        main.ads           1:6
14371 C                                                      Type: Integer
14372   Decl: main.ads          4:5
14373   Modi: main.adb          4:8
14374   Ref:  main.adb          7:19
14375 D                                                      Type: Integer
14376   Decl: main.ads          6:5
14377   Modi: main.adb          5:8
14378 Foo                                                    Type: Unit
14379   Decl: main.ads          3:15
14380   Body: main.adb          2:15
14381 Main                                                    Type: Unit
14382   Decl: main.ads          2:9
14383   Body: main.adb          1:14
14384 Print                                                   Type: Unit
14385   Decl: bar.ads           2:15
14386   Ref:  main.adb          6:12     7:12
14387 @end smallexample
14389 @noindent
14390 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14391 its body is in main.adb, line 1, column 14 and is not referenced any where.
14393 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14394 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14396 @item gnatxref package1.adb package2.ads
14397 @code{gnatxref} will generates cross-reference information for
14398 package1.adb, package2.ads and any other package 'with'ed by any
14399 of these.
14401 @end table
14403 @ifclear vms
14404 @subsection Using gnatxref with vi
14406 @code{gnatxref} can generate a tags file output, which can be used
14407 directly from @file{vi}. Note that the standard version of @file{vi}
14408 will not work properly with overloaded symbols. Consider using another
14409 free implementation of @file{vi}, such as @file{vim}.
14411 @smallexample
14412 $ gnatxref -v gnatfind.adb > tags
14413 @end smallexample
14415 @noindent
14416 will generate the tags file for @code{gnatfind} itself (if the sources
14417 are in the search path!).
14419 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14420 (replacing @i{entity} by whatever you are looking for), and vi will
14421 display a new file with the corresponding declaration of entity.
14422 @end ifclear
14424 @node Examples of gnatfind Usage
14425 @section Examples of @code{gnatfind} Usage
14427 @table @code
14429 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14430 Find declarations for all entities xyz referenced at least once in
14431 main.adb. The references are search in every library file in the search
14432 path.
14434 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14435 switch is set)
14437 The output will look like:
14438 @smallexample
14439 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14440 ^directory/^[directory]^main.adb:24:10: xyz <= body
14441 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14442 @end smallexample
14444 @noindent
14445 that is to say, one of the entities xyz found in main.adb is declared at
14446 line 12 of main.ads (and its body is in main.adb), and another one is
14447 declared at line 45 of foo.ads
14449 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14450 This is the same command as the previous one, instead @code{gnatfind} will
14451 display the content of the Ada source file lines.
14453 The output will look like:
14455 @smallexample
14456 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14457    procedure xyz;
14458 ^directory/^[directory]^main.adb:24:10: xyz <= body
14459    procedure xyz is
14460 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14461    xyz : Integer;
14462 @end smallexample
14464 @noindent
14465 This can make it easier to find exactly the location your are looking
14466 for.
14468 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14469 Find references to all entities containing an x that are
14470 referenced on line 123 of main.ads.
14471 The references will be searched only in main.ads and foo.adb.
14473 @item gnatfind main.ads:123
14474 Find declarations and bodies for all entities that are referenced on
14475 line 123 of main.ads.
14477 This is the same as @code{gnatfind "*":main.adb:123}.
14479 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14480 Find the declaration for the entity referenced at column 45 in
14481 line 123 of file main.adb in directory mydir. Note that it
14482 is usual to omit the identifier name when the column is given,
14483 since the column position identifies a unique reference.
14485 The column has to be the beginning of the identifier, and should not
14486 point to any character in the middle of the identifier.
14488 @end table
14490 @c *********************************
14491 @node The GNAT Pretty-Printer gnatpp
14492 @chapter The GNAT Pretty-Printer @command{gnatpp}
14493 @findex gnatpp
14494 @cindex Pretty-Printer
14496 @noindent
14497 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14498 for source reformatting / pretty-printing.
14499 It takes an Ada source file as input and generates a reformatted
14500 version as output.
14501 You can specify various style directives via switches; e.g.,
14502 identifier case conventions, rules of indentation, and comment layout.
14504 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14505 tree for the input source and thus requires the input to be syntactically and
14506 semantically legal.
14507 If this condition is not met, @command{gnatpp} will terminate with an
14508 error message; no output file will be generated.
14510 If the compilation unit
14511 contained in the input source depends semantically upon units located
14512 outside the current directory, you have to provide the source search path
14513 when invoking @command{gnatpp}, if these units are contained in files with
14514 names that do not follow the GNAT file naming rules, you have to provide
14515 the configuration file describing the corresponding naming scheme;
14516 see the description of the @command{gnatpp}
14517 switches below. Another possibility is to use a project file and to
14518 call @command{gnatpp} through the @command{gnat} driver
14520 The @command{gnatpp} command has the form
14522 @smallexample
14523 $ gnatpp [@var{switches}] @var{filename}
14524 @end smallexample
14526 @noindent
14527 where
14528 @itemize @bullet
14529 @item
14530 @var{switches} is an optional sequence of switches defining such properties as
14531 the formatting rules, the source search path, and the destination for the
14532 output source file
14534 @item
14535 @var{filename} is the name (including the extension) of the source file to
14536 reformat; ``wildcards'' or several file names on the same gnatpp command are
14537 allowed.  The file name may contain path information; it does not have to
14538 follow the GNAT file naming rules
14539 @end itemize
14541 @menu
14542 * Switches for gnatpp::
14543 * Formatting Rules::
14544 @end menu
14546 @node Switches for gnatpp
14547 @section Switches for @command{gnatpp}
14549 @noindent
14550 The following subsections describe the various switches accepted by
14551 @command{gnatpp}, organized by category.
14553 @ifclear vms
14554 You specify a switch by supplying a name and generally also a value.
14555 In many cases the values for a switch with a given name are incompatible with
14556 each other
14557 (for example the switch that controls the casing of a reserved word may have
14558 exactly one value: upper case, lower case, or
14559 mixed case) and thus exactly one such switch can be in effect for an
14560 invocation of @command{gnatpp}.
14561 If more than one is supplied, the last one is used.
14562 However, some values for the same switch are mutually compatible.
14563 You may supply several such switches to @command{gnatpp}, but then
14564 each must be specified in full, with both the name and the value.
14565 Abbreviated forms (the name appearing once, followed by each value) are
14566 not permitted.
14567 For example, to set
14568 the alignment of the assignment delimiter both in declarations and in
14569 assignment statements, you must write @option{-A2A3}
14570 (or @option{-A2 -A3}), but not @option{-A23}.
14571 @end ifclear
14573 @ifset vms
14574 In many cases the set of options for a given qualifier are incompatible with
14575 each other (for example the qualifier that controls the casing of a reserved
14576 word may have exactly one option, which specifies either upper case, lower
14577 case, or mixed case), and thus exactly one such option can be in effect for
14578 an invocation of @command{gnatpp}.
14579 If more than one is supplied, the last one is used.
14580 However, some qualifiers have options that are mutually compatible,
14581 and then you may then supply several such options when invoking
14582 @command{gnatpp}.
14583 @end ifset
14585 In most cases, it is obvious whether or not the
14586 ^values for a switch with a given name^options for a given qualifier^
14587 are compatible with each other.
14588 When the semantics might not be evident, the summaries below explicitly
14589 indicate the effect.
14591 @menu
14592 * Alignment Control::
14593 * Casing Control::
14594 * Construct Layout Control::
14595 * General Text Layout Control::
14596 * Other Formatting Options::
14597 * Setting the Source Search Path::
14598 * Output File Control::
14599 * Other gnatpp Switches::
14600 @end menu
14602 @node Alignment Control
14603 @subsection Alignment Control
14604 @cindex Alignment control in @command{gnatpp}
14606 @noindent
14607 Programs can be easier to read if certain constructs are vertically aligned.
14608 By default all alignments are set ON.
14609 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14610 OFF, and then use one or more of the other
14611 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14612 to activate alignment for specific constructs.
14614 @table @option
14615 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14617 @ifset vms
14618 @item /ALIGN=ON
14619 Set all alignments to ON
14620 @end ifset
14622 @item ^-A0^/ALIGN=OFF^
14623 Set all alignments to OFF
14625 @item ^-A1^/ALIGN=COLONS^
14626 Align @code{:} in declarations
14628 @item ^-A2^/ALIGN=DECLARATIONS^
14629 Align @code{:=} in initializations in declarations
14631 @item ^-A3^/ALIGN=STATEMENTS^
14632 Align @code{:=} in assignment statements
14634 @item ^-A4^/ALIGN=ARROWS^
14635 Align @code{=>} in associations
14636 @end table
14638 @noindent
14639 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14640 is allowed.
14642 @node Casing Control
14643 @subsection Casing Control
14644 @cindex Casing control in @command{gnatpp}
14646 @noindent
14647 @command{gnatpp} allows you to specify the casing for reserved words,
14648 pragma names, attribute designators and identifiers.
14649 For identifiers you may define a
14650 general rule for name casing but also override this rule
14651 via a set of dictionary files.
14653 Three types of casing are supported: lower case, upper case, and mixed case.
14654 Lower and upper case are self-explanatory (but since some letters in
14655 Latin1 and other GNAT-supported character sets
14656 exist only in lower-case form, an upper case conversion will have no
14657 effect on them.)
14658 ``Mixed case'' means that the first letter, and also each letter immediately
14659 following an underscore, are converted to their uppercase forms;
14660 all the other letters are converted to their lowercase forms.
14662 @table @option
14663 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14664 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14665 Attribute designators are lower case
14667 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14668 Attribute designators are upper case
14670 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14671 Attribute designators are mixed case (this is the default)
14673 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14674 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14675 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14676 lower case (this is the default)
14678 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14679 Keywords are upper case
14681 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14682 @item ^-nD^/NAME_CASING=AS_DECLARED^
14683 Name casing for defining occurrences are as they appear in the source file
14684 (this is the default)
14686 @item ^-nU^/NAME_CASING=UPPER_CASE^
14687 Names are in upper case
14689 @item ^-nL^/NAME_CASING=LOWER_CASE^
14690 Names are in lower case
14692 @item ^-nM^/NAME_CASING=MIXED_CASE^
14693 Names are in mixed case
14695 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14696 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14697 Pragma names are lower case
14699 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14700 Pragma names are upper case
14702 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14703 Pragma names are mixed case (this is the default)
14705 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14706 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14707 Use @var{file} as a @emph{dictionary file} that defines
14708 the casing for a set of specified names,
14709 thereby overriding the effect on these names by
14710 any explicit or implicit
14711 ^-n^/NAME_CASING^ switch.
14712 To supply more than one dictionary file,
14713 use ^several @option{-D} switches^a list of files as options^.
14715 @noindent
14716 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14717 to define the casing for the Ada predefined names and
14718 the names declared in the GNAT libraries.
14720 @item ^-D-^/SPECIFIC_CASING^
14721 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14722 Do not use the default dictionary file;
14723 instead, use the casing
14724 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14725 dictionary file(s)
14726 @end table
14728 @noindent
14729 The structure of a dictionary file, and details on the conventions
14730 used in the default dictionary file, are defined in @ref{Name Casing}.
14732 The @option{^-D-^/SPECIFIC_CASING^} and
14733 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14734 compatible.
14736 @node Construct Layout Control
14737 @subsection Construct Layout Control
14738 @cindex Layout control in @command{gnatpp}
14740 @noindent
14741 This group of @command{gnatpp} switches controls the layout of comments and
14742 complex syntactic constructs.  See @ref{Formatting Comments}, for details
14743 on their effect.
14745 @table @option
14746 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14747 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14748 All the comments remain unchanged
14750 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14751 GNAT-style comment line indentation (this is the default).
14753 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14754 Reference-manual comment line indentation.
14756 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14757 GNAT-style comment beginning
14759 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14760 Reformat comment blocks
14762 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14763 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14764 GNAT-style layout (this is the default)
14766 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14767 Compact layout
14769 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14770 Uncompact layout
14772 @item ^-notab^/NOTABS^
14773 All the VT characters are removed from the comment text. All the HT characters
14774 are expanded with the sequences of space characters to get to the next tab
14775 stops.
14777 @end table
14779 @ifclear vms
14780 @noindent
14781 The @option{-c1} and @option{-c2} switches are incompatible.
14782 The @option{-c3} and @option{-c4} switches are compatible with each other and
14783 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14784 the other comment formatting switches.
14786 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14787 @end ifclear
14789 @ifset vms
14790 @noindent
14791 For the @option{/COMMENTS_LAYOUT} qualifier:
14792 @itemize @bullet
14793 @item
14794 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14795 @item
14796 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14797 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14798 @end itemize
14800 @noindent
14801 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14802 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14803 @end ifset
14805 @node General Text Layout Control
14806 @subsection General Text Layout Control
14808 @noindent
14809 These switches allow control over line length and indentation.
14811 @table @option
14812 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14813 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14814 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14816 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14817 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14818 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14820 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14821 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14822 Indentation level for continuation lines (relative to the line being
14823 continued), @i{nnn} from 1 .. 9.
14824 The default
14825 value is one less then the (normal) indentation level, unless the
14826 indentation is set to 1 (in which case the default value for continuation
14827 line indentation is also 1)
14828 @end table
14830 @node Other Formatting Options
14831 @subsection Other Formatting Options
14833 @noindent
14834 These switches control the inclusion of missing end/exit labels, and
14835 the indentation level in @b{case} statements.
14837 @table @option
14838 @item ^-e^/NO_MISSED_LABELS^
14839 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14840 Do not insert missing end/exit labels. An end label is the name of
14841 a construct that may optionally be repeated at the end of the
14842 construct's declaration;
14843 e.g., the names of packages, subprograms, and tasks.
14844 An exit label is the name of a loop that may appear as target
14845 of an exit statement within the loop.
14846 By default, @command{gnatpp} inserts these end/exit labels when
14847 they are absent from the original source. This option suppresses such
14848 insertion, so that the formatted source reflects the original.
14850 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14851 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14852 Insert a Form Feed character after a pragma Page.
14854 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14855 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14856 Do not use an additional indentation level for @b{case} alternatives
14857 and variants if there are @i{nnn} or more (the default
14858 value is 10).
14859 If @i{nnn} is 0, an additional indentation level is
14860 used for @b{case} alternatives and variants regardless of their number.
14861 @end table
14863 @node Setting the Source Search Path
14864 @subsection Setting the Source Search Path
14866 @noindent
14867 To define the search path for the input source file, @command{gnatpp}
14868 uses the same switches as the GNAT compiler, with the same effects.
14870 @table @option
14871 @item ^-I^/SEARCH=^@var{dir}
14872 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14873 The same as the corresponding gcc switch
14875 @item ^-I-^/NOCURRENT_DIRECTORY^
14876 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14877 The same as the corresponding gcc switch
14879 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14880 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14881 The same as the corresponding gcc switch
14883 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14884 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14885 The same as the corresponding gcc switch
14887 @end table
14889 @node Output File Control
14890 @subsection Output File Control
14892 @noindent
14893 By default the output is sent to the file whose name is obtained by appending
14894 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14895 (if the file with this name already exists, it is unconditionally overwritten).
14896 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14897 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14898 as output file.
14899 The output may be redirected by the following switches:
14901 @table @option
14902 @item ^-pipe^/STANDARD_OUTPUT^
14903 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14904 Send the output to @code{Standard_Output}
14906 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14907 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14908 Write the output into @var{output_file}.
14909 If @var{output_file} already exists, @command{gnatpp} terminates without
14910 reading or processing the input file.
14912 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14913 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14914 Write the output into @var{output_file}, overwriting the existing file
14915 (if one is present).
14917 @item ^-r^/REPLACE^
14918 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14919 Replace the input source file with the reformatted output, and copy the
14920 original input source into the file whose name is obtained by appending the
14921 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14922 If a file with this name already exists, @command{gnatpp} terminates without
14923 reading or processing the input file.
14925 @item ^-rf^/OVERRIDING_REPLACE^
14926 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14927 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14928 already exists, it is overwritten.
14930 @item ^-rnb^/NO_BACKUP^
14931 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
14932 Replace the input source file with the reformatted output without
14933 creating any backup copy of the input source.
14934 @end table
14936 @noindent
14937 Options @option{^-pipe^/STANDARD_OUTPUT^},
14938 @option{^-o^/OUTPUT^} and
14939 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14940 contains only one file to reformat
14942 @node Other gnatpp Switches
14943 @subsection Other @code{gnatpp} Switches
14945 @noindent
14946 The additional @command{gnatpp} switches are defined in this subsection.
14948 @table @option
14949 @item ^-files @var{filename}^/FILES=@var{output_file}^
14950 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14951 Take the argument source files from the specified file. This file should be an
14952 ordinary textual file containing file names separated by spaces or
14953 line breaks. You can use this switch more then once in the same call to
14954 @command{gnatpp}. You also can combine this switch with explicit list of
14955 files.
14957 @item ^-v^/VERBOSE^
14958 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14959 Verbose mode;
14960 @command{gnatpp} generates version information and then
14961 a trace of the actions it takes to produce or obtain the ASIS tree.
14963 @item ^-w^/WARNINGS^
14964 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14965 Warning mode;
14966 @command{gnatpp} generates a warning whenever it can not provide
14967 a required layout in the result source.
14968 @end table
14970 @node Formatting Rules
14971 @section Formatting Rules
14973 @noindent
14974 The following subsections show how @command{gnatpp} treats ``white space'',
14975 comments, program layout, and name casing.
14976 They provide the detailed descriptions of the switches shown above.
14978 @menu
14979 * White Space and Empty Lines::
14980 * Formatting Comments::
14981 * Construct Layout::
14982 * Name Casing::
14983 @end menu
14985 @node White Space and Empty Lines
14986 @subsection White Space and Empty Lines
14988 @noindent
14989 @command{gnatpp} does not have an option to control space characters.
14990 It will add or remove spaces according to the style illustrated by the
14991 examples in the @cite{Ada Reference Manual}.
14993 The only format effectors
14994 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14995 that will appear in the output file are platform-specific line breaks,
14996 and also format effectors within (but not at the end of) comments.
14997 In particular, each horizontal tab character that is not inside
14998 a comment will be treated as a space and thus will appear in the
14999 output file as zero or more spaces depending on
15000 the reformatting of the line in which it appears.
15001 The only exception is a Form Feed character, which is inserted after a
15002 pragma @code{Page} when @option{-ff} is set.
15004 The output file will contain no lines with trailing ``white space'' (spaces,
15005 format effectors).
15007 Empty lines in the original source are preserved
15008 only if they separate declarations or statements.
15009 In such contexts, a
15010 sequence of two or more empty lines is replaced by exactly one empty line.
15011 Note that a blank line will be removed if it separates two ``comment blocks''
15012 (a comment block is a sequence of whole-line comments).
15013 In order to preserve a visual separation between comment blocks, use an
15014 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15015 Likewise, if for some reason you wish to have a sequence of empty lines,
15016 use a sequence of empty comments instead.
15018 @node Formatting Comments
15019 @subsection Formatting Comments
15021 @noindent
15022 Comments in Ada code are of two kinds:
15023 @itemize @bullet
15024 @item
15025 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15026 ``white space'') on a line
15028 @item
15029 an @emph{end-of-line comment}, which follows some other Ada lexical element
15030 on the same line.
15031 @end itemize
15033 @noindent
15034 The indentation of a whole-line comment is that of either
15035 the preceding or following line in
15036 the formatted source, depending on switch settings as will be described below.
15038 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15039 between the end of the preceding Ada lexical element and the beginning
15040 of the comment as appear in the original source,
15041 unless either the comment has to be split to
15042 satisfy the line length limitation, or else the next line contains a
15043 whole line comment that is considered a continuation of this end-of-line
15044 comment (because it starts at the same position).
15045 In the latter two
15046 cases, the start of the end-of-line comment is moved right to the nearest
15047 multiple of the indentation level.
15048 This may result in a ``line overflow'' (the right-shifted comment extending
15049 beyond the maximum line length), in which case the comment is split as
15050 described below.
15052 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15053 (GNAT-style comment line indentation)
15054 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15055 (reference-manual comment line indentation).
15056 With reference-manual style, a whole-line comment is indented as if it
15057 were a declaration or statement at the same place
15058 (i.e., according to the indentation of the preceding line(s)).
15059 With GNAT style, a whole-line comment that is immediately followed by an
15060 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15061 word @b{begin}, is indented based on the construct that follows it.
15063 For example:
15064 @smallexample @c ada
15065 @cartouche
15066 if A then
15067     null;
15068        -- some comment
15069 else
15070    null;
15071 end if;
15072 @end cartouche
15073 @end smallexample
15075 @noindent
15076 Reference-manual indentation produces:
15078 @smallexample @c ada
15079 @cartouche
15080 if A then
15081    null;
15082    --  some comment
15083 else
15084    null;
15085 end if;
15086 @end cartouche
15087 @end smallexample
15089 @noindent
15090 while GNAT-style indentation produces:
15092 @smallexample @c ada
15093 @cartouche
15094 if A then
15095    null;
15096 --  some comment
15097 else
15098    null;
15099 end if;
15100 @end cartouche
15101 @end smallexample
15103 @noindent
15104 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15105 (GNAT style comment beginning) has the following
15106 effect:
15108 @itemize @bullet
15109 @item
15110 For each whole-line comment that does not end with two hyphens,
15111 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15112 to ensure that there are at least two spaces between these hyphens and the
15113 first non-blank character of the comment.
15114 @end itemize
15116 @noindent
15117 For an end-of-line comment, if in the original source the next line is a
15118 whole-line comment that starts at the same position
15119 as the end-of-line comment,
15120 then the whole-line comment (and all whole-line comments
15121 that follow it and that start at the same position)
15122 will start at this position in the output file.
15124 @noindent
15125 That is, if in the original source we have:
15127 @smallexample @c ada
15128 @cartouche
15129 begin
15130 A := B + C;            --  B must be in the range Low1..High1
15131                        --  C must be in the range Low2..High2
15132              --B+C will be in the range Low1+Low2..High1+High2
15133 X := X + 1;
15134 @end cartouche
15135 @end smallexample
15137 @noindent
15138 Then in the formatted source we get
15140 @smallexample @c ada
15141 @cartouche
15142 begin
15143    A := B + C;            --  B must be in the range Low1..High1
15144                           --  C must be in the range Low2..High2
15145    --  B+C will be in the range Low1+Low2..High1+High2
15146    X := X + 1;
15147 @end cartouche
15148 @end smallexample
15150 @noindent
15151 A comment that exceeds the line length limit will be split.
15152 Unless switch
15153 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15154 the line belongs to a reformattable block, splitting the line generates a
15155 @command{gnatpp} warning.
15156 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15157 comments may be reformatted in typical
15158 word processor style (that is, moving words between lines and putting as
15159 many words in a line as possible).
15161 @node Construct Layout
15162 @subsection Construct Layout
15164 @noindent
15165 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15166 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15167 layout on the one hand, and uncompact layout
15168 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15169 can be illustrated by the following examples:
15171 @iftex
15172 @cartouche
15173 @multitable @columnfractions .5 .5
15174 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15176 @item
15177 @smallexample @c ada
15178 type q is record
15179    a : integer;
15180    b : integer;
15181 end record;
15182 @end smallexample
15183 @tab
15184 @smallexample @c ada
15185 type q is
15186    record
15187       a : integer;
15188       b : integer;
15189    end record;
15190 @end smallexample
15192 @item
15193 @smallexample @c ada
15194 Block : declare
15195    A : Integer := 3;
15196 begin
15197    Proc (A, A);
15198 end Block;
15199 @end smallexample
15200 @tab
15201 @smallexample @c ada
15202 Block :
15203    declare
15204       A : Integer := 3;
15205    begin
15206       Proc (A, A);
15207    end Block;
15208 @end smallexample
15210 @item
15211 @smallexample @c ada
15212 Clear : for J in 1 .. 10 loop
15213    A (J) := 0;
15214 end loop Clear;
15215 @end smallexample
15216 @tab
15217 @smallexample @c ada
15218 Clear :
15219    for J in 1 .. 10 loop
15220       A (J) := 0;
15221    end loop Clear;
15222 @end smallexample
15223 @end multitable
15224 @end cartouche
15225 @end iftex
15227 @ifnottex
15228 @smallexample
15229 @cartouche
15230 GNAT style, compact layout              Uncompact layout
15232 type q is record                        type q is
15233    a : integer;                            record
15234    b : integer;                               a : integer;
15235 end record;                                   b : integer;
15236                                            end record;
15238 Block : declare                         Block :
15239    A : Integer := 3;                       declare
15240 begin                                         A : Integer := 3;
15241    Proc (A, A);                            begin
15242 end Block;                                    Proc (A, A);
15243                                            end Block;
15245 Clear : for J in 1 .. 10 loop           Clear :
15246    A (J) := 0;                             for J in 1 .. 10 loop
15247 end loop Clear;                               A (J) := 0;
15248                                            end loop Clear;
15249 @end cartouche
15250 @end smallexample
15251 @end ifnottex
15253 @noindent
15254 A further difference between GNAT style layout and compact layout is that
15255 GNAT style layout inserts empty lines as separation for
15256 compound statements, return statements and bodies.
15258 @node Name Casing
15259 @subsection Name Casing
15261 @noindent
15262 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15263 the same casing as the corresponding defining identifier.
15265 You control the casing for defining occurrences via the
15266 @option{^-n^/NAME_CASING^} switch.
15267 @ifclear vms
15268 With @option{-nD} (``as declared'', which is the default),
15269 @end ifclear
15270 @ifset vms
15271 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15272 @end ifset
15273 defining occurrences appear exactly as in the source file
15274 where they are declared.
15275 The other ^values for this switch^options for this qualifier^ ---
15276 @option{^-nU^UPPER_CASE^},
15277 @option{^-nL^LOWER_CASE^},
15278 @option{^-nM^MIXED_CASE^} ---
15279 result in
15280 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15281 If @command{gnatpp} changes the casing of a defining
15282 occurrence, it analogously changes the casing of all the
15283 usage occurrences of this name.
15285 If the defining occurrence of a name is not in the source compilation unit
15286 currently being processed by @command{gnatpp}, the casing of each reference to
15287 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15288 switch (subject to the dictionary file mechanism described below).
15289 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15290 had affected the
15291 casing for the defining occurrence of the name.
15293 Some names may need to be spelled with casing conventions that are not
15294 covered by the upper-, lower-, and mixed-case transformations.
15295 You can arrange correct casing by placing such names in a
15296 @emph{dictionary file},
15297 and then supplying a @option{^-D^/DICTIONARY^} switch.
15298 The casing of names from dictionary files overrides
15299 any @option{^-n^/NAME_CASING^} switch.
15301 To handle the casing of Ada predefined names and the names from GNAT libraries,
15302 @command{gnatpp} assumes a default dictionary file.
15303 The name of each predefined entity is spelled with the same casing as is used
15304 for the entity in the @cite{Ada Reference Manual}.
15305 The name of each entity in the GNAT libraries is spelled with the same casing
15306 as is used in the declaration of that entity.
15308 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15309 default dictionary file.
15310 Instead, the casing for predefined and GNAT-defined names will be established
15311 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15312 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15313 will appear as just shown,
15314 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15315 To ensure that even such names are rendered in uppercase,
15316 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15317 (or else, less conveniently, place these names in upper case in a dictionary
15318 file).
15320 A dictionary file is
15321 a plain text file; each line in this file can be either a blank line
15322 (containing only space characters and ASCII.HT characters), an Ada comment
15323 line, or the specification of exactly one @emph{casing schema}.
15325 A casing schema is a string that has the following syntax:
15327 @smallexample
15328 @cartouche
15329   @var{casing_schema} ::= @var{identifier} | [*]@var{simple_identifier}[*]
15331   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15332 @end cartouche
15333 @end smallexample
15335 @noindent
15336 (The @code{[]} metanotation stands for an optional part;
15337 see @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15338 @var{identifier} lexical element and the @var{letter_or_digit} category).
15340 The casing schema string can be followed by white space and/or an Ada-style
15341 comment; any amount of white space is allowed before the string.
15343 If a dictionary file is passed as
15344 @ifclear vms
15345 the value of a @option{-D@var{file}} switch
15346 @end ifclear
15347 @ifset vms
15348 an option to the @option{/DICTIONARY} qualifier
15349 @end ifset
15350 then for every
15351 simple name and every identifier, @command{gnatpp} checks if the dictionary
15352 defines the casing for the name or for some of its parts (the term ``subword''
15353 is used below to denote the part of a name which is delimited by ``_'' or by
15354 the beginning or end of the word and which does not contain any ``_'' inside):
15356 @itemize @bullet
15357 @item
15358 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15359 the casing defined by the dictionary; no subwords are checked for this word
15361 @item
15362 for the first subword (that is, for the subword preceding the leftmost
15363 ``_''), @command{gnatpp} checks if the dictionary contains the corresponding
15364 string of the form @code{@var{simple_identifier}*}, and if it does, the
15365 casing of this @var{simple_identifier} is used for this subword
15367 @item
15368 for the last subword (following the rightmost ``_'') @command{gnatpp}
15369 checks if the dictionary contains the corresponding string of the form
15370 @code{*@var{simple_identifier}}, and if it does, the casing of this
15371 @var{simple_identifier} is used for this subword
15373 @item
15374 for every intermediate subword (surrounded by two'_') @command{gnatpp} checks
15375 if the dictionary contains the corresponding string of the form
15376 @code{*@var{simple_identifier}*}, and if it does, the casing of this
15377 simple_identifier is used for this subword
15379 @item
15380 if more than one dictionary file is passed as @command{gnatpp} switches, each
15381 dictionary adds new casing exceptions and overrides all the existing casing
15382 exceptions set by the previous dictionaries
15384 @item
15385 when @command{gnatpp} checks if the word or subword is in the dictionary,
15386 this check is not case sensitive
15387 @end itemize
15389 @noindent
15390 For example, suppose we have the following source to reformat:
15392 @smallexample @c ada
15393 @cartouche
15394 procedure test is
15395    name1 : integer := 1;
15396    name4_name3_name2 : integer := 2;
15397    name2_name3_name4 : Boolean;
15398    name1_var : Float;
15399 begin
15400    name2_name3_name4 := name4_name3_name2 > name1;
15401 end;
15402 @end cartouche
15403 @end smallexample
15405 @noindent
15406 And suppose we have two dictionaries:
15408 @smallexample
15409 @cartouche
15410 @i{dict1:}
15411    NAME1
15412    *NaMe3*
15413    *NAME2
15414 @end cartouche
15416 @cartouche
15417 @i{dict2:}
15418   *NAME3*
15419 @end cartouche
15420 @end smallexample
15422 @noindent
15423 If @command{gnatpp} is called with the following switches:
15425 @smallexample
15426 @ifclear vms
15427 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15428 @end ifclear
15429 @ifset vms
15430 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15431 @end ifset
15432 @end smallexample
15434 @noindent
15435 then we will get the following name casing in the @command{gnatpp} output:
15437 @smallexample @c ada
15438 @cartouche
15439 procedure Test is
15440    NAME1             : Integer := 1;
15441    Name4_NAME3_NAME2 : integer := 2;
15442    Name2_NAME3_Name4 : Boolean;
15443    Name1_Var         : Float;
15444 begin
15445    Name2_NAME3_Name4 := Name4_NAME3_NAME2 > NAME1;
15446 end Test;
15447 @end cartouche
15448 @end smallexample
15450 @c *********************************
15451 @node The GNAT Metric Tool gnatmetric
15452 @chapter The GNAT Metric Tool @command{gnatmetric}
15453 @findex gnatmetric
15454 @cindex Metric tool
15456 @noindent
15457 ^The @command{gnatmetric} tool^GNAT METRIC^ is an ASIS-based utility
15458 for computing various program metrics.
15459 It takes an Ada source file as input and generates a file containing the
15460 metrics data as output. Various switches control which
15461 metrics are computed and output.
15463 @command{gnatmetric} generates and uses the ASIS
15464 tree for the input source and thus requires the input to be syntactically and
15465 semantically legal.
15466 If this condition is not met, @command{gnatmetric} will generate
15467 an error message; no metric information for this file will be
15468 computed and reported.
15470 If the compilation unit contained in the input source depends semantically
15471 upon units located outside the current directory, you have to provide the
15472 source search path when invoking @command{gnatmetric}.
15473 If these units are contained in files
15474 with names that do not follow the GNAT file naming rules, you have to provide
15475 the configuration file describing the corresponding naming scheme; see the
15476 description of the @command{gnatmetric} switches below. Another possibility
15477 is to use a project file and to
15478 call @command{gnatmetric} through the @command{gnat} driver
15480 The @command{gnatmetric} command has the form
15482 @smallexample
15483 $ gnatmetric [@var{switches}] @var{filename} [@var{-cargs gcc_switches}]
15484 @end smallexample
15486 @noindent
15487 where
15488 @itemize @bullet
15489 @item
15490 @var{switches} specify the metrics to compute and define the destination for
15491 the output
15493 @item
15494 @var{filename} is the name (including the extension) of the source file to
15495 process; ``wildcards'' or several file names on the same @command{gnatmetric}
15496 command are allowed.  The file name may contain path information; in this case
15497 it does not have to follow the GNAT file naming rules
15499 @item
15500 @option{-cargs gcc_switches} is a list of switches for
15501 @command{gcc}. They will be passed on to all compiler invocations made by
15502 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15503 @option{-I} switches to form the source search path,
15504 and use the @var{-gnatec} switch to set the configuration file.
15505 @end itemize
15507 @menu
15508 * Switches for gnatmetric::
15509 @end menu
15511 @node Switches for gnatmetric
15512 @section Switches for @command{gnatmetric}
15514 @noindent
15515 The following subsections describe the various switches accepted by
15516 @command{gnatmetric}, organized by category.
15518 @menu
15519 * Output Files Control::
15520 * Disable Metrics For Local Units::
15521 * Line Metrics Control::
15522 * Syntax Metrics Control::
15523 * Complexity Metrics Control::
15524 * Other gnatmetric Switches::
15525 @end menu
15527 @node Output Files Control
15528 @subsection Output File Control
15529 @cindex Output file control in @command{gnatmetric}
15531 @noindent
15532 @command{gnatmetric} has two output formats. It can generate a
15533 textual (human-readable) form, and also XML. By default only textual
15534 output is generated.
15536 When generating the output in textual form, @command{gnatmetric} creates
15537 for each Ada source file a corresponding text file
15538 containing the computed metrics. By default, this file
15539 is placed in the same directory as where the source file is located, and
15540 its name is obtained
15541 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15542 input file.
15544 All the output information generated in XML format is placed in a single
15545 file. By default this file is placed in the current directory and has the
15546 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15548 Some of the computed metrics are summed over the units passed to
15549 @command{gnatmetric}; for example, the total number of lines of code.
15550 By default this information is sent to @file{stdout}, but a file
15551 can be specified with the @option{-og} switch.
15553 The following switches control the @command{gnatmetric} output:
15555 @table @option
15556 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15557 @item ^-x^/XML^
15558 Generate the XML output
15560 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15561 @item ^-nt^/NO_TEXT^
15562 Do not generate the output in text form (implies @option{^-x^/XML^})
15564 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15565 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15566 Put textual files with detailed metrics into @var{output_dir}
15568 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15569 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15570 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15571 in the name of the output file.
15573 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15574 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15575 Put global metrics into @var{file_name}
15577 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15578 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15579 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15581 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15582 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15583 Use short source file names in the output
15585 @end table
15587 @node Disable Metrics For Local Units
15588 @subsection Disable Metrics For Local Units
15589 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15591 @noindent
15592 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15593 one compilation
15594 unit per one source file. It computes some metrics for the whole source
15595 file (mostly ``number of lines'' metrics) and it always computes metrics for
15596 the top program unit of the corresponding compilation unit.
15598 @command{gnatmetric} considers the following constructs as program units to
15599 compute metrics for:
15601 @itemize @bullet
15602 @item
15603 a library item or a subunit in a compilation unit;
15605 @item
15606 all kinds of bodies;
15608 @item
15609 declarations of tasks and protected types and objects, package and generic
15610 package declarations;
15612 @end itemize
15614 @noindent
15615 That is, a subprogram declaration, a generic instantiation or a renaming is
15616 considered as a program unit only if it is a library item of a compilation
15617 unit.
15619 @table @option
15620 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15621 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15622 Do not compute detailed metrics for local program units
15624 @end table
15626 @node Line Metrics Control
15627 @subsection Line Metrics Control
15628 @cindex Line metrics control in @command{gnatmetric}
15630 @noindent
15631 For any source file containing a legal compilation unit, and for any program
15632 unit, @command{gnatmetric} computes the following metrics:
15634 @itemize @bullet
15635 @item
15636 the total number of lines in the file;
15638 @item
15639 the total number of code lines (i.e., non-blank lines that are not comments)
15641 @item
15642 the number of comment lines
15644 @item
15645 the number of code lines containing end-of-line comments;
15647 @item
15648 the number of empty lines and lines containing only space characters and/or
15649 format effectors (blank lines)
15651 @end itemize
15653 If @command{gnatmetric} is invoked on more than one source file, it sums the
15654 values of the line metrics for all the files being processed and then
15655 generates the cumulative results.
15657 By default, all the line metrics are computed and reported. You can use the
15658 following switches to select the specific line metrics to be computed and
15659 reported (if any of these parameters is set, only explicitly specified line
15660 metrics are computed).
15662 @table @option
15663 @cindex @option{^-la^/LINES_ALL^} (@command{gnatmetric})
15664 @item ^-la^/LINES_ALL^
15665 The number of all lines
15667 @cindex @option{^-lcode^/CODE_LINES^} (@command{gnatmetric})
15668 @item ^-lcode^/CODE_LINES^
15669 The number of code lines
15671 @cindex @option{^-lcomm^/COMENT_LINES^} (@command{gnatmetric})
15672 @item ^-lcomm^/COMENT_LINES^
15673 The number of comment lines
15675 @cindex @option{^-leol^/MIXED_CODE_COMMENTS^} (@command{gnatmetric})
15676 @item ^-leol^/MIXED_CODE_COMMENTS^
15677 The number of code lines containing
15678 end-of-line comments
15680 @cindex @option{^-lb^/BLANK_LINES^} (@command{gnatmetric})
15681 @item ^-lb^/BLANK_LINES^
15682 The number of blank lines
15684 @end table
15686 @node Syntax Metrics Control
15687 @subsection Syntax Metrics Control
15688 @cindex Syntax metrics control in @command{gnatmetric}
15690 @noindent
15691 For any program unit, @command{gnatmetric} computes the total number of
15692 declarations and the total number of statements.  The sum of all the statements
15693 and all the declarations is considered as @emph{LSLOC} (``Logical Source
15694 Lines Of Code'')
15695 and is reported as a separate metric.
15697 For any body and any task, protected, package and generic package declaration
15698 the maximal static nesting level of nested program units is computed.
15699 According to
15700 @cite{Ada 95 Language Reference Manual}, 10.1(1), ``A program unit is either a
15701 package, a task unit, a protected unit, a
15702 protected entry, a generic unit, or an explicitly declared subprogram other
15703 than an enumeration literal.''
15705 For any program unit @command{gnatmetric} computes the maximal nesting level of
15706 composite syntactic constructs.  This corresponds to the notion of the
15707 maximum nesting level in the GNAT built-in style checks
15708 (see @ref{Style Checking})
15710 For any library-level program unit @command{gnatmetric} additionally computes
15711 the following metrics:
15713 @table @emph
15714 @item Public subprograms
15715 This metric is computed for non-private compilation units only. It is a number
15716 of the subprograms and generic subprograms declared in the given compilation
15717 unit that can be called
15718 or instantiated outside the unit. Formal generic subprograms and generic
15719 instantiations are not counted. Protected subprograms are counted in the same
15720 way as non-protected ones.
15722 @item All subprograms
15723 This metric is computed for all the library level bodies and subunits. The
15724 metric is equal to a total number of subprogram bodies in the compilation unit.
15725 Neither generic instantiations nor renamings-as-a-body nor body stubs
15726 are counted. Any subprogram body is counted, independently of its nesting
15727 level and enclosing constructs. Generic bodies and bodies of protected
15728 subprograms are counted in the same way as ``usual'' subprogram bodies.
15730 @item Public types
15731 This metric is computed only for non-private package declarations and
15732 generic package declarations. It is the total number of types
15733 that can be referenced from outside this compilation unit, plus the
15734 number of types from all the visible parts of all the visible generic packages.
15735 Generic formal types are not counted.
15737 @noindent
15738 Along with counting the total number of public types, the following
15739 types are counted and reported separately:
15741 @itemize @bullet
15742 @item
15743 Abstract types
15745 @item
15746 Root tagged types (abstract, non-abstract, private, non-private). Type
15747 extensions are @emph{not} counted
15749 @item
15750 Private types (including private extensions)
15752 @item
15753 Task types
15755 @item
15756 Protected types
15758 @end itemize
15760 @item All types
15761 This metric is computed for any compilation unit. It is equal to the total
15762 number of the declarations of different types given in the compilation unit.
15763 The private and the corresponding full type declaration are counted as one
15764 type declaration. Incomplete type declarations and generic formal types
15765 are not counted.
15766 No distinction is made among different kinds of types (abstract,
15767 private etc.); the total number of types is computed and reported.
15769 @end table
15771 @noindent
15772 By default, all the syntax metrics are computed and reported. You can use the
15773 following switches to select specific syntax metrics;
15774 if any of these is set, only the explicitly specified metrics are computed.
15776 @table @option
15777 @cindex @option{^-ed^/DECLARATION_TOTAL^} (@command{gnatmetric})
15778 @item ^-ed^/DECLARATION_TOTAL^
15779 The total number of declarations
15781 @cindex @option{^-es^/STATEMENT_TOTAL^} (@command{gnatmetric})
15782 @item ^-es^/STATEMENT_TOTAL^
15783 The total number of statements
15785 @cindex @option{^-eps^/^} (@command{gnatmetric})
15786 @item ^-eps^/INT_SUBPROGRAMS^
15787 The number of public subprograms in a compilation unit
15789 @cindex @option{^-eas^/SUBPROGRAMS_ALL^} (@command{gnatmetric})
15790 @item ^-eas^/SUBPROGRAMS_ALL^
15791 The number of all the subprograms in a compilation unit
15793 @cindex @option{^-ept^/INT_TYPES^} (@command{gnatmetric})
15794 @item ^-ept^/INT_TYPES^
15795 The number of public types in a compilation unit
15797 @cindex @option{^-eat^/TYPES_ALL^} (@command{gnatmetric})
15798 @item ^-eat^/TYPES_ALL^
15799 The number of all the types in a compilation unit
15801 @cindex @option{^-enu^/PROGRAM_NESTING_MAX^} (@command{gnatmetric})
15802 @item ^-enu^/PROGRAM_NESTING_MAX^
15803 The maximal program unit nesting level
15805 @cindex @option{^-ec^/CONSTRUCT_NESTING_MAX^} (@command{gnatmetric})
15806 @item ^-ec^/CONSTRUCT_NESTING_MAX^
15807 The maximal construct nesting level
15809 @end table
15811 @node Complexity Metrics Control
15812 @subsection Complexity Metrics Control
15813 @cindex Complexity metrics control in @command{gnatmetric}
15815 @noindent
15816 For a program unit that is an executable body (a subprogram body (including
15817 generic bodies), task body, entry body or a package body containing
15818 its own statement sequence ) @command{gnatmetric} computes the following
15819 complexity metrics:
15821 @itemize @bullet
15822 @item
15823 McCabe cyclomatic complexity;
15825 @item
15826 McCabe essential complexity;
15828 @item
15829 maximal loop nesting level
15831 @end itemize
15833 @noindent
15834 The McCabe complexity metrics are defined
15835 in @url{www.mccabe.com/pdf/nist235r.pdf}
15837 According to McCabe, both control statements and short-circuit control forms
15838 should be taken into account when computing cyclomatic complexity. For each
15839 body, we compute three metric values:
15841 @itemize @bullet
15842 @item
15843 the complexity introduced by control
15844 statements only, without taking into account short-circuit forms,
15846 @item
15847 the complexity introduced by short-circuit control forms only, and
15849 @item
15850 the total
15851 cyclomatic complexity, which is the sum of these two values.
15852 @end itemize
15854 @noindent
15855 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15856 the code in the exception handlers and in all the nested program units.
15858 By default, all the complexity metrics are computed and reported.
15859 For more finely-grained control you can use
15860 the following switches:
15862 @table @option
15863 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15865 @item ^-nocc^/SUPPRESS=CYCLOMATIC_COMPLEXITY^
15866 Do not compute the McCabe Cyclomatic Complexity
15868 @item ^noec-^/SUPPRESS=ESSENTIAL_COMPLEXITY^
15869 Do not compute the Essential Complexity
15871 @item ^-nonl^/SUPPRESS=MAXIMAL_LOOP_NESTING^
15872 Do not compute maximal loop nesting level
15874 @item ^-ne^/SUPPRESS=EXITS_AS_GOTOS^
15875 Do not consider @code{exit} statements as @code{goto}s when
15876 computing Essential Complexity
15878 @end table
15880 @node Other gnatmetric Switches
15881 @subsection Other @code{gnatmetric} Switches
15883 @noindent
15884 Additional @command{gnatmetric} switches are as follows:
15886 @table @option
15887 @item ^-files @var{filename}^/FILES=@var{filename}^
15888 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15889 Take the argument source files from the specified file. This file should be an
15890 ordinary textual file containing file names separated by spaces or
15891 line breaks. You can use this switch more then once in the same call to
15892 @command{gnatmetric}. You also can combine this switch with
15893 an explicit list of files.
15895 @item ^-v^/VERBOSE^
15896 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
15897 Verbose mode;
15898 @command{gnatmetric} generates version information and then
15899 a trace of sources being procesed.
15901 @item ^-dv^/DEBUG_OUTPUT^
15902 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
15903 Debug mode;
15904 @command{gnatmetric} generates various messages useful to understand what
15905 happens during the metrics computation
15907 @item ^-q^/QUIET^
15908 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
15909 Quiet mode.
15910 @end table
15912 @c ***********************************
15913 @node File Name Krunching Using gnatkr
15914 @chapter File Name Krunching Using @code{gnatkr}
15915 @findex gnatkr
15917 @noindent
15918 This chapter discusses the method used by the compiler to shorten
15919 the default file names chosen for Ada units so that they do not
15920 exceed the maximum length permitted. It also describes the
15921 @code{gnatkr} utility that can be used to determine the result of
15922 applying this shortening.
15923 @menu
15924 * About gnatkr::
15925 * Using gnatkr::
15926 * Krunching Method::
15927 * Examples of gnatkr Usage::
15928 @end menu
15930 @node About gnatkr
15931 @section About @code{gnatkr}
15933 @noindent
15934 The default file naming rule in GNAT
15935 is that the file name must be derived from
15936 the unit name. The exact default rule is as follows:
15937 @itemize @bullet
15938 @item
15939 Take the unit name and replace all dots by hyphens.
15940 @item
15941 If such a replacement occurs in the
15942 second character position of a name, and the first character is
15943 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
15944 ^~ (tilde)^$ (dollar sign)^
15945 instead of a minus.
15946 @end itemize
15947 The reason for this exception is to avoid clashes
15948 with the standard names for children of System, Ada, Interfaces,
15949 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
15950 respectively.
15952 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
15953 switch of the compiler activates a ``krunching''
15954 circuit that limits file names to nn characters (where nn is a decimal
15955 integer). For example, using OpenVMS,
15956 where the maximum file name length is
15957 39, the value of nn is usually set to 39, but if you want to generate
15958 a set of files that would be usable if ported to a system with some
15959 different maximum file length, then a different value can be specified.
15960 The default value of 39 for OpenVMS need not be specified.
15962 The @code{gnatkr} utility can be used to determine the krunched name for
15963 a given file, when krunched to a specified maximum length.
15965 @node Using gnatkr
15966 @section Using @code{gnatkr}
15968 @noindent
15969 The @code{gnatkr} command has the form
15971 @ifclear vms
15972 @smallexample
15973 $ gnatkr @var{name} [@var{length}]
15974 @end smallexample
15975 @end ifclear
15977 @ifset vms
15978 @smallexample
15979 $ gnatkr @var{name} /COUNT=nn
15980 @end smallexample
15981 @end ifset
15983 @noindent
15984 @var{name} is the uncrunched file name, derived from the name of the unit
15985 in the standard manner described in the previous section (i.e. in particular
15986 all dots are replaced by hyphens). The file name may or may not have an
15987 extension (defined as a suffix of the form period followed by arbitrary
15988 characters other than period). If an extension is present then it will
15989 be preserved in the output. For example, when krunching @file{hellofile.ads}
15990 to eight characters, the result will be hellofil.ads.
15992 Note: for compatibility with previous versions of @code{gnatkr} dots may
15993 appear in the name instead of hyphens, but the last dot will always be
15994 taken as the start of an extension. So if @code{gnatkr} is given an argument
15995 such as @file{Hello.World.adb} it will be treated exactly as if the first
15996 period had been a hyphen, and for example krunching to eight characters
15997 gives the result @file{hellworl.adb}.
15999 Note that the result is always all lower case (except on OpenVMS where it is
16000 all upper case). Characters of the other case are folded as required.
16002 @var{length} represents the length of the krunched name. The default
16003 when no argument is given is ^8^39^ characters. A length of zero stands for
16004 unlimited, in other words do not chop except for system files where the
16005 impled crunching length is always eight characters.
16007 @noindent
16008 The output is the krunched name. The output has an extension only if the
16009 original argument was a file name with an extension.
16011 @node Krunching Method
16012 @section Krunching Method
16014 @noindent
16015 The initial file name is determined by the name of the unit that the file
16016 contains. The name is formed by taking the full expanded name of the
16017 unit and replacing the separating dots with hyphens and
16018 using ^lowercase^uppercase^
16019 for all letters, except that a hyphen in the second character position is
16020 replaced by a ^tilde^dollar sign^ if the first character is
16021 ^a, i, g, or s^A, I, G, or S^.
16022 The extension is @code{.ads} for a
16023 specification and @code{.adb} for a body.
16024 Krunching does not affect the extension, but the file name is shortened to
16025 the specified length by following these rules:
16027 @itemize @bullet
16028 @item
16029 The name is divided into segments separated by hyphens, tildes or
16030 underscores and all hyphens, tildes, and underscores are
16031 eliminated. If this leaves the name short enough, we are done.
16033 @item
16034 If the name is too long, the longest segment is located (left-most
16035 if there are two of equal length), and shortened by dropping
16036 its last character. This is repeated until the name is short enough.
16038 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16039 to fit the name into 8 characters as required by some operating systems.
16041 @smallexample
16042 our-strings-wide_fixed 22
16043 our strings wide fixed 19
16044 our string  wide fixed 18
16045 our strin   wide fixed 17
16046 our stri    wide fixed 16
16047 our stri    wide fixe  15
16048 our str     wide fixe  14
16049 our str     wid  fixe  13
16050 our str     wid  fix   12
16051 ou  str     wid  fix   11
16052 ou  st      wid  fix   10
16053 ou  st      wi   fix   9
16054 ou  st      wi   fi    8
16055 Final file name: oustwifi.adb
16056 @end smallexample
16058 @item
16059 The file names for all predefined units are always krunched to eight
16060 characters. The krunching of these predefined units uses the following
16061 special prefix replacements:
16063 @table @file
16064 @item ada-
16065 replaced by @file{^a^A^-}
16067 @item gnat-
16068 replaced by @file{^g^G^-}
16070 @item interfaces-
16071 replaced by @file{^i^I^-}
16073 @item system-
16074 replaced by @file{^s^S^-}
16075 @end table
16077 These system files have a hyphen in the second character position. That
16078 is why normal user files replace such a character with a
16079 ^tilde^dollar sign^, to
16080 avoid confusion with system file names.
16082 As an example of this special rule, consider
16083 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16085 @smallexample
16086 ada-strings-wide_fixed 22
16087 a-  strings wide fixed 18
16088 a-  string  wide fixed 17
16089 a-  strin   wide fixed 16
16090 a-  stri    wide fixed 15
16091 a-  stri    wide fixe  14
16092 a-  str     wide fixe  13
16093 a-  str     wid  fixe  12
16094 a-  str     wid  fix   11
16095 a-  st      wid  fix   10
16096 a-  st      wi   fix   9
16097 a-  st      wi   fi    8
16098 Final file name: a-stwifi.adb
16099 @end smallexample
16100 @end itemize
16102 Of course no file shortening algorithm can guarantee uniqueness over all
16103 possible unit names, and if file name krunching is used then it is your
16104 responsibility to ensure that no name clashes occur. The utility
16105 program @code{gnatkr} is supplied for conveniently determining the
16106 krunched name of a file.
16108 @node Examples of gnatkr Usage
16109 @section Examples of @code{gnatkr} Usage
16111 @smallexample
16112 @iftex
16113 @leftskip=0cm
16114 @end iftex
16115 @ifclear vms
16116 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16117 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16118 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16119 $ gnatkr grandparent-parent-child     --> grparchi
16120 @end ifclear
16121 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16122 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16123 @end smallexample
16125 @node Preprocessing Using gnatprep
16126 @chapter Preprocessing Using @code{gnatprep}
16127 @findex gnatprep
16129 @noindent
16130 The @code{gnatprep} utility provides
16131 a simple preprocessing capability for Ada programs.
16132 It is designed for use with GNAT, but is not dependent on any special
16133 features of GNAT.
16135 @menu
16136 * Using gnatprep::
16137 * Switches for gnatprep::
16138 * Form of Definitions File::
16139 * Form of Input Text for gnatprep::
16140 @end menu
16142 @node Using gnatprep
16143 @section Using @code{gnatprep}
16145 @noindent
16146 To call @code{gnatprep} use
16148 @smallexample
16149 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
16150 @end smallexample
16152 @noindent
16153 where
16154 @table @code
16155 @item infile
16156 is the full name of the input file, which is an Ada source
16157 file containing preprocessor directives.
16159 @item outfile
16160 is the full name of the output file, which is an Ada source
16161 in standard Ada form. When used with GNAT, this file name will
16162 normally have an ads or adb suffix.
16164 @item deffile
16165 is the full name of a text file containing definitions of
16166 symbols to be referenced by the preprocessor. This argument is
16167 optional, and can be replaced by the use of the @option{-D} switch.
16169 @item switches
16170 is an optional sequence of switches as described in the next section.
16171 @end table
16173 @node Switches for gnatprep
16174 @section Switches for @code{gnatprep}
16176 @table @option
16177 @c !sort!
16179 @item ^-b^/BLANK_LINES^
16180 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16181 Causes both preprocessor lines and the lines deleted by
16182 preprocessing to be replaced by blank lines in the output source file,
16183 preserving line numbers in the output file.
16185 @item ^-c^/COMMENTS^
16186 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16187 Causes both preprocessor lines and the lines deleted
16188 by preprocessing to be retained in the output source as comments marked
16189 with the special string @code{"--! "}. This option will result in line numbers
16190 being preserved in the output file.
16192 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16193 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16194 Defines a new symbol, associated with value. If no value is given on the
16195 command line, then symbol is considered to be @code{True}. This switch
16196 can be used in place of a definition file.
16198 @ifset vms
16199 @item /REMOVE
16200 @cindex @option{/REMOVE} (@command{gnatprep})
16201 This is the default setting which causes lines deleted by preprocessing
16202 to be entirely removed from the output file.
16203 @end ifset
16205 @item ^-r^/REFERENCE^
16206 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16207 Causes a @code{Source_Reference} pragma to be generated that
16208 references the original input file, so that error messages will use
16209 the file name of this original file. The use of this switch implies
16210 that preprocessor lines are not to be removed from the file, so its
16211 use will force @option{^-b^/BLANK_LINES^} mode if
16212 @option{^-c^/COMMENTS^}
16213 has not been specified explicitly.
16215 Note that if the file to be preprocessed contains multiple units, then
16216 it will be necessary to @code{gnatchop} the output file from
16217 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16218 in the preprocessed file, it will be respected by
16219 @code{gnatchop ^-r^/REFERENCE^}
16220 so that the final chopped files will correctly refer to the original
16221 input source file for @code{gnatprep}.
16223 @item ^-s^/SYMBOLS^
16224 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16225 Causes a sorted list of symbol names and values to be
16226 listed on the standard output file.
16228 @item ^-u^/UNDEFINED^
16229 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16230 Causes undefined symbols to be treated as having the value FALSE in the context
16231 of a preprocessor test. In the absence of this option, an undefined symbol in
16232 a @code{#if} or @code{#elsif} test will be treated as an error.
16234 @end table
16236 @ifclear vms
16237 @noindent
16238 Note: if neither @option{-b} nor @option{-c} is present,
16239 then preprocessor lines and
16240 deleted lines are completely removed from the output, unless -r is
16241 specified, in which case -b is assumed.
16242 @end ifclear
16244 @node Form of Definitions File
16245 @section Form of Definitions File
16247 @noindent
16248 The definitions file contains lines of the form
16250 @smallexample
16251 symbol := value
16252 @end smallexample
16254 @noindent
16255 where symbol is an identifier, following normal Ada (case-insensitive)
16256 rules for its syntax, and value is one of the following:
16258 @itemize @bullet
16259 @item
16260 Empty, corresponding to a null substitution
16261 @item
16262 A string literal using normal Ada syntax
16263 @item
16264 Any sequence of characters from the set
16265 (letters, digits, period, underline).
16266 @end itemize
16268 @noindent
16269 Comment lines may also appear in the definitions file, starting with
16270 the usual @code{--},
16271 and comments may be added to the definitions lines.
16273 @node Form of Input Text for gnatprep
16274 @section Form of Input Text for @code{gnatprep}
16276 @noindent
16277 The input text may contain preprocessor conditional inclusion lines,
16278 as well as general symbol substitution sequences.
16280 The preprocessor conditional inclusion commands have the form
16282 @smallexample
16283 @group
16284 @cartouche
16285 #if @i{expression} [then]
16286    lines
16287 #elsif @i{expression} [then]
16288    lines
16289 #elsif @i{expression} [then]
16290    lines
16292 #else
16293    lines
16294 #end if;
16295 @end cartouche
16296 @end group
16297 @end smallexample
16299 @noindent
16300 In this example, @i{expression} is defined by the following grammar:
16301 @smallexample
16302 @i{expression} ::=  <symbol>
16303 @i{expression} ::=  <symbol> = "<value>"
16304 @i{expression} ::=  <symbol> = <symbol>
16305 @i{expression} ::=  <symbol> 'Defined
16306 @i{expression} ::=  not @i{expression}
16307 @i{expression} ::=  @i{expression} and @i{expression}
16308 @i{expression} ::=  @i{expression} or @i{expression}
16309 @i{expression} ::=  @i{expression} and then @i{expression}
16310 @i{expression} ::=  @i{expression} or else @i{expression}
16311 @i{expression} ::=  ( @i{expression} )
16312 @end smallexample
16314 @noindent
16315 For the first test (@i{expression} ::= <symbol>) the symbol must have
16316 either the value true or false, that is to say the right-hand of the
16317 symbol definition must be one of the (case-insensitive) literals
16318 @code{True} or @code{False}. If the value is true, then the
16319 corresponding lines are included, and if the value is false, they are
16320 excluded.
16322 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16323 the symbol has been defined in the definition file or by a @option{-D}
16324 switch on the command line. Otherwise, the test is false.
16326 The equality tests are case insensitive, as are all the preprocessor lines.
16328 If the symbol referenced is not defined in the symbol definitions file,
16329 then the effect depends on whether or not switch @option{-u}
16330 is specified. If so, then the symbol is treated as if it had the value
16331 false and the test fails. If this switch is not specified, then
16332 it is an error to reference an undefined symbol. It is also an error to
16333 reference a symbol that is defined with a value other than @code{True}
16334 or @code{False}.
16336 The use of the @code{not} operator inverts the sense of this logical test, so
16337 that the lines are included only if the symbol is not defined.
16338 The @code{then} keyword is optional as shown
16340 The @code{#} must be the first non-blank character on a line, but
16341 otherwise the format is free form. Spaces or tabs may appear between
16342 the @code{#} and the keyword. The keywords and the symbols are case
16343 insensitive as in normal Ada code. Comments may be used on a
16344 preprocessor line, but other than that, no other tokens may appear on a
16345 preprocessor line. Any number of @code{elsif} clauses can be present,
16346 including none at all. The @code{else} is optional, as in Ada.
16348 The @code{#} marking the start of a preprocessor line must be the first
16349 non-blank character on the line, i.e. it must be preceded only by
16350 spaces or horizontal tabs.
16352 Symbol substitution outside of preprocessor lines is obtained by using
16353 the sequence
16355 @smallexample
16356 $symbol
16357 @end smallexample
16359 @noindent
16360 anywhere within a source line, except in a comment or within a
16361 string literal. The identifier
16362 following the @code{$} must match one of the symbols defined in the symbol
16363 definition file, and the result is to substitute the value of the
16364 symbol in place of @code{$symbol} in the output file.
16366 Note that although the substitution of strings within a string literal
16367 is not possible, it is possible to have a symbol whose defined value is
16368 a string literal. So instead of setting XYZ to @code{hello} and writing:
16370 @smallexample
16371 Header : String := "$XYZ";
16372 @end smallexample
16374 @noindent
16375 you should set XYZ to @code{"hello"} and write:
16377 @smallexample
16378 Header : String := $XYZ;
16379 @end smallexample
16381 @noindent
16382 and then the substitution will occur as desired.
16384 @ifset vms
16385 @node The GNAT Run-Time Library Builder gnatlbr
16386 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
16387 @findex gnatlbr
16388 @cindex Library builder
16390 @noindent
16391 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
16392 supplied configuration pragmas.
16394 @menu
16395 * Running gnatlbr::
16396 * Switches for gnatlbr::
16397 * Examples of gnatlbr Usage::
16398 @end menu
16400 @node Running gnatlbr
16401 @section Running @code{gnatlbr}
16403 @noindent
16404 The @code{gnatlbr} command has the form
16406 @smallexample
16407 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
16408 @end smallexample
16410 @node Switches for gnatlbr
16411 @section Switches for @code{gnatlbr}
16413 @noindent
16414 @code{gnatlbr} recognizes the following switches:
16416 @table @option
16417 @c !sort!
16418 @item /CREATE=directory
16419 @cindex @code{/CREATE} (@code{gnatlbr})
16420      Create the new run-time library in the specified directory.
16422 @item /SET=directory
16423 @cindex @code{/SET} (@code{gnatlbr})
16424      Make the library in the specified directory the current run-time
16425      library.
16427 @item /DELETE=directory
16428 @cindex @code{/DELETE} (@code{gnatlbr})
16429      Delete the run-time library in the specified directory.
16431 @item /CONFIG=file
16432 @cindex @code{/CONFIG} (@code{gnatlbr})
16433      With /CREATE:
16434      Use the configuration pragmas in the specified file when building
16435      the library.
16437      With /SET:
16438      Use the configuration pragmas in the specified file when compiling.
16440 @end table
16442 @node Examples of gnatlbr Usage
16443 @section Example of @code{gnatlbr} Usage
16445 @smallexample
16446 Contents of VAXFLOAT.ADC:
16447 pragma Float_Representation (VAX_Float);
16449 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
16451 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
16453 @end smallexample
16454 @end ifset
16456 @node The GNAT Library Browser gnatls
16457 @chapter The GNAT Library Browser @code{gnatls}
16458 @findex gnatls
16459 @cindex Library browser
16461 @noindent
16462 @code{gnatls} is a tool that outputs information about compiled
16463 units. It gives the relationship between objects, unit names and source
16464 files. It can also be used to check the source dependencies of a unit
16465 as well as various characteristics.
16467 @menu
16468 * Running gnatls::
16469 * Switches for gnatls::
16470 * Examples of gnatls Usage::
16471 @end menu
16473 @node Running gnatls
16474 @section Running @code{gnatls}
16476 @noindent
16477 The @code{gnatls} command has the form
16479 @smallexample
16480 $ gnatls switches @var{object_or_ali_file}
16481 @end smallexample
16483 @noindent
16484 The main argument is the list of object or @file{ali} files
16485 (@pxref{The Ada Library Information Files})
16486 for which information is requested.
16488 In normal mode, without additional option, @code{gnatls} produces a
16489 four-column listing. Each line represents information for a specific
16490 object. The first column gives the full path of the object, the second
16491 column gives the name of the principal unit in this object, the third
16492 column gives the status of the source and the fourth column gives the
16493 full path of the source representing this unit.
16494 Here is a simple example of use:
16496 @smallexample
16497 $ gnatls *.o
16498 ^./^[]^demo1.o            demo1            DIF demo1.adb
16499 ^./^[]^demo2.o            demo2             OK demo2.adb
16500 ^./^[]^hello.o            h1                OK hello.adb
16501 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
16502 ^./^[]^instr.o            instr             OK instr.adb
16503 ^./^[]^tef.o              tef              DIF tef.adb
16504 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
16505 ^./^[]^tgef.o             tgef             DIF tgef.adb
16506 @end smallexample
16508 @noindent
16509 The first line can be interpreted as follows: the main unit which is
16510 contained in
16511 object file @file{demo1.o} is demo1, whose main source is in
16512 @file{demo1.adb}. Furthermore, the version of the source used for the
16513 compilation of demo1 has been modified (DIF). Each source file has a status
16514 qualifier which can be:
16516 @table @code
16517 @item OK (unchanged)
16518 The version of the source file used for the compilation of the
16519 specified unit corresponds exactly to the actual source file.
16521 @item MOK (slightly modified)
16522 The version of the source file used for the compilation of the
16523 specified unit differs from the actual source file but not enough to
16524 require recompilation. If you use gnatmake with the qualifier
16525 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16526 MOK will not be recompiled.
16528 @item DIF (modified)
16529 No version of the source found on the path corresponds to the source
16530 used to build this object.
16532 @item ??? (file not found)
16533 No source file was found for this unit.
16535 @item HID (hidden,  unchanged version not first on PATH)
16536 The version of the source that corresponds exactly to the source used
16537 for compilation has been found on the path but it is hidden by another
16538 version of the same source that has been modified.
16540 @end table
16542 @node Switches for gnatls
16543 @section Switches for @code{gnatls}
16545 @noindent
16546 @code{gnatls} recognizes the following switches:
16548 @table @option
16549 @c !sort!
16550 @item ^-a^/ALL_UNITS^
16551 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16552 Consider all units, including those of the predefined Ada library.
16553 Especially useful with @option{^-d^/DEPENDENCIES^}.
16555 @item ^-d^/DEPENDENCIES^
16556 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16557 List sources from which specified units depend on.
16559 @item ^-h^/OUTPUT=OPTIONS^
16560 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16561 Output the list of options.
16563 @item ^-o^/OUTPUT=OBJECTS^
16564 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16565 Only output information about object files.
16567 @item ^-s^/OUTPUT=SOURCES^
16568 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16569 Only output information about source files.
16571 @item ^-u^/OUTPUT=UNITS^
16572 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16573 Only output information about compilation units.
16575 @item ^-files^/FILES^=@var{file}
16576 @cindex @option{^-files^/FILES^} (@code{gnatls})
16577 Take as arguments the files listed in text file @var{file}.
16578 Text file @var{file} may contain empty lines that are ignored.
16579 Each non empty line should contain the name of an existing file.
16580 Several such switches may be specified simultaneously.
16582 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16583 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16584 @itemx ^-I^/SEARCH=^@var{dir}
16585 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
16586 @itemx -nostdinc
16587 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16588 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16589 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16590 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16591 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
16592 (see @ref{Switches for gnatmake}).
16594 @item --RTS=@var{rts-path}
16595 @cindex @option{--RTS} (@code{gnatls})
16596 Specifies the default location of the runtime library. Same meaning as the
16597 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
16599 @item ^-v^/OUTPUT=VERBOSE^
16600 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16601 Verbose mode. Output the complete source, object and project paths. Do not use
16602 the default column layout but instead use long format giving as much as
16603 information possible on each requested units, including special
16604 characteristics such as:
16606 @table @code
16607 @item  Preelaborable
16608 The unit is preelaborable in the Ada 95 sense.
16610 @item No_Elab_Code
16611 No elaboration code has been produced by the compiler for this unit.
16613 @item Pure
16614 The unit is pure in the Ada 95 sense.
16616 @item Elaborate_Body
16617 The unit contains a pragma Elaborate_Body.
16619 @item Remote_Types
16620 The unit contains a pragma Remote_Types.
16622 @item Shared_Passive
16623 The unit contains a pragma Shared_Passive.
16625 @item Predefined
16626 This unit is part of the predefined environment and cannot be modified
16627 by the user.
16629 @item Remote_Call_Interface
16630 The unit contains a pragma Remote_Call_Interface.
16632 @end table
16634 @end table
16636 @node Examples of gnatls Usage
16637 @section Example of @code{gnatls} Usage
16638 @ifclear vms
16640 @noindent
16641 Example of using the verbose switch. Note how the source and
16642 object paths are affected by the -I switch.
16644 @smallexample
16645 $ gnatls -v -I.. demo1.o
16647 GNATLS 5.03w (20041123-34)
16648 Copyright 1997-2004 Free Software Foundation, Inc.
16650 Source Search Path:
16651    <Current_Directory>
16652    ../
16653    /home/comar/local/adainclude/
16655 Object Search Path:
16656    <Current_Directory>
16657    ../
16658    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
16660 Project Search Path:
16661    <Current_Directory>
16662    /home/comar/local/lib/gnat/
16664 ./demo1.o
16665    Unit =>
16666      Name   => demo1
16667      Kind   => subprogram body
16668      Flags  => No_Elab_Code
16669      Source => demo1.adb    modified
16670 @end smallexample
16672 @noindent
16673 The following is an example of use of the dependency list.
16674 Note the use of the -s switch
16675 which gives a straight list of source files. This can be useful for
16676 building specialized scripts.
16678 @smallexample
16679 $ gnatls -d demo2.o
16680 ./demo2.o   demo2        OK demo2.adb
16681                          OK gen_list.ads
16682                          OK gen_list.adb
16683                          OK instr.ads
16684                          OK instr-child.ads
16686 $ gnatls -d -s -a demo1.o
16687 demo1.adb
16688 /home/comar/local/adainclude/ada.ads
16689 /home/comar/local/adainclude/a-finali.ads
16690 /home/comar/local/adainclude/a-filico.ads
16691 /home/comar/local/adainclude/a-stream.ads
16692 /home/comar/local/adainclude/a-tags.ads
16693 gen_list.ads
16694 gen_list.adb
16695 /home/comar/local/adainclude/gnat.ads
16696 /home/comar/local/adainclude/g-io.ads
16697 instr.ads
16698 /home/comar/local/adainclude/system.ads
16699 /home/comar/local/adainclude/s-exctab.ads
16700 /home/comar/local/adainclude/s-finimp.ads
16701 /home/comar/local/adainclude/s-finroo.ads
16702 /home/comar/local/adainclude/s-secsta.ads
16703 /home/comar/local/adainclude/s-stalib.ads
16704 /home/comar/local/adainclude/s-stoele.ads
16705 /home/comar/local/adainclude/s-stratt.ads
16706 /home/comar/local/adainclude/s-tasoli.ads
16707 /home/comar/local/adainclude/s-unstyp.ads
16708 /home/comar/local/adainclude/unchconv.ads
16709 @end smallexample
16710 @end ifclear
16712 @ifset vms
16713 @smallexample
16714 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16716 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16717 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16718 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16719 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16720 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16721 demo1.adb
16722 gen_list.ads
16723 gen_list.adb
16724 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16725 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16726 instr.ads
16727 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16728 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16729 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16730 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16731 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16732 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16733 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16734 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16735 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16736 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16737 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16738 @end smallexample
16739 @end ifset
16741 @node Cleaning Up Using gnatclean
16742 @chapter Cleaning Up Using @code{gnatclean}
16743 @findex gnatclean
16744 @cindex Cleaning tool
16746 @noindent
16747 @code{gnatclean} is a tool that allows the deletion of files produced by the
16748 compiler, binder and linker, including ALI files, object files, tree files,
16749 expanded source files, library files, interface copy source files, binder
16750 generated files and executable files.
16752 @menu
16753 * Running gnatclean::
16754 * Switches for gnatclean::
16755 * Examples of gnatclean Usage::
16756 @end menu
16758 @node Running gnatclean
16759 @section Running @code{gnatclean}
16761 @noindent
16762 The @code{gnatclean} command has the form:
16764 @smallexample
16765 $ gnatclean switches @var{names}
16766 @end smallexample
16768 @noindent
16769 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16770 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16771 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16773 @noindent
16774 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16775 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16776 the linker. In informative-only mode, specified by switch
16777 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16778 normal mode is listed, but no file is actually deleted.
16780 @node Switches for gnatclean
16781 @section Switches for @code{gnatclean}
16783 @noindent
16784 @code{gnatclean} recognizes the following switches:
16786 @table @option
16787 @c !sort!
16788 @item ^-c^/COMPILER_FILES_ONLY^
16789 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16790 Only attempt to delete the files produced by the compiler, not those produced
16791 by the binder or the linker. The files that are not to be deleted are library
16792 files, interface copy files, binder generated files and executable files.
16794 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16795 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16796 Indicate that ALI and object files should normally be found in directory
16797 @var{dir}.
16799 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16800 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16801 When using project files, if some errors or warnings are detected during
16802 parsing and verbose mode is not in effect (no use of switch
16803 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16804 file, rather than its simple file name.
16806 @item ^-h^/HELP^
16807 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16808 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16810 @item ^-n^/NODELETE^
16811 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16812 Informative-only mode. Do not delete any files. Output the list of the files
16813 that would have been deleted if this switch was not specified.
16815 @item ^-P^/PROJECT_FILE=^@var{project}
16816 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16817 Use project file @var{project}. Only one such switch can be used.
16818 When cleaning a project file, the files produced by the compilation of the
16819 immediate sources or inherited sources of the project files are to be
16820 deleted. This is not depending on the presence or not of executable names
16821 on the command line.
16823 @item ^-q^/QUIET^
16824 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16825 Quiet output. If there are no error, do not ouuput anything, except in
16826 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16827 (switch ^-n^/NODELETE^).
16829 @item ^-r^/RECURSIVE^
16830 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16831 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16832 clean all imported and extended project files, recursively. If this switch
16833 is not specified, only the files related to the main project file are to be
16834 deleted. This switch has no effect if no project file is specified.
16836 @item ^-v^/VERBOSE^
16837 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16838 Verbose mode.
16840 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16841 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16842 Indicates the verbosity of the parsing of GNAT project files.
16843 See @ref{Switches Related to Project Files}.
16845 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16846 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16847 Indicates that external variable @var{name} has the value @var{value}.
16848 The Project Manager will use this value for occurrences of
16849 @code{external(name)} when parsing the project file.
16850 See @ref{Switches Related to Project Files}.
16852 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16853 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16854 When searching for ALI and object files, look in directory
16855 @var{dir}.
16857 @item ^-I^/SEARCH=^@var{dir}
16858 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16859 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16861 @item ^-I-^/NOCURRENT_DIRECTORY^
16862 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16863 @cindex Source files, suppressing search
16864 Do not look for ALI or object files in the directory
16865 where @code{gnatclean} was invoked.
16867 @end table
16869 @node Examples of gnatclean Usage
16870 @section Examples of @code{gnatclean} Usage
16872 @ifclear vms
16873 @node GNAT and Libraries
16874 @chapter GNAT and Libraries
16875 @cindex Library, building, installing, using
16877 @noindent
16878 This chapter describes how to build and use libraries with GNAT, and also shows
16879 how to recompile the GNAT run-time library. You should be familiar with the
16880 Project Manager facility (see @ref{GNAT Project Manager}) before reading this
16881 chapter.
16883 @menu
16884 * Introduction to Libraries in GNAT::
16885 * General Ada Libraries::
16886 * Stand-alone Ada Libraries::
16887 * Rebuilding the GNAT Run-Time Library::
16888 @end menu
16890 @node Introduction to Libraries in GNAT
16891 @section Introduction to Libraries in GNAT
16893 @noindent
16894 A library is, conceptually, a collection of objects which does not have its
16895 own main thread of execution, but rather provides certain services to the
16896 applications that use it. A library can be either statically linked with the
16897 application, in which case its code is directly included in the application,
16898 or, on platforms that support it, be dynamically linked, in which case
16899 its code is shared by all applications making use of this library.
16901 GNAT supports both types of libraries.
16902 In the static case, the compiled code can be provided in different ways. The
16903 simplest approach is to provide directly the set of objects resulting from
16904 compilation of the library source files. Alternatively, you can group the
16905 objects into an archive using whatever commands are provided by the operating
16906 system. For the latter case, the objects are grouped into a shared library.
16908 In the GNAT environment, a library has three types of components:
16909 @itemize @bullet
16910 @item
16911 Source files.
16912 @item
16913 @file{ALI} files.
16914 See @ref{The Ada Library Information Files}.
16915 @item
16916 Object files, an archive or a shared library.
16917 @end itemize
16919 @noindent
16920 A GNAT library may expose all its source files, which is useful for
16921 documentation purposes. Alternatively, it may expose only the units needed by
16922 an external user to make use of the library. That is to say, the specs
16923 expliciting the library services along with all the units needed to compile
16924 those specs, which can include generic bodies or any body implementing an
16925 inlined routine. In the case of @emph{stand-alone libraries} those exposed
16926 units are called @emph{interface units} (see @ref{Stand-alone Ada Libraries}).
16928 All compilation units comprising an application, including those in a library,
16929 need to be elaborated in an order partially defined by Ada's semantics. GNAT
16930 computes the elaboration order from the @file{ALI} files and this is why they
16931 constitute a mandatory part of GNAT libraries. Except in the case of
16932 @emph{stand-alone libraries}, where a specific library elaboration routine is
16933 produced independantly of the application(s) using the library.
16935 @node General Ada Libraries
16936 @section General Ada Libraries
16938 @menu
16939 * Building a library::
16940 * Installing a library::
16941 * Using a library::
16942 @end menu
16944 @node Building a library
16945 @subsection Building a library
16947 @noindent
16948 The easiest way to build a library is to use the Project Manager,
16949 which supports a special type of projects called Library Projects
16950 (see @ref{Library Projects}).
16952 A project is considered a library project, when two project-level attributes
16953 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
16954 control different aspects of library configuration, additional optional
16955 project-level attributes can be specified:
16956 @table @code
16957 @item Library_Kind
16958 This attribute controls whether the library is to be static or dynamic
16960 @item Library_Version
16961 This attribute specifies what is the library version; this value is used
16962 during dynamic linking of shared libraries to determine if the currently
16963 installed versions of the binaries are compatible.
16965 @item Library_Options
16966 @item Library_GCC
16967 These attributes specify additional low-level options to be used during
16968 library generation, and redefine the actual application used to generate
16969 library.
16970 @end table
16972 @noindent
16973 The GNAT Project Manager takes full care of the library maintenance task,
16974 including recompilation of the source files for which objects do not exist
16975 or are not up to date, assembly of the library archive, and installation of
16976 the library, i.e. copying associated source, object and @file{ALI} files
16977 to the specified location.
16979 Here is a simple library project file:
16980 @smallexample @c ada
16981 project My_Lib is
16982    for Source_Dirs use ("src1", "src2");
16983    for Object_Dir use "obj";
16984    for Library_Name use "mylib";
16985    for Library_Dir use "lib";
16986    for Library_Kind use "dynamic";
16987 end My_lib;
16988 @end smallexample
16989 and the compilation command to build and install the library:
16990 @smallexample @c ada
16991   $ gnatmake -Pmy_lib
16992 @end smallexample
16994 It is not entirely trivial to perform manually all the steps required to
16995 produce a library. We recommend that you use the GNAT Project Manager
16996 for this task. In special cases where this is not desired, the necessary
16997 steps are discussed below.
16999 There are various possibilities for compiling the units that make up the
17000 library: for example with a Makefile (see @ref{Using the GNU make Utility}) or
17001 with a conventional script. For simple libraries, it is also possible to create
17002 dummy main program which depends upon all the packages that comprise the
17003 interface of the library. This dummy main program can then be given to
17004 @command{gnatmake}, which will ensure that all necessary objects are built.
17006 After this task is accomplished, you should follow the standard procedure
17007 of the underlying operating system to produce the static or shared library.
17009 Here is an example of such a dummy program:
17010 @smallexample @c ada
17011 @group
17012 with My_Lib.Service1;
17013 with My_Lib.Service2;
17014 with My_Lib.Service3;
17015 procedure My_Lib_Dummy is
17016 begin
17017    null;
17018 end;
17019 @end group
17020 @end smallexample
17022 @noindent
17023 Here are the generic commands that will build an archive or a shared library.
17025 @smallexample
17026 # compiling the library
17027 $ gnatmake -c my_lib_dummy.adb
17029 # we don't need the dummy object itself
17030 $ rm my_lib_dummy.o my_lib_dummy.ali
17032 # create an archive with the remaining objects
17033 $ ar rc libmy_lib.a *.o
17034 # some systems may require "ranlib" to be run as well
17036 # or create a shared library
17037 $ gcc -shared -o libmy_lib.so *.o
17038 # some systems may require the code to have been compiled with -fPIC
17040 # remove the object files that are now in the library
17041 $ rm *.o
17043 # Make the ALI files read-only so that gnatmake will not try to
17044 # regenerate the objects that are in the library
17045 $ chmod -w *.ali
17046 @end smallexample
17048 @noindent
17049 Please note that the library must have a name of the form @file{libxxx.a} or
17050 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
17051 the directive @option{-lxxx} at link time.
17053 @node Installing a library
17054 @subsection Installing a library
17056 @noindent
17057 When using project files, installing libraries is part of the library build
17058 process and thus, no further action is needed in order to make use of the
17059 libraries that are built as part of the general application build. A usable
17060 version of the library is installed in the directory specified by the
17061 @code{Library_Dir} attribute of the library project file.
17063 One may want to install a library in a context different from where the library
17064 is built. This is, for instance, the case of third party suppliers, who whish
17065 to distribute a library in binary form where the user is not expected to be
17066 able to recompile the library. The simplest option, in this case, is to provide
17067 project file slightly different from the one used to build the library which
17068 makes use of the @code{externally_built} attribute. For instance the project
17069 file used to build the library in the previous section can be changed into the
17070 following one when the library is installed:
17072 @smallexample @c ada
17073 project My_Lib is
17074    for Source_Dirs use ("src1", "src2");
17075    for Library_Name use "mylib";
17076    for Library_Dir use "lib";
17077    for Library_Kind use "dynamic";
17078    for Externally_Built use "true";
17079 end My_lib;
17080 @end smallexample
17082 This project file assumes that the directories "src1", "src2" & "lib" exist in
17083 the directory containing the project file. The @code{externally_built}
17084 attribute makes it clear to the GNAT builder that it should not attempt to
17085 recompile any of the units from this library. It allows the library provider to
17086 restrict the source set to the minimum necessary for clients to make use of the
17087 library as described in the first section of this chapter. It is the
17088 responsability of the library provider to install the necessary sources, ALI
17089 files & libraries in the directories mentioned in the project file. For
17090 convenience to the user, it is recommended to install the user's library
17091 project file in a location that will be searched automatically by the GNAT
17092 builder. That is to say, any directory refernced in the @code{ADA_LIBRARY_PATH}
17093 environmenbt variable (see @ref{Importing Projects}), or in the default GNAT
17094 library location that can be queried with @code{gnatls -v} and is usually of
17095 the form $gnat_install_root/lib/gnat.
17097 When project files are not an option, it is also possible, but not recommended,
17098 to install the library so that the sources needed to use the library be on the
17099 Ada source path and the ALI files & libraries be on the Ada Object path (see
17100 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, he system
17101 administrator can place general purpose libraries in the default compiler
17102 paths, by specifying the libraries' location in the configuration files
17103 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17104 must be located in the GNAT installation tree at the same place as the gcc spec
17105 file. The location of the gcc spec file can be determined as follows:
17106 @smallexample
17107 $ gcc -v
17108 @end smallexample
17110 @noindent
17111 The configuration files mentioned above have a simple format: each line
17112 must contain one unique directory name.
17113 Those names are added to the corresponding path
17114 in their order of appearance in the file. The names can be either absolute
17115 or relative; in the latter case, they are relative to where theses files
17116 are located.
17118 The files @file{ada_source_path} and @file{ada_object_path} might not be
17119 present in a
17120 GNAT installation, in which case, GNAT will look for its run-time library in
17121 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17122 objects and @file{ALI} files). When the files exist, the compiler does not
17123 look in @file{adainclude} and @file{adalib}, and thus the
17124 @file{ada_source_path} file
17125 must contain the location for the GNAT run-time sources (which can simply
17126 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17127 contain the location for the GNAT run-time objects (which can simply
17128 be @file{adalib}).
17130 You can also specify a new default path to the run-time library at compilation
17131 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17132 the run-time library you want your program to be compiled with. This switch is
17133 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17134 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17136 It is possible to install a library before or after the standard GNAT
17137 library, by reordering the lines in the configuration files. In general, a
17138 library must be installed before the GNAT library if it redefines
17139 any part of it.
17141 @node Using a library
17142 @subsection Using a library
17144 @noindent Once again, the project facility greatly simplifies the use of
17145 libraries. In this context, using a library is just a matter of adding a
17146 @code{with} clause in the user project. For instance, to make use of the
17147 library "My_Lib" used as an examples in earlier sections, is just a matter of
17148 writing something like:
17149 @smallexample @c ada
17150 with "my_lib";
17151 project My_Proj is
17152   ...
17153 end My_Proj;
17154 @end smallexample
17156 Even if you have a third-party, non-Ada library, you can still use GNAT's
17157 Project Manager facility to provide a wrapper for it. The following project for
17158 example, when @code{with}ed in your main project, will link with the
17159 third-party library @file{liba.a}:
17161 @smallexample @c projectfile
17162 @group
17163 project Liba is
17164    for Source_Dirs use ();
17165    for Library_Dir use "lib";
17166    for Library_Name use "a";
17167    for Library_Kind use "static";
17168 end Liba;
17169 @end group
17170 @end smallexample
17172 @noindent
17173 In order to use an Ada library manually, you need to make sure that this
17174 library is on both your source and object path
17175 (see @ref{Search Paths and the Run-Time Library (RTL)},
17176 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17177 in an archive or a shared library, you need to specify the desired
17178 library at link time.
17180 For example, you can use the library @file{mylib} installed in
17181 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17183 @smallexample
17184 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17185   -largs -lmy_lib
17186 @end smallexample
17188 @noindent
17189 This can be expressed more simply:
17190 @smallexample
17191 $ gnatmake my_appl
17192 @end smallexample
17193 @noindent
17194 when the following conditions are met:
17195 @itemize @bullet
17196 @item
17197 @file{/dir/my_lib_src} has been added by the user to the environment
17198 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
17199 @file{ada_source_path}
17200 @item
17201 @file{/dir/my_lib_obj} has been added by the user to the environment
17202 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
17203 @file{ada_object_path}
17204 @item
17205 a pragma @code{Linker_Options} has been added to one of the sources.
17206 For example:
17208 @smallexample @c ada
17209 pragma Linker_Options ("-lmy_lib");
17210 @end smallexample
17211 @end itemize
17213 @node Stand-alone Ada Libraries
17214 @section Stand-alone Ada Libraries
17215 @cindex Stand-alone library, building, using
17217 @menu
17218 * Introduction to Stand-alone Libraries::
17219 * Building a Stand-alone Library::
17220 * Creating a Stand-alone Library to be used in a non-Ada context::
17221 * Restrictions in Stand-alone Libraries::
17222 @end menu
17224 @node Introduction to Stand-alone Libraries
17225 @subsection Introduction to Stand-alone Libraries
17227 @noindent
17228 A Stand-alone Library (SAL) is a library that contains the necessary code to
17229 elaborate the Ada units that are included in the library. In contrast with
17230 an ordinary library, which consists of all sources, objects and @file{ALI}
17231 files of the
17232 library, a SAL may specify a restricted subset of compilation units
17233 to serve as a library interface. In this case, the fully
17234 self-sufficient set of files will normally consist of an objects
17235 archive, the sources of interface units' specs, and the @file{ALI}
17236 files of interface units.
17237 If an interface spec contains a generic unit or an inlined subprogram,
17238 the body's
17239 source must also be provided; if the units that must be provided in the source
17240 form depend on other units, the source and @file{ALI} files of those must
17241 also be provided.
17243 The main purpose of a SAL is to minimize the recompilation overhead of client
17244 applications when a new version of the library is installed. Specifically,
17245 if the interface sources have not changed, client applications do not need to
17246 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17247 version, controlled by @code{Library_Version} attribute, is not changed,
17248 then the clients do not need to be relinked.
17250 SALs also allow the library providers to minimize the amount of library source
17251 text exposed to the clients.  Such ``information hiding'' might be useful or
17252 necessary for various reasons.
17254 Stand-alone libraries are also well suited to be used in an executable whose
17255 main routine is not written in Ada.
17257 @node Building a Stand-alone Library
17258 @subsection Building a Stand-alone Library
17260 @noindent
17261 GNAT's Project facility provides a simple way of building and installing
17262 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17263 To be a Stand-alone Library Project, in addition to the two attributes
17264 that make a project a Library Project (@code{Library_Name} and
17265 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17266 @code{Library_Interface} must be defined.  For example:
17268 @smallexample @c projectfile
17269 @group
17270    for Library_Dir use "lib_dir";
17271    for Library_Name use "dummy";
17272    for Library_Interface use ("int1", "int1.child");
17273 @end group
17274 @end smallexample
17276 @noindent
17277 Attribute @code{Library_Interface} has a non empty string list value,
17278 each string in the list designating a unit contained in an immediate source
17279 of the project file.
17281 When a Stand-alone Library is built, first the binder is invoked to build
17282 a package whose name depends on the library name
17283 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17284 This binder-generated package includes initialization and
17285 finalization procedures whose
17286 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17287 in the example
17288 above). The object corresponding to this package is included in the library.
17290 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17291 calling of these procedures if a static SAL is built, or if a shared SAL
17292 is built
17293 with the project-level attribute @code{Library_Auto_Init} set to
17294 @code{"false"}.
17296 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17297 (those that are listed in attribute @code{Library_Interface}) are copied to
17298 the Library Directory. As a consequence, only the Interface Units may be
17299 imported from Ada units outside of the library. If other units are imported,
17300 the binding phase will fail.
17302 The attribute @code{Library_Src_Dir} may be specified for a
17303 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17304 single string value. Its value must be the path (absolute or relative to the
17305 project directory) of an existing directory. This directory cannot be the
17306 object directory or one of the source directories, but it can be the same as
17307 the library directory. The sources of the Interface
17308 Units of the library that are needed by an Ada client of the library will be
17309 copied to the designated directory, called the Interface Copy directory.
17310 These sources includes the specs of the Interface Units, but they may also
17311 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17312 are used, or when there is a generic unit in the spec. Before the sources
17313 are copied to the Interface Copy directory, an attempt is made to delete all
17314 files in the Interface Copy directory.
17316 Building stand-alone libraries by hand is somewhat tedious, but for those
17317 occasions when it is necessary here are the steps that you need to perform:
17318 @itemize @bullet
17319 @item
17320 Compile all library sources.
17322 @item
17323 Invoke the binder with the switch @option{-n} (No Ada main program),
17324 with all the @file{ALI} files of the interfaces, and
17325 with the switch @option{-L} to give specific names to the @code{init}
17326 and @code{final} procedures.  For example:
17327 @smallexample
17328   gnatbind -n int1.ali int2.ali -Lsal1
17329 @end smallexample
17331 @item
17332 Compile the binder generated file:
17333 @smallexample
17334   gcc -c b~int2.adb
17335 @end smallexample
17337 @item
17338 Link the dynamic library with all the necessary object files,
17339 indicating to the linker the names of the @code{init} (and possibly
17340 @code{final}) procedures for automatic initialization (and finalization).
17341 The built library should be placed in a directory different from
17342 the object directory.
17344 @item
17345 Copy the @code{ALI} files of the interface to the library directory,
17346 add in this copy an indication that it is an interface to a SAL
17347 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
17348 with letter ``P'') and make the modified copy of the @file{ALI} file
17349 read-only.
17350 @end itemize
17352 @noindent
17353 Using SALs is not different from using other libraries
17354 (see @ref{Using a library}).
17356 @node Creating a Stand-alone Library to be used in a non-Ada context
17357 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17359 @noindent
17360 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17361 a non-Ada context.
17363 The only extra step required is to ensure that library interface subprograms
17364 are compatible with the main program, by means of @code{pragma Export}
17365 or @code{pragma Convention}.
17367 Here is an example of simple library interface for use with C main program:
17369 @smallexample @c ada
17370 package Interface is
17372    procedure Do_Something;
17373    pragma Export (C, Do_Something, "do_something");
17375    procedure Do_Something_Else;
17376    pragma Export (C, Do_Something_Else, "do_something_else");
17378 end Interface;
17379 @end smallexample
17381 @noindent
17382 On the foreign language side, you must provide a ``foreign'' view of the
17383 library interface; remember that it should contain elaboration routines in
17384 addition to interface subprograms.
17386 The example below shows the content of @code{mylib_interface.h} (note
17387 that there is no rule for the naming of this file, any name can be used)
17388 @smallexample
17389 /* the library elaboration procedure */
17390 extern void mylibinit (void);
17392 /* the library finalization procedure */
17393 extern void mylibfinal (void);
17395 /* the interface exported by the library */
17396 extern void do_something (void);
17397 extern void do_something_else (void);
17398 @end smallexample
17400 @noindent
17401 Libraries built as explained above can be used from any program, provided
17402 that the elaboration procedures (named @code{mylibinit} in the previous
17403 example) are called before the library services are used. Any number of
17404 libraries can be used simultaneously, as long as the elaboration
17405 procedure of each library is called.
17407 Below is an example of C program that uses the @code{mylib} library.
17409 @smallexample
17410 #include "mylib_interface.h"
17413 main (void)
17415    /* First, elaborate the library before using it */
17416    mylibinit ();
17418    /* Main program, using the library exported entities */
17419    do_something ();
17420    do_something_else ();
17422    /* Library finalization at the end of the program */
17423    mylibfinal ();
17424    return 0;
17426 @end smallexample
17428 @noindent
17429 Note that invoking any library finalization procedure generated by
17430 @code{gnatbind} shuts down the Ada run-time environment.
17431 Consequently, the
17432 finalization of all Ada libraries must be performed at the end of the program.
17433 No call to these libraries nor to the Ada run-time library should be made
17434 after the finalization phase.
17436 @node Restrictions in Stand-alone Libraries
17437 @subsection Restrictions in Stand-alone Libraries
17439 @noindent
17440 The pragmas listed below should be used with caution inside libraries,
17441 as they can create incompatibilities with other Ada libraries:
17442 @itemize @bullet
17443 @item pragma @code{Locking_Policy}
17444 @item pragma @code{Queuing_Policy}
17445 @item pragma @code{Task_Dispatching_Policy}
17446 @item pragma @code{Unreserve_All_Interrupts}
17447 @end itemize
17449 @noindent
17450 When using a library that contains such pragmas, the user must make sure
17451 that all libraries use the same pragmas with the same values. Otherwise,
17452 @code{Program_Error} will
17453 be raised during the elaboration of the conflicting
17454 libraries. The usage of these pragmas and its consequences for the user
17455 should therefore be well documented.
17457 Similarly, the traceback in the exception occurrence mechanism should be
17458 enabled or disabled in a consistent manner across all libraries.
17459 Otherwise, Program_Error will be raised during the elaboration of the
17460 conflicting libraries.
17462 If the @code{Version} or @code{Body_Version}
17463 attributes are used inside a library, then you need to
17464 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17465 libraries, so that version identifiers can be properly computed.
17466 In practice these attributes are rarely used, so this is unlikely
17467 to be a consideration.
17469 @node  Rebuilding the GNAT Run-Time Library
17470 @section Rebuilding the GNAT Run-Time Library
17471 @cindex GNAT Run-Time Library, rebuilding
17473 @noindent
17474 It may be useful to recompile the GNAT library in various contexts, the
17475 most important one being the use of partition-wide configuration pragmas
17476 such as @code{Normalize_Scalars}. A special Makefile called
17477 @code{Makefile.adalib} is provided to that effect and can be found in
17478 the directory containing the GNAT library. The location of this
17479 directory depends on the way the GNAT environment has been installed and can
17480 be determined by means of the command:
17482 @smallexample
17483 $ gnatls -v
17484 @end smallexample
17486 @noindent
17487 The last entry in the object search path usually contains the
17488 gnat library. This Makefile contains its own documentation and in
17489 particular the set of instructions needed to rebuild a new library and
17490 to use it.
17492 @node Using the GNU make Utility
17493 @chapter Using the GNU @code{make} Utility
17494 @findex make
17496 @noindent
17497 This chapter offers some examples of makefiles that solve specific
17498 problems. It does not explain how to write a makefile (see the GNU make
17499 documentation), nor does it try to replace the @code{gnatmake} utility
17500 (@pxref{The GNAT Make Program gnatmake}).
17502 All the examples in this section are specific to the GNU version of
17503 make. Although @code{make} is a standard utility, and the basic language
17504 is the same, these examples use some advanced features found only in
17505 @code{GNU make}.
17507 @menu
17508 * Using gnatmake in a Makefile::
17509 * Automatically Creating a List of Directories::
17510 * Generating the Command Line Switches::
17511 * Overcoming Command Line Length Limits::
17512 @end menu
17514 @node Using gnatmake in a Makefile
17515 @section Using gnatmake in a Makefile
17516 @findex makefile
17517 @cindex GNU make
17519 @noindent
17520 Complex project organizations can be handled in a very powerful way by
17521 using GNU make combined with gnatmake. For instance, here is a Makefile
17522 which allows you to build each subsystem of a big project into a separate
17523 shared library. Such a makefile allows you to significantly reduce the link
17524 time of very big applications while maintaining full coherence at
17525 each step of the build process.
17527 The list of dependencies are handled automatically by
17528 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
17529 the appropriate directories.
17531 Note that you should also read the example on how to automatically
17532 create the list of directories
17533 (@pxref{Automatically Creating a List of Directories})
17534 which might help you in case your project has a lot of subdirectories.
17536 @smallexample
17537 @iftex
17538 @leftskip=0cm
17539 @font@heightrm=cmr8
17540 @heightrm
17541 @end iftex
17542 ## This Makefile is intended to be used with the following directory
17543 ## configuration:
17544 ##  - The sources are split into a series of csc (computer software components)
17545 ##    Each of these csc is put in its own directory.
17546 ##    Their name are referenced by the directory names.
17547 ##    They will be compiled into shared library (although this would also work
17548 ##    with static libraries
17549 ##  - The main program (and possibly other packages that do not belong to any
17550 ##    csc is put in the top level directory (where the Makefile is).
17551 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17552 ##                    \_ second_csc (sources) __ lib (will contain the library)
17553 ##                    \_ ...
17554 ## Although this Makefile is build for shared library, it is easy to modify
17555 ## to build partial link objects instead (modify the lines with -shared and
17556 ## gnatlink below)
17558 ## With this makefile, you can change any file in the system or add any new
17559 ## file, and everything will be recompiled correctly (only the relevant shared
17560 ## objects will be recompiled, and the main program will be re-linked).
17562 # The list of computer software component for your project. This might be
17563 # generated automatically.
17564 CSC_LIST=aa bb cc
17566 # Name of the main program (no extension)
17567 MAIN=main
17569 # If we need to build objects with -fPIC, uncomment the following line
17570 #NEED_FPIC=-fPIC
17572 # The following variable should give the directory containing libgnat.so
17573 # You can get this directory through 'gnatls -v'. This is usually the last
17574 # directory in the Object_Path.
17575 GLIB=...
17577 # The directories for the libraries
17578 # (This macro expands the list of CSC to the list of shared libraries, you
17579 # could simply use the expanded form :
17580 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17581 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17583 $@{MAIN@}: objects $@{LIB_DIR@}
17584     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17585     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17587 objects::
17588     # recompile the sources
17589     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17591 # Note: In a future version of GNAT, the following commands will be simplified
17592 # by a new tool, gnatmlib
17593 $@{LIB_DIR@}:
17594     mkdir -p $@{dir $@@ @}
17595     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17596     cd $@{dir $@@ @}; cp -f ../*.ali .
17598 # The dependencies for the modules
17599 # Note that we have to force the expansion of *.o, since in some cases
17600 # make won't be able to do it itself.
17601 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17602 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17603 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17605 # Make sure all of the shared libraries are in the path before starting the
17606 # program
17607 run::
17608     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17610 clean::
17611     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17612     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17613     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17614     $@{RM@} *.o *.ali $@{MAIN@}
17615 @end smallexample
17617 @node Automatically Creating a List of Directories
17618 @section Automatically Creating a List of Directories
17620 @noindent
17621 In most makefiles, you will have to specify a list of directories, and
17622 store it in a variable. For small projects, it is often easier to
17623 specify each of them by hand, since you then have full control over what
17624 is the proper order for these directories, which ones should be
17625 included...
17627 However, in larger projects, which might involve hundreds of
17628 subdirectories, it might be more convenient to generate this list
17629 automatically.
17631 The example below presents two methods. The first one, although less
17632 general, gives you more control over the list. It involves wildcard
17633 characters, that are automatically expanded by @code{make}. Its
17634 shortcoming is that you need to explicitly specify some of the
17635 organization of your project, such as for instance the directory tree
17636 depth, whether some directories are found in a separate tree,...
17638 The second method is the most general one. It requires an external
17639 program, called @code{find}, which is standard on all Unix systems. All
17640 the directories found under a given root directory will be added to the
17641 list.
17643 @smallexample
17644 @iftex
17645 @leftskip=0cm
17646 @font@heightrm=cmr8
17647 @heightrm
17648 @end iftex
17649 # The examples below are based on the following directory hierarchy:
17650 # All the directories can contain any number of files
17651 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17652 #                       ->  ab
17653 #                       ->  ac
17654 #                ->  b  ->  ba  ->  baa
17655 #                       ->  bb
17656 #                       ->  bc
17657 # This Makefile creates a variable called DIRS, that can be reused any time
17658 # you need this list (see the other examples in this section)
17660 # The root of your project's directory hierarchy
17661 ROOT_DIRECTORY=.
17663 ####
17664 # First method: specify explicitly the list of directories
17665 # This allows you to specify any subset of all the directories you need.
17666 ####
17668 DIRS := a/aa/ a/ab/ b/ba/
17670 ####
17671 # Second method: use wildcards
17672 # Note that the argument(s) to wildcard below should end with a '/'.
17673 # Since wildcards also return file names, we have to filter them out
17674 # to avoid duplicate directory names.
17675 # We thus use make's @code{dir} and @code{sort} functions.
17676 # It sets DIRs to the following value (note that the directories aaa and baa
17677 # are not given, unless you change the arguments to wildcard).
17678 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17679 ####
17681 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17682                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17684 ####
17685 # Third method: use an external program
17686 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17687 # This is the most complete command: it sets DIRs to the following value:
17688 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17689 ####
17691 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17693 @end smallexample
17695 @node Generating the Command Line Switches
17696 @section Generating the Command Line Switches
17698 @noindent
17699 Once you have created the list of directories as explained in the
17700 previous section (@pxref{Automatically Creating a List of Directories}),
17701 you can easily generate the command line arguments to pass to gnatmake.
17703 For the sake of completeness, this example assumes that the source path
17704 is not the same as the object path, and that you have two separate lists
17705 of directories.
17707 @smallexample
17708 # see "Automatically creating a list of directories" to create
17709 # these variables
17710 SOURCE_DIRS=
17711 OBJECT_DIRS=
17713 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17714 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17716 all:
17717         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17718 @end smallexample
17720 @node Overcoming Command Line Length Limits
17721 @section Overcoming Command Line Length Limits
17723 @noindent
17724 One problem that might be encountered on big projects is that many
17725 operating systems limit the length of the command line. It is thus hard to give
17726 gnatmake the list of source and object directories.
17728 This example shows how you can set up environment variables, which will
17729 make @code{gnatmake} behave exactly as if the directories had been
17730 specified on the command line, but have a much higher length limit (or
17731 even none on most systems).
17733 It assumes that you have created a list of directories in your Makefile,
17734 using one of the methods presented in
17735 @ref{Automatically Creating a List of Directories}.
17736 For the sake of completeness, we assume that the object
17737 path (where the ALI files are found) is different from the sources patch.
17739 Note a small trick in the Makefile below: for efficiency reasons, we
17740 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17741 expanded immediately by @code{make}. This way we overcome the standard
17742 make behavior which is to expand the variables only when they are
17743 actually used.
17745 On Windows, if you are using the standard Windows command shell, you must
17746 replace colons with semicolons in the assignments to these variables.
17748 @smallexample
17749 @iftex
17750 @leftskip=0cm
17751 @font@heightrm=cmr8
17752 @heightrm
17753 @end iftex
17754 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
17755 # This is the same thing as putting the -I arguments on the command line.
17756 # (the equivalent of using -aI on the command line would be to define
17757 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
17758 # You can of course have different values for these variables.
17760 # Note also that we need to keep the previous values of these variables, since
17761 # they might have been set before running 'make' to specify where the GNAT
17762 # library is installed.
17764 # see "Automatically creating a list of directories" to create these
17765 # variables
17766 SOURCE_DIRS=
17767 OBJECT_DIRS=
17769 empty:=
17770 space:=$@{empty@} $@{empty@}
17771 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17772 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17773 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17774 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
17775 export ADA_INCLUDE_PATH
17776 export ADA_OBJECT_PATH
17778 all:
17779         gnatmake main_unit
17780 @end smallexample
17781 @end ifclear
17783 @node Memory Management Issues
17784 @chapter Memory Management Issues
17786 @noindent
17787 This chapter describes some useful memory pools provided in the GNAT library
17788 and in particular the GNAT Debug Pool facility, which can be used to detect
17789 incorrect uses of access values (including ``dangling references'').
17790 @ifclear vms
17791 It also describes the @command{gnatmem} tool, which can be used to track down
17792 ``memory leaks''.
17793 @end ifclear
17795 @menu
17796 * Some Useful Memory Pools::
17797 * The GNAT Debug Pool Facility::
17798 @ifclear vms
17799 * The gnatmem Tool::
17800 @end ifclear
17801 @end menu
17803 @node Some Useful Memory Pools
17804 @section Some Useful Memory Pools
17805 @findex Memory Pool
17806 @cindex storage, pool
17808 @noindent
17809 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17810 storage pool. Allocations use the standard system call @code{malloc} while
17811 deallocations use the standard system call @code{free}. No reclamation is
17812 performed when the pool goes out of scope. For performance reasons, the
17813 standard default Ada allocators/deallocators do not use any explicit storage
17814 pools but if they did, they could use this storage pool without any change in
17815 behavior. That is why this storage pool is used  when the user
17816 manages to make the default implicit allocator explicit as in this example:
17817 @smallexample @c ada
17818    type T1 is access Something;
17819     -- no Storage pool is defined for T2
17820    type T2 is access Something_Else;
17821    for T2'Storage_Pool use T1'Storage_Pool;
17822    -- the above is equivalent to
17823    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
17824 @end smallexample
17826 @noindent
17827 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17828 pool. The allocation strategy is similar to @code{Pool_Local}'s
17829 except that the all
17830 storage allocated with this pool is reclaimed when the pool object goes out of
17831 scope. This pool provides a explicit mechanism similar to the implicit one
17832 provided by several Ada 83 compilers for allocations performed through a local
17833 access type and whose purpose was to reclaim memory when exiting the
17834 scope of a given local access. As an example, the following program does not
17835 leak memory even though it does not perform explicit deallocation:
17837 @smallexample @c ada
17838 with System.Pool_Local;
17839 procedure Pooloc1 is
17840    procedure Internal is
17841       type A is access Integer;
17842       X : System.Pool_Local.Unbounded_Reclaim_Pool;
17843       for A'Storage_Pool use X;
17844       v : A;
17845    begin
17846       for I in  1 .. 50 loop
17847          v := new Integer;
17848       end loop;
17849    end Internal;
17850 begin
17851    for I in  1 .. 100 loop
17852       Internal;
17853    end loop;
17854 end Pooloc1;
17855 @end smallexample
17857 @noindent
17858 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17859 @code{Storage_Size} is specified for an access type.
17860 The whole storage for the pool is
17861 allocated at once, usually on the stack at the point where the access type is
17862 elaborated. It is automatically reclaimed when exiting the scope where the
17863 access type is defined. This package is not intended to be used directly by the
17864 user and it is implicitly used for each such declaration:
17866 @smallexample @c ada
17867    type T1 is access Something;
17868    for T1'Storage_Size use 10_000;
17869 @end smallexample
17872 @node The GNAT Debug Pool Facility
17873 @section The GNAT Debug Pool Facility
17874 @findex Debug Pool
17875 @cindex storage, pool, memory corruption
17877 @noindent
17878 The use of unchecked deallocation and unchecked conversion can easily
17879 lead to incorrect memory references. The problems generated by such
17880 references are usually difficult to tackle because the symptoms can be
17881 very remote from the origin of the problem. In such cases, it is
17882 very helpful to detect the problem as early as possible. This is the
17883 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17885 In order to use the GNAT specific debugging pool, the user must
17886 associate a debug pool object with each of the access types that may be
17887 related to suspected memory problems. See Ada Reference Manual 13.11.
17888 @smallexample @c ada
17889 type Ptr is access Some_Type;
17890 Pool : GNAT.Debug_Pools.Debug_Pool;
17891 for Ptr'Storage_Pool use Pool;
17892 @end smallexample
17894 @noindent
17895 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17896 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17897 allow the user to redefine allocation and deallocation strategies. They
17898 also provide a checkpoint for each dereference, through the use of
17899 the primitive operation @code{Dereference} which is implicitly called at
17900 each dereference of an access value.
17902 Once an access type has been associated with a debug pool, operations on
17903 values of the type may raise four distinct exceptions,
17904 which correspond to four potential kinds of memory corruption:
17905 @itemize @bullet
17906 @item
17907 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17908 @item
17909 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17910 @item
17911 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17912 @item
17913 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
17914 @end itemize
17916 @noindent
17917 For types associated with a Debug_Pool, dynamic allocation is performed using
17918 the standard GNAT allocation routine. References to all allocated chunks of
17919 memory are kept in an internal dictionary. Several deallocation strategies are
17920 provided, whereupon the user can choose to release the memory to the system,
17921 keep it allocated for further invalid access checks, or fill it with an easily
17922 recognizable pattern for debug sessions. The memory pattern is the old IBM
17923 hexadecimal convention: @code{16#DEADBEEF#}.
17925 See the documentation in the file g-debpoo.ads for more information on the
17926 various strategies.
17928 Upon each dereference, a check is made that the access value denotes a
17929 properly allocated memory location. Here is a complete example of use of
17930 @code{Debug_Pools}, that includes typical instances of  memory corruption:
17931 @smallexample @c ada
17932 @iftex
17933 @leftskip=0cm
17934 @end iftex
17935 with Gnat.Io; use Gnat.Io;
17936 with Unchecked_Deallocation;
17937 with Unchecked_Conversion;
17938 with GNAT.Debug_Pools;
17939 with System.Storage_Elements;
17940 with Ada.Exceptions; use Ada.Exceptions;
17941 procedure Debug_Pool_Test is
17943    type T is access Integer;
17944    type U is access all T;
17946    P : GNAT.Debug_Pools.Debug_Pool;
17947    for T'Storage_Pool use P;
17949    procedure Free is new Unchecked_Deallocation (Integer, T);
17950    function UC is new Unchecked_Conversion (U, T);
17951    A, B : aliased T;
17953    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
17955 begin
17956    Info (P);
17957    A := new Integer;
17958    B := new Integer;
17959    B := A;
17960    Info (P);
17961    Free (A);
17962    begin
17963       Put_Line (Integer'Image(B.all));
17964    exception
17965       when E : others => Put_Line ("raised: " & Exception_Name (E));
17966    end;
17967    begin
17968       Free (B);
17969    exception
17970       when E : others => Put_Line ("raised: " & Exception_Name (E));
17971    end;
17972    B := UC(A'Access);
17973    begin
17974       Put_Line (Integer'Image(B.all));
17975    exception
17976       when E : others => Put_Line ("raised: " & Exception_Name (E));
17977    end;
17978    begin
17979       Free (B);
17980    exception
17981       when E : others => Put_Line ("raised: " & Exception_Name (E));
17982    end;
17983    Info (P);
17984 end Debug_Pool_Test;
17985 @end smallexample
17987 @noindent
17988 The debug pool mechanism provides the following precise diagnostics on the
17989 execution of this erroneous program:
17990 @smallexample
17991 Debug Pool info:
17992   Total allocated bytes :  0
17993   Total deallocated bytes :  0
17994   Current Water Mark:  0
17995   High Water Mark:  0
17997 Debug Pool info:
17998   Total allocated bytes :  8
17999   Total deallocated bytes :  0
18000   Current Water Mark:  8
18001   High Water Mark:  8
18003 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18004 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18005 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18006 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18007 Debug Pool info:
18008   Total allocated bytes :  8
18009   Total deallocated bytes :  4
18010   Current Water Mark:  4
18011   High Water Mark:  8
18012 @end smallexample
18014 @ifclear vms
18015 @node The gnatmem Tool
18016 @section The @command{gnatmem} Tool
18017 @findex gnatmem
18019 @noindent
18020 The @code{gnatmem} utility monitors dynamic allocation and
18021 deallocation activity in a program, and displays information about
18022 incorrect deallocations and possible sources of memory leaks.
18023 It provides three type of information:
18024 @itemize @bullet
18025 @item
18026 General information concerning memory management, such as the total
18027 number of allocations and deallocations, the amount of allocated
18028 memory and the high water mark, i.e. the largest amount of allocated
18029 memory in the course of program execution.
18031 @item
18032 Backtraces for all incorrect deallocations, that is to say deallocations
18033 which do not correspond to a valid allocation.
18035 @item
18036 Information on each allocation that is potentially the origin of a memory
18037 leak.
18038 @end itemize
18040 @menu
18041 * Running gnatmem::
18042 * Switches for gnatmem::
18043 * Example of gnatmem Usage::
18044 @end menu
18046 @node Running gnatmem
18047 @subsection Running @code{gnatmem}
18049 @noindent
18050 @code{gnatmem} makes use of the output created by the special version of
18051 allocation and deallocation routines that record call information. This
18052 allows to obtain accurate dynamic memory usage history at a minimal cost to
18053 the execution speed. Note however, that @code{gnatmem} is not supported on
18054 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
18055 Solaris (sparc and x86) and Windows NT/2000/XP (x86).
18057 @noindent
18058 The @code{gnatmem} command has the form
18060 @smallexample
18061    $ gnatmem [switches] user_program
18062 @end smallexample
18064 @noindent
18065 The program must have been linked with the instrumented version of the
18066 allocation and deallocation routines. This is done by linking with the
18067 @file{libgmem.a} library. For correct symbolic backtrace information,
18068 the user program should be compiled with debugging options
18069 @ref{Switches for gcc}. For example to build @file{my_program}:
18071 @smallexample
18072 $ gnatmake -g my_program -largs -lgmem
18073 @end smallexample
18075 @noindent
18076 When running @file{my_program} the file @file{gmem.out} is produced. This file
18077 contains information about all allocations and deallocations done by the
18078 program. It is produced by the instrumented allocations and
18079 deallocations routines and will be used by @code{gnatmem}.
18081 @noindent
18082 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18083 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18084 @code{-i} switch, gnatmem will assume that this file can be found in the
18085 current directory. For example, after you have executed @file{my_program},
18086 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18088 @smallexample
18089 $ gnatmem my_program
18090 @end smallexample
18092 @noindent
18093 This will produce the output with the following format:
18095 *************** debut cc
18096 @smallexample
18097 $ gnatmem my_program
18099 Global information
18100 ------------------
18101    Total number of allocations        :  45
18102    Total number of deallocations      :   6
18103    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18104    High Water Mark                    :  11.40 Kilobytes
18109 Allocation Root # 2
18110 -------------------
18111  Number of non freed allocations    :  11
18112  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18113  High Water Mark                    :   1.27 Kilobytes
18114  Backtrace                          :
18115    my_program.adb:23 my_program.alloc
18119 @end smallexample
18121 The first block of output gives general information. In this case, the
18122 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18123 Unchecked_Deallocation routine occurred.
18125 @noindent
18126 Subsequent paragraphs display  information on all allocation roots.
18127 An allocation root is a specific point in the execution of the program
18128 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18129 construct. This root is represented by an execution backtrace (or subprogram
18130 call stack). By default the backtrace depth for allocations roots is 1, so
18131 that a root corresponds exactly to a source location. The backtrace can
18132 be made deeper, to make the root more specific.
18134 @node Switches for gnatmem
18135 @subsection Switches for @code{gnatmem}
18137 @noindent
18138 @code{gnatmem} recognizes the following switches:
18140 @table @option
18142 @item -q
18143 @cindex @option{-q} (@code{gnatmem})
18144 Quiet. Gives the minimum output needed to identify the origin of the
18145 memory leaks. Omits statistical information.
18147 @item @var{N}
18148 @cindex @var{N} (@code{gnatmem})
18149 N is an integer literal (usually between 1 and 10) which controls the
18150 depth of the backtraces defining allocation root. The default value for
18151 N is 1. The deeper the backtrace, the more precise the localization of
18152 the root. Note that the total number of roots can depend on this
18153 parameter. This parameter must be specified @emph{before} the name of the
18154 executable to be analyzed, to avoid ambiguity.
18156 @item -b n
18157 @cindex @option{-b} (@code{gnatmem})
18158 This switch has the same effect as just depth parameter.
18160 @item -i @var{file}
18161 @cindex @option{-i} (@code{gnatmem})
18162 Do the @code{gnatmem} processing starting from @file{file}, rather than
18163 @file{gmem.out} in the current directory.
18165 @item -m n
18166 @cindex @option{-m} (@code{gnatmem})
18167 This switch causes @code{gnatmem} to mask the allocation roots that have less
18168 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18169 examine even the roots that didn't result in leaks.
18171 @item -s order
18172 @cindex @option{-s} (@code{gnatmem})
18173 This switch causes @code{gnatmem} to sort the allocation roots according to the
18174 specified order of sort criteria, each identified by a single letter. The
18175 currently supported criteria are @code{n, h, w} standing respectively for
18176 number of unfreed allocations, high watermark, and final watermark
18177 corresponding to a specific root. The default order is @code{nwh}.
18179 @end table
18181 @node Example of gnatmem Usage
18182 @subsection Example of @code{gnatmem} Usage
18184 @noindent
18185 The following example shows the use of @code{gnatmem}
18186 on a simple memory-leaking program.
18187 Suppose that we have the following Ada program:
18189 @smallexample @c ada
18190 @group
18191 @cartouche
18192 with Unchecked_Deallocation;
18193 procedure Test_Gm is
18195    type T is array (1..1000) of Integer;
18196    type Ptr is access T;
18197    procedure Free is new Unchecked_Deallocation (T, Ptr);
18198    A : Ptr;
18200    procedure My_Alloc is
18201    begin
18202       A := new T;
18203    end My_Alloc;
18205    procedure My_DeAlloc is
18206       B : Ptr := A;
18207    begin
18208       Free (B);
18209    end My_DeAlloc;
18211 begin
18212    My_Alloc;
18213    for I in 1 .. 5 loop
18214       for J in I .. 5 loop
18215          My_Alloc;
18216       end loop;
18217       My_Dealloc;
18218    end loop;
18219 end;
18220 @end cartouche
18221 @end group
18222 @end smallexample
18224 @noindent
18225 The program needs to be compiled with debugging option and linked with
18226 @code{gmem} library:
18228 @smallexample
18229 $ gnatmake -g test_gm -largs -lgmem
18230 @end smallexample
18232 @noindent
18233 Then we execute the program as usual:
18235 @smallexample
18236 $ test_gm
18237 @end smallexample
18239 @noindent
18240 Then @code{gnatmem} is invoked simply with
18241 @smallexample
18242 $ gnatmem test_gm
18243 @end smallexample
18245 @noindent
18246 which produces the following output (result may vary on different platforms):
18248 @smallexample
18249 Global information
18250 ------------------
18251    Total number of allocations        :  18
18252    Total number of deallocations      :   5
18253    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18254    High Water Mark                    :  56.90 Kilobytes
18256 Allocation Root # 1
18257 -------------------
18258  Number of non freed allocations    :  11
18259  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18260  High Water Mark                    :  46.88 Kilobytes
18261  Backtrace                          :
18262    test_gm.adb:11 test_gm.my_alloc
18264 Allocation Root # 2
18265 -------------------
18266  Number of non freed allocations    :   1
18267  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18268  High Water Mark                    :  10.02 Kilobytes
18269  Backtrace                          :
18270    s-secsta.adb:81 system.secondary_stack.ss_init
18272 Allocation Root # 3
18273 -------------------
18274  Number of non freed allocations    :   1
18275  Final Water Mark (non freed mem)   :  12 Bytes
18276  High Water Mark                    :  12 Bytes
18277  Backtrace                          :
18278    s-secsta.adb:181 system.secondary_stack.ss_init
18279 @end smallexample
18281 @noindent
18282 Note that the GNAT run time contains itself a certain number of
18283 allocations that have no  corresponding deallocation,
18284 as shown here for root #2 and root
18285 #3. This is a normal behavior when the number of non freed allocations
18286 is one, it allocates dynamic data structures that the run time needs for
18287 the complete lifetime of the program. Note also that there is only one
18288 allocation root in the user program with a single line back trace:
18289 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18290 program shows that 'My_Alloc' is called at 2 different points in the
18291 source (line 21 and line 24). If those two allocation roots need to be
18292 distinguished, the backtrace depth parameter can be used:
18294 @smallexample
18295 $ gnatmem 3 test_gm
18296 @end smallexample
18298 @noindent
18299 which will give the following output:
18301 @smallexample
18302 Global information
18303 ------------------
18304    Total number of allocations        :  18
18305    Total number of deallocations      :   5
18306    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18307    High Water Mark                    :  56.90 Kilobytes
18309 Allocation Root # 1
18310 -------------------
18311  Number of non freed allocations    :  10
18312  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18313  High Water Mark                    :  42.97 Kilobytes
18314  Backtrace                          :
18315    test_gm.adb:11 test_gm.my_alloc
18316    test_gm.adb:24 test_gm
18317    b_test_gm.c:52 main
18319 Allocation Root # 2
18320 -------------------
18321  Number of non freed allocations    :   1
18322  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18323  High Water Mark                    :  10.02 Kilobytes
18324  Backtrace                          :
18325    s-secsta.adb:81  system.secondary_stack.ss_init
18326    s-secsta.adb:283 <system__secondary_stack___elabb>
18327    b_test_gm.c:33   adainit
18329 Allocation Root # 3
18330 -------------------
18331  Number of non freed allocations    :   1
18332  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18333  High Water Mark                    :   3.91 Kilobytes
18334  Backtrace                          :
18335    test_gm.adb:11 test_gm.my_alloc
18336    test_gm.adb:21 test_gm
18337    b_test_gm.c:52 main
18339 Allocation Root # 4
18340 -------------------
18341  Number of non freed allocations    :   1
18342  Final Water Mark (non freed mem)   :  12 Bytes
18343  High Water Mark                    :  12 Bytes
18344  Backtrace                          :
18345    s-secsta.adb:181 system.secondary_stack.ss_init
18346    s-secsta.adb:283 <system__secondary_stack___elabb>
18347    b_test_gm.c:33   adainit
18348 @end smallexample
18350 @noindent
18351 The allocation root #1 of the first example has been split in 2 roots #1
18352 and #3 thanks to the more precise associated backtrace.
18354 @end ifclear
18356 @node Creating Sample Bodies Using gnatstub
18357 @chapter Creating Sample Bodies Using @command{gnatstub}
18358 @findex gnatstub
18360 @noindent
18361 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18362 for library unit declarations.
18364 To create a body stub, @command{gnatstub} has to compile the library
18365 unit declaration. Therefore, bodies can be created only for legal
18366 library units. Moreover, if a library unit depends semantically upon
18367 units located outside the current directory, you have to provide
18368 the source search path when calling @command{gnatstub}, see the description
18369 of @command{gnatstub} switches below.
18371 @menu
18372 * Running gnatstub::
18373 * Switches for gnatstub::
18374 @end menu
18376 @node Running gnatstub
18377 @section Running @command{gnatstub}
18379 @noindent
18380 @command{gnatstub} has the command-line interface of the form
18382 @smallexample
18383 $ gnatstub [switches] filename [directory]
18384 @end smallexample
18386 @noindent
18387 where
18388 @table @emph
18389 @item filename
18390 is the name of the source file that contains a library unit declaration
18391 for which a body must be created. The file name may contain the path
18392 information.
18393 The file name does not have to follow the GNAT file name conventions. If the
18394 name
18395 does not follow GNAT file naming conventions, the name of the body file must
18396 be provided
18397 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18398 If the file name follows the GNAT file naming
18399 conventions and the name of the body file is not provided,
18400 @command{gnatstub}
18401 creates the name
18402 of the body file from the argument file name by replacing the @file{.ads}
18403 suffix
18404 with the @file{.adb} suffix.
18406 @item directory
18407 indicates the directory in which the body stub is to be placed (the default
18408 is the
18409 current directory)
18411 @item switches
18412 is an optional sequence of switches as described in the next section
18413 @end table
18415 @node Switches for gnatstub
18416 @section Switches for @command{gnatstub}
18418 @table @option
18419 @c !sort!
18421 @item ^-f^/FULL^
18422 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18423 If the destination directory already contains a file with the name of the
18424 body file
18425 for the argument spec file, replace it with the generated body stub.
18427 @item ^-hs^/HEADER=SPEC^
18428 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18429 Put the comment header (i.e., all the comments preceding the
18430 compilation unit) from the source of the library unit declaration
18431 into the body stub.
18433 @item ^-hg^/HEADER=GENERAL^
18434 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18435 Put a sample comment header into the body stub.
18437 @ifclear vms
18438 @item -IDIR
18439 @cindex @option{-IDIR} (@command{gnatstub})
18440 @itemx -I-
18441 @cindex @option{-I-} (@command{gnatstub})
18442 @end ifclear
18443 @ifset vms
18444 @item /NOCURRENT_DIRECTORY
18445 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18446 @end ifset
18447 ^These switches have ^This switch has^ the same meaning as in calls to
18448 @command{gcc}.
18449 ^They define ^It defines ^ the source search path in the call to
18450 @command{gcc} issued
18451 by @command{gnatstub} to compile an argument source file.
18453 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18454 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18455 This switch has the same meaning as in calls to @command{gcc}.
18456 It defines the additional configuration file to be passed to the call to
18457 @command{gcc} issued
18458 by @command{gnatstub} to compile an argument source file.
18460 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18461 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18462 (@var{n} is a non-negative integer). Set the maximum line length in the
18463 body stub to @var{n}; the default is 79. The maximum value that can be
18464 specified is 32767. Note that in the special case of configuration
18465 pragma files, the maximum is always 32767 regardless of whether or
18466 not this switch appears.
18468 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18469 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18470 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18471 the generated body sample to @var{n}.
18472 The default indentation is 3.
18474 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18475 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18476 Order local bodies alphabetically. (By default local bodies are ordered
18477 in the same way as the corresponding local specs in the argument spec file.)
18479 @item ^-i^/INDENTATION=^@var{n}
18480 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18481 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18483 @item ^-k^/TREE_FILE=SAVE^
18484 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18485 Do not remove the tree file (i.e., the snapshot of the compiler internal
18486 structures used by @command{gnatstub}) after creating the body stub.
18488 @item ^-l^/LINE_LENGTH=^@var{n}
18489 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18490 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18492 @item ^-o^/BODY=^@var{body-name}
18493 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18494 Body file name.  This should be set if the argument file name does not
18495 follow
18496 the GNAT file naming
18497 conventions. If this switch is omitted the default name for the body will be
18498 obtained
18499 from the argument file name according to the GNAT file naming conventions.
18501 @item ^-q^/QUIET^
18502 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18503 Quiet mode: do not generate a confirmation when a body is
18504 successfully created, and do not generate a message when a body is not
18505 required for an
18506 argument unit.
18508 @item ^-r^/TREE_FILE=REUSE^
18509 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18510 Reuse the tree file (if it exists) instead of creating it.  Instead of
18511 creating the tree file for the library unit declaration, @command{gnatstub}
18512 tries to find it in the current directory and use it for creating
18513 a body. If the tree file is not found, no body is created. This option
18514 also implies @option{^-k^/SAVE^}, whether or not
18515 the latter is set explicitly.
18517 @item ^-t^/TREE_FILE=OVERWRITE^
18518 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18519 Overwrite the existing tree file.  If the current directory already
18520 contains the file which, according to the GNAT file naming rules should
18521 be considered as a tree file for the argument source file,
18522 @command{gnatstub}
18523 will refuse to create the tree file needed to create a sample body
18524 unless this option is set.
18526 @item ^-v^/VERBOSE^
18527 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18528 Verbose mode: generate version information.
18530 @end table
18532 @node Other Utility Programs
18533 @chapter Other Utility Programs
18535 @noindent
18536 This chapter discusses some other utility programs available in the Ada
18537 environment.
18539 @menu
18540 * Using Other Utility Programs with GNAT::
18541 * The External Symbol Naming Scheme of GNAT::
18542 @ifclear vms
18543 * Ada Mode for Glide::
18544 @end ifclear
18545 * Converting Ada Files to html with gnathtml::
18546 * Installing gnathtml::
18547 @ifset vms
18548 * LSE::
18549 * Profiling::
18550 @end ifset
18551 @end menu
18553 @node Using Other Utility Programs with GNAT
18554 @section Using Other Utility Programs with GNAT
18556 @noindent
18557 The object files generated by GNAT are in standard system format and in
18558 particular the debugging information uses this format. This means
18559 programs generated by GNAT can be used with existing utilities that
18560 depend on these formats.
18562 @ifclear vms
18563 In general, any utility program that works with C will also often work with
18564 Ada programs generated by GNAT. This includes software utilities such as
18565 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18566 as Purify.
18567 @end ifclear
18569 @node The External Symbol Naming Scheme of GNAT
18570 @section The External Symbol Naming Scheme of GNAT
18572 @noindent
18573 In order to interpret the output from GNAT, when using tools that are
18574 originally intended for use with other languages, it is useful to
18575 understand the conventions used to generate link names from the Ada
18576 entity names.
18578 All link names are in all lowercase letters. With the exception of library
18579 procedure names, the mechanism used is simply to use the full expanded
18580 Ada name with dots replaced by double underscores. For example, suppose
18581 we have the following package spec:
18583 @smallexample @c ada
18584 @group
18585 @cartouche
18586 package QRS is
18587    MN : Integer;
18588 end QRS;
18589 @end cartouche
18590 @end group
18591 @end smallexample
18593 @noindent
18594 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18595 the corresponding link name is @code{qrs__mn}.
18596 @findex Export
18597 Of course if a @code{pragma Export} is used this may be overridden:
18599 @smallexample @c ada
18600 @group
18601 @cartouche
18602 package Exports is
18603    Var1 : Integer;
18604    pragma Export (Var1, C, External_Name => "var1_name");
18605    Var2 : Integer;
18606    pragma Export (Var2, C, Link_Name => "var2_link_name");
18607 end Exports;
18608 @end cartouche
18609 @end group
18610 @end smallexample
18612 @noindent
18613 In this case, the link name for @var{Var1} is whatever link name the
18614 C compiler would assign for the C function @var{var1_name}. This typically
18615 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18616 system conventions, but other possibilities exist. The link name for
18617 @var{Var2} is @var{var2_link_name}, and this is not operating system
18618 dependent.
18620 @findex _main
18621 One exception occurs for library level procedures. A potential ambiguity
18622 arises between the required name @code{_main} for the C main program,
18623 and the name we would otherwise assign to an Ada library level procedure
18624 called @code{Main} (which might well not be the main program).
18626 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18627 names. So if we have a library level procedure such as
18629 @smallexample @c ada
18630 @group
18631 @cartouche
18632 procedure Hello (S : String);
18633 @end cartouche
18634 @end group
18635 @end smallexample
18637 @noindent
18638 the external name of this procedure will be @var{_ada_hello}.
18640 @ifclear vms
18641 @node Ada Mode for Glide
18642 @section Ada Mode for @code{Glide}
18643 @cindex Ada mode (for Glide)
18645 @noindent
18646 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
18647 user to understand and navigate existing code, and facilitates writing
18648 new code. It furthermore provides some utility functions for easier
18649 integration of standard Emacs features when programming in Ada.
18651 Its general features include:
18653 @itemize @bullet
18654 @item
18655 An Integrated Development Environment with functionality such as the
18656 following
18658 @itemize @bullet
18659 @item
18660 ``Project files'' for configuration-specific aspects
18661 (e.g. directories and compilation options)
18663 @item
18664 Compiling and stepping through error messages.
18666 @item
18667 Running and debugging an applications within Glide.
18668 @end itemize
18670 @item
18671 Pull-down menus
18673 @item
18674 User configurability
18675 @end itemize
18677 Some of the specific Ada mode features are:
18679 @itemize @bullet
18680 @item
18681 Functions for easy and quick stepping through Ada code
18683 @item
18684 Getting cross reference information for identifiers (e.g., finding a
18685 defining occurrence)
18687 @item
18688 Displaying an index menu of types and subprograms, allowing
18689 direct selection for browsing
18691 @item
18692 Automatic color highlighting of the various Ada entities
18693 @end itemize
18695 Glide directly supports writing Ada code, via several facilities:
18697 @itemize @bullet
18698 @item
18699 Switching between spec and body files with possible
18700 autogeneration of body files
18702 @item
18703 Automatic formating of subprogram parameter lists
18705 @item
18706 Automatic indentation according to Ada syntax
18708 @item
18709 Automatic completion of identifiers
18711 @item
18712 Automatic (and configurable) casing of identifiers, keywords, and attributes
18714 @item
18715 Insertion of syntactic templates
18717 @item
18718 Block commenting / uncommenting
18719 @end itemize
18721 @noindent
18722 For more information, please refer to the online documentation
18723 available in the @code{Glide} @result{} @code{Help} menu.
18724 @end ifclear
18726 @node Converting Ada Files to html with gnathtml
18727 @section Converting Ada Files to HTML with @code{gnathtml}
18729 @noindent
18730 This @code{Perl} script allows Ada source files to be browsed using
18731 standard Web browsers. For installation procedure, see the section
18732 @xref{Installing gnathtml}.
18734 Ada reserved keywords are highlighted in a bold font and Ada comments in
18735 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18736 switch to suppress the generation of cross-referencing information, user
18737 defined variables and types will appear in a different color; you will
18738 be able to click on any identifier and go to its declaration.
18740 The command line is as follow:
18741 @smallexample
18742 $ perl gnathtml.pl [switches] ada-files
18743 @end smallexample
18745 @noindent
18746 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18747 an html file for every ada file, and a global file called @file{index.htm}.
18748 This file is an index of every identifier defined in the files.
18750 The available switches are the following ones :
18752 @table @option
18753 @item -83
18754 @cindex @option{-83} (@code{gnathtml})
18755 Only the subset on the Ada 83 keywords will be highlighted, not the full
18756 Ada 95 keywords set.
18758 @item -cc @var{color}
18759 @cindex @option{-cc} (@code{gnathtml})
18760 This option allows you to change the color used for comments. The default
18761 value is green. The color argument can be any name accepted by html.
18763 @item -d
18764 @cindex @option{-d} (@code{gnathtml})
18765 If the ada files depend on some other files (using for instance the
18766 @code{with} command, the latter will also be converted to html.
18767 Only the files in the user project will be converted to html, not the files
18768 in the run-time library itself.
18770 @item -D
18771 @cindex @option{-D} (@code{gnathtml})
18772 This command is the same as @option{-d} above, but @command{gnathtml} will
18773 also look for files in the run-time library, and generate html files for them.
18775 @item -ext @var{extension}
18776 @cindex @option{-ext} (@code{gnathtml})
18777 This option allows you to change the extension of the generated HTML files.
18778 If you do not specify an extension, it will default to @file{htm}.
18780 @item -f
18781 @cindex @option{-f} (@code{gnathtml})
18782 By default, gnathtml will generate html links only for global entities
18783 ('with'ed units, global variables and types,...). If you specify the
18784 @option{-f} on the command line, then links will be generated for local
18785 entities too.
18787 @item -l @var{number}
18788 @cindex @option{-l} (@code{gnathtml})
18789 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
18790 will number the html files every @var{number} line.
18792 @item -I @var{dir}
18793 @cindex @option{-I} (@code{gnathtml})
18794 Specify a directory to search for library files (@file{.ALI} files) and
18795 source files. You can provide several -I switches on the command line,
18796 and the directories will be parsed in the order of the command line.
18798 @item -o @var{dir}
18799 @cindex @option{-o} (@code{gnathtml})
18800 Specify the output directory for html files. By default, gnathtml will
18801 saved the generated html files in a subdirectory named @file{html/}.
18803 @item -p @var{file}
18804 @cindex @option{-p} (@code{gnathtml})
18805 If you are using Emacs and the most recent Emacs Ada mode, which provides
18806 a full Integrated Development Environment for compiling, checking,
18807 running and debugging applications, you may use @file{.gpr} files
18808 to give the directories where Emacs can find sources and object files.
18810 Using this switch, you can tell gnathtml to use these files. This allows
18811 you to get an html version of your application, even if it is spread
18812 over multiple directories.
18814 @item -sc @var{color}
18815 @cindex @option{-sc} (@code{gnathtml})
18816 This option allows you to change the color used for symbol definitions.
18817 The default value is red. The color argument can be any name accepted by html.
18819 @item -t @var{file}
18820 @cindex @option{-t} (@code{gnathtml})
18821 This switch provides the name of a file. This file contains a list of
18822 file names to be converted, and the effect is exactly as though they had
18823 appeared explicitly on the command line. This
18824 is the recommended way to work around the command line length limit on some
18825 systems.
18827 @end table
18829 @node Installing gnathtml
18830 @section Installing @code{gnathtml}
18832 @noindent
18833 @code{Perl} needs to be installed on your machine to run this script.
18834 @code{Perl} is freely available for almost every architecture and
18835 Operating System via the Internet.
18837 On Unix systems, you  may want to modify  the  first line of  the script
18838 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18839 is. The syntax of this line is :
18840 @smallexample
18841 #!full_path_name_to_perl
18842 @end smallexample
18844 @noindent
18845 Alternatively, you may run the script using the following command line:
18847 @smallexample
18848 $ perl gnathtml.pl [switches] files
18849 @end smallexample
18851 @ifset vms
18852 @node LSE
18853 @section LSE
18854 @findex LSE
18856 @noindent
18857 The GNAT distribution provides an Ada 95 template for the Digital Language
18858 Sensitive Editor (LSE), a component of DECset. In order to
18859 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18861 @node Profiling
18862 @section Profiling
18863 @findex PCA
18865 @noindent
18866 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
18867 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18868 the collection phase with the /DEBUG qualifier.
18870 @smallexample
18871 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18872 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18873 $ RUN/DEBUG <PROGRAM_NAME>
18874 @end smallexample
18875 @noindent
18876 @end ifset
18878 @node Running and Debugging Ada Programs
18879 @chapter Running and Debugging Ada Programs
18880 @cindex Debugging
18882 @noindent
18883 This chapter discusses how to debug Ada programs.
18884 @ifset vms
18885 It applies to the Alpha OpenVMS platform;
18886 the debugger for Integrity OpenVMS is scheduled for a subsequent release.
18887 @end ifset
18889 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18891 @enumerate
18892 @item
18893 The illegality may be a violation of the static semantics of Ada. In
18894 that case GNAT diagnoses the constructs in the program that are illegal.
18895 It is then a straightforward matter for the user to modify those parts of
18896 the program.
18898 @item
18899 The illegality may be a violation of the dynamic semantics of Ada. In
18900 that case the program compiles and executes, but may generate incorrect
18901 results, or may terminate abnormally with some exception.
18903 @item
18904 When presented with a program that contains convoluted errors, GNAT
18905 itself may terminate abnormally without providing full diagnostics on
18906 the incorrect user program.
18907 @end enumerate
18909 @menu
18910 * The GNAT Debugger GDB::
18911 * Running GDB::
18912 * Introduction to GDB Commands::
18913 * Using Ada Expressions::
18914 * Calling User-Defined Subprograms::
18915 * Using the Next Command in a Function::
18916 * Ada Exceptions::
18917 * Ada Tasks::
18918 * Debugging Generic Units::
18919 * GNAT Abnormal Termination or Failure to Terminate::
18920 * Naming Conventions for GNAT Source Files::
18921 * Getting Internal Debugging Information::
18922 * Stack Traceback::
18923 @end menu
18925 @cindex Debugger
18926 @findex gdb
18928 @node The GNAT Debugger GDB
18929 @section The GNAT Debugger GDB
18931 @noindent
18932 @code{GDB} is a general purpose, platform-independent debugger that
18933 can be used to debug mixed-language programs compiled with @code{GCC},
18934 and in particular is capable of debugging Ada programs compiled with
18935 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18936 complex Ada data structures.
18938 The manual @cite{Debugging with GDB}
18939 @ifset vms
18940 , located in the GNU:[DOCS] directory,
18941 @end ifset
18942 contains full details on the usage of @code{GDB}, including a section on
18943 its usage on programs. This manual should be consulted for full
18944 details. The section that follows is a brief introduction to the
18945 philosophy and use of @code{GDB}.
18947 When GNAT programs are compiled, the compiler optionally writes debugging
18948 information into the generated object file, including information on
18949 line numbers, and on declared types and variables. This information is
18950 separate from the generated code. It makes the object files considerably
18951 larger, but it does not add to the size of the actual executable that
18952 will be loaded into memory, and has no impact on run-time performance. The
18953 generation of debug information is triggered by the use of the
18954 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
18955 the compilations. It is important to emphasize that the use of these
18956 options does not change the generated code.
18958 The debugging information is written in standard system formats that
18959 are used by many tools, including debuggers and profilers. The format
18960 of the information is typically designed to describe C types and
18961 semantics, but GNAT implements a translation scheme which allows full
18962 details about Ada types and variables to be encoded into these
18963 standard C formats. Details of this encoding scheme may be found in
18964 the file exp_dbug.ads in the GNAT source distribution. However, the
18965 details of this encoding are, in general, of no interest to a user,
18966 since @code{GDB} automatically performs the necessary decoding.
18968 When a program is bound and linked, the debugging information is
18969 collected from the object files, and stored in the executable image of
18970 the program. Again, this process significantly increases the size of
18971 the generated executable file, but it does not increase the size of
18972 the executable program itself. Furthermore, if this program is run in
18973 the normal manner, it runs exactly as if the debug information were
18974 not present, and takes no more actual memory.
18976 However, if the program is run under control of @code{GDB}, the
18977 debugger is activated.  The image of the program is loaded, at which
18978 point it is ready to run.  If a run command is given, then the program
18979 will run exactly as it would have if @code{GDB} were not present. This
18980 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18981 entirely non-intrusive until a breakpoint is encountered.  If no
18982 breakpoint is ever hit, the program will run exactly as it would if no
18983 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18984 the debugging information and can respond to user commands to inspect
18985 variables, and more generally to report on the state of execution.
18987 @c **************
18988 @node Running GDB
18989 @section Running GDB
18991 @noindent
18992 The debugger can be launched directly and simply from @code{glide} or
18993 through its graphical interface: @code{gvd}. It can also be used
18994 directly in text mode. Here is described the basic use of @code{GDB}
18995 in text mode. All the commands described below can be used in the
18996 @code{gvd} console window even though there is usually other more
18997 graphical ways to achieve the same goals.
18999 @ifclear vms
19000 @noindent
19001 The command to run the graphical interface of the debugger is
19002 @smallexample
19003 $ gvd program
19004 @end smallexample
19005 @end ifclear
19007 @noindent
19008 The command to run @code{GDB} in text mode is
19010 @smallexample
19011 $ ^gdb program^$ GDB PROGRAM^
19012 @end smallexample
19014 @noindent
19015 where @code{^program^PROGRAM^} is the name of the executable file. This
19016 activates the debugger and results in a prompt for debugger commands.
19017 The simplest command is simply @code{run}, which causes the program to run
19018 exactly as if the debugger were not present. The following section
19019 describes some of the additional commands that can be given to @code{GDB}.
19021 @c *******************************
19022 @node Introduction to GDB Commands
19023 @section Introduction to GDB Commands
19025 @noindent
19026 @code{GDB} contains a large repertoire of commands. The manual
19027 @cite{Debugging with GDB}
19028 @ifset vms
19029 , located in the GNU:[DOCS] directory,
19030 @end ifset
19031 includes extensive documentation on the use
19032 of these commands, together with examples of their use. Furthermore,
19033 the command @var{help} invoked from within @code{GDB} activates a simple help
19034 facility which summarizes the available commands and their options.
19035 In this section we summarize a few of the most commonly
19036 used commands to give an idea of what @code{GDB} is about. You should create
19037 a simple program with debugging information and experiment with the use of
19038 these @code{GDB} commands on the program as you read through the
19039 following section.
19041 @table @code
19042 @item set args @var{arguments}
19043 The @var{arguments} list above is a list of arguments to be passed to
19044 the program on a subsequent run command, just as though the arguments
19045 had been entered on a normal invocation of the program. The @code{set args}
19046 command is not needed if the program does not require arguments.
19048 @item run
19049 The @code{run} command causes execution of the program to start from
19050 the beginning. If the program is already running, that is to say if
19051 you are currently positioned at a breakpoint, then a prompt will ask
19052 for confirmation that you want to abandon the current execution and
19053 restart.
19055 @item breakpoint @var{location}
19056 The breakpoint command sets a breakpoint, that is to say a point at which
19057 execution will halt and @code{GDB} will await further
19058 commands. @var{location} is
19059 either a line number within a file, given in the format @code{file:linenumber},
19060 or it is the name of a subprogram. If you request that a breakpoint be set on
19061 a subprogram that is overloaded, a prompt will ask you to specify on which of
19062 those subprograms you want to breakpoint. You can also
19063 specify that all of them should be breakpointed. If the program is run
19064 and execution encounters the breakpoint, then the program
19065 stops and @code{GDB} signals that the breakpoint was encountered by
19066 printing the line of code before which the program is halted.
19068 @item breakpoint exception @var{name}
19069 A special form of the breakpoint command which breakpoints whenever
19070 exception @var{name} is raised.
19071 If @var{name} is omitted,
19072 then a breakpoint will occur when any exception is raised.
19074 @item print @var{expression}
19075 This will print the value of the given expression. Most simple
19076 Ada expression formats are properly handled by @code{GDB}, so the expression
19077 can contain function calls, variables, operators, and attribute references.
19079 @item continue
19080 Continues execution following a breakpoint, until the next breakpoint or the
19081 termination of the program.
19083 @item step
19084 Executes a single line after a breakpoint. If the next statement
19085 is a subprogram call, execution continues into (the first statement of)
19086 the called subprogram.
19088 @item next
19089 Executes a single line. If this line is a subprogram call, executes and
19090 returns from the call.
19092 @item list
19093 Lists a few lines around the current source location. In practice, it
19094 is usually more convenient to have a separate edit window open with the
19095 relevant source file displayed. Successive applications of this command
19096 print subsequent lines. The command can be given an argument which is a
19097 line number, in which case it displays a few lines around the specified one.
19099 @item backtrace
19100 Displays a backtrace of the call chain. This command is typically
19101 used after a breakpoint has occurred, to examine the sequence of calls that
19102 leads to the current breakpoint. The display includes one line for each
19103 activation record (frame) corresponding to an active subprogram.
19105 @item up
19106 At a breakpoint, @code{GDB} can display the values of variables local
19107 to the current frame. The command @code{up} can be used to
19108 examine the contents of other active frames, by moving the focus up
19109 the stack, that is to say from callee to caller, one frame at a time.
19111 @item down
19112 Moves the focus of @code{GDB} down from the frame currently being
19113 examined to the frame of its callee (the reverse of the previous command),
19115 @item frame @var{n}
19116 Inspect the frame with the given number. The value 0 denotes the frame
19117 of the current breakpoint, that is to say the top of the call stack.
19119 @end table
19121 The above list is a very short introduction to the commands that
19122 @code{GDB} provides. Important additional capabilities, including conditional
19123 breakpoints, the ability to execute command sequences on a breakpoint,
19124 the ability to debug at the machine instruction level and many other
19125 features are described in detail in @cite{Debugging with GDB}.
19126 Note that most commands can be abbreviated
19127 (for example, c for continue, bt for backtrace).
19129 @node Using Ada Expressions
19130 @section Using Ada Expressions
19131 @cindex Ada expressions
19133 @noindent
19134 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19135 extensions. The philosophy behind the design of this subset is
19137 @itemize @bullet
19138 @item
19139 That @code{GDB} should provide basic literals and access to operations for
19140 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19141 leaving more sophisticated computations to subprograms written into the
19142 program (which therefore may be called from @code{GDB}).
19144 @item
19145 That type safety and strict adherence to Ada language restrictions
19146 are not particularly important to the @code{GDB} user.
19148 @item
19149 That brevity is important to the @code{GDB} user.
19150 @end itemize
19152 Thus, for brevity, the debugger acts as if there were
19153 implicit @code{with} and @code{use} clauses in effect for all user-written
19154 packages, thus making it unnecessary to fully qualify most names with
19155 their packages, regardless of context. Where this causes ambiguity,
19156 @code{GDB} asks the user's intent.
19158 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19160 @node Calling User-Defined Subprograms
19161 @section Calling User-Defined Subprograms
19163 @noindent
19164 An important capability of @code{GDB} is the ability to call user-defined
19165 subprograms while debugging. This is achieved simply by entering
19166 a subprogram call statement in the form:
19168 @smallexample
19169 call subprogram-name (parameters)
19170 @end smallexample
19172 @noindent
19173 The keyword @code{call} can be omitted in the normal case where the
19174 @code{subprogram-name} does not coincide with any of the predefined
19175 @code{GDB} commands.
19177 The effect is to invoke the given subprogram, passing it the
19178 list of parameters that is supplied. The parameters can be expressions and
19179 can include variables from the program being debugged. The
19180 subprogram must be defined
19181 at the library level within your program, and @code{GDB} will call the
19182 subprogram within the environment of your program execution (which
19183 means that the subprogram is free to access or even modify variables
19184 within your program).
19186 The most important use of this facility is in allowing the inclusion of
19187 debugging routines that are tailored to particular data structures
19188 in your program. Such debugging routines can be written to provide a suitably
19189 high-level description of an abstract type, rather than a low-level dump
19190 of its physical layout. After all, the standard
19191 @code{GDB print} command only knows the physical layout of your
19192 types, not their abstract meaning. Debugging routines can provide information
19193 at the desired semantic level and are thus enormously useful.
19195 For example, when debugging GNAT itself, it is crucial to have access to
19196 the contents of the tree nodes used to represent the program internally.
19197 But tree nodes are represented simply by an integer value (which in turn
19198 is an index into a table of nodes).
19199 Using the @code{print} command on a tree node would simply print this integer
19200 value, which is not very useful. But the PN routine (defined in file
19201 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19202 a useful high level representation of the tree node, which includes the
19203 syntactic category of the node, its position in the source, the integers
19204 that denote descendant nodes and parent node, as well as varied
19205 semantic information. To study this example in more detail, you might want to
19206 look at the body of the PN procedure in the stated file.
19208 @node Using the Next Command in a Function
19209 @section Using the Next Command in a Function
19211 @noindent
19212 When you use the @code{next} command in a function, the current source
19213 location will advance to the next statement as usual. A special case
19214 arises in the case of a @code{return} statement.
19216 Part of the code for a return statement is the ``epilog'' of the function.
19217 This is the code that returns to the caller. There is only one copy of
19218 this epilog code, and it is typically associated with the last return
19219 statement in the function if there is more than one return. In some
19220 implementations, this epilog is associated with the first statement
19221 of the function.
19223 The result is that if you use the @code{next} command from a return
19224 statement that is not the last return statement of the function you
19225 may see a strange apparent jump to the last return statement or to
19226 the start of the function. You should simply ignore this odd jump.
19227 The value returned is always that from the first return statement
19228 that was stepped through.
19230 @node Ada Exceptions
19231 @section Breaking on Ada Exceptions
19232 @cindex Exceptions
19234 @noindent
19235 You can set breakpoints that trip when your program raises
19236 selected exceptions.
19238 @table @code
19239 @item break exception
19240 Set a breakpoint that trips whenever (any task in the) program raises
19241 any exception.
19243 @item break exception @var{name}
19244 Set a breakpoint that trips whenever (any task in the) program raises
19245 the exception @var{name}.
19247 @item break exception unhandled
19248 Set a breakpoint that trips whenever (any task in the) program raises an
19249 exception for which there is no handler.
19251 @item info exceptions
19252 @itemx info exceptions @var{regexp}
19253 The @code{info exceptions} command permits the user to examine all defined
19254 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19255 argument, prints out only those exceptions whose name matches @var{regexp}.
19256 @end table
19258 @node Ada Tasks
19259 @section Ada Tasks
19260 @cindex Tasks
19262 @noindent
19263 @code{GDB} allows the following task-related commands:
19265 @table @code
19266 @item info tasks
19267 This command shows a list of current Ada tasks, as in the following example:
19269 @smallexample
19270 @iftex
19271 @leftskip=0cm
19272 @end iftex
19273 (gdb) info tasks
19274   ID       TID P-ID   Thread Pri State                 Name
19275    1   8088000   0   807e000  15 Child Activation Wait main_task
19276    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19277    3   809a800   1   80a4800  15 Child Activation Wait a
19278 *  4   80ae800   3   80b8000  15 Running               c
19279 @end smallexample
19281 @noindent
19282 In this listing, the asterisk before the first task indicates it to be the
19283 currently running task. The first column lists the task ID that is used
19284 to refer to tasks in the following commands.
19286 @item break @var{linespec} task @var{taskid}
19287 @itemx break @var{linespec} task @var{taskid} if @dots{}
19288 @cindex Breakpoints and tasks
19289 These commands are like the @code{break @dots{} thread @dots{}}.
19290 @var{linespec} specifies source lines.
19292 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19293 to specify that you only want @code{GDB} to stop the program when a
19294 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19295 numeric task identifiers assigned by @code{GDB}, shown in the first
19296 column of the @samp{info tasks} display.
19298 If you do not specify @samp{task @var{taskid}} when you set a
19299 breakpoint, the breakpoint applies to @emph{all} tasks of your
19300 program.
19302 You can use the @code{task} qualifier on conditional breakpoints as
19303 well; in this case, place @samp{task @var{taskid}} before the
19304 breakpoint condition (before the @code{if}).
19306 @item task @var{taskno}
19307 @cindex Task switching
19309 This command allows to switch to the task referred by @var{taskno}. In
19310 particular, This allows to browse the backtrace of the specified
19311 task. It is advised to switch back to the original task before
19312 continuing execution otherwise the scheduling of the program may be
19313 perturbated.
19314 @end table
19316 @noindent
19317 For more detailed information on the tasking support,
19318 see @cite{Debugging with GDB}.
19320 @node Debugging Generic Units
19321 @section Debugging Generic Units
19322 @cindex Debugging Generic Units
19323 @cindex Generics
19325 @noindent
19326 GNAT always uses code expansion for generic instantiation. This means that
19327 each time an instantiation occurs, a complete copy of the original code is
19328 made, with appropriate substitutions of formals by actuals.
19330 It is not possible to refer to the original generic entities in
19331 @code{GDB}, but it is always possible to debug a particular instance of
19332 a generic, by using the appropriate expanded names. For example, if we have
19334 @smallexample @c ada
19335 @group
19336 @cartouche
19337 procedure g is
19339    generic package k is
19340       procedure kp (v1 : in out integer);
19341    end k;
19343    package body k is
19344       procedure kp (v1 : in out integer) is
19345       begin
19346          v1 := v1 + 1;
19347       end kp;
19348    end k;
19350    package k1 is new k;
19351    package k2 is new k;
19353    var : integer := 1;
19355 begin
19356    k1.kp (var);
19357    k2.kp (var);
19358    k1.kp (var);
19359    k2.kp (var);
19360 end;
19361 @end cartouche
19362 @end group
19363 @end smallexample
19365 @noindent
19366 Then to break on a call to procedure kp in the k2 instance, simply
19367 use the command:
19369 @smallexample
19370 (gdb) break g.k2.kp
19371 @end smallexample
19373 @noindent
19374 When the breakpoint occurs, you can step through the code of the
19375 instance in the normal manner and examine the values of local variables, as for
19376 other units.
19378 @node GNAT Abnormal Termination or Failure to Terminate
19379 @section GNAT Abnormal Termination or Failure to Terminate
19380 @cindex GNAT Abnormal Termination or Failure to Terminate
19382 @noindent
19383 When presented with programs that contain serious errors in syntax
19384 or semantics,
19385 GNAT may on rare occasions  experience problems in operation, such
19386 as aborting with a
19387 segmentation fault or illegal memory access, raising an internal
19388 exception, terminating abnormally, or failing to terminate at all.
19389 In such cases, you can activate
19390 various features of GNAT that can help you pinpoint the construct in your
19391 program that is the likely source of the problem.
19393 The following strategies are presented in increasing order of
19394 difficulty, corresponding to your experience in using GNAT and your
19395 familiarity with compiler internals.
19397 @enumerate
19398 @item
19399 Run @code{gcc} with the @option{-gnatf}. This first
19400 switch causes all errors on a given line to be reported. In its absence,
19401 only the first error on a line is displayed.
19403 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19404 are encountered, rather than after compilation is terminated. If GNAT
19405 terminates prematurely or goes into an infinite loop, the last error
19406 message displayed may help to pinpoint the culprit.
19408 @item
19409 Run @code{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this mode,
19410 @code{gcc} produces ongoing information about the progress of the
19411 compilation and provides the name of each procedure as code is
19412 generated. This switch allows you to find which Ada procedure was being
19413 compiled when it encountered a code generation problem.
19415 @item
19416 @cindex @option{-gnatdc} switch
19417 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19418 switch that does for the front-end what @option{^-v^VERBOSE^} does
19419 for the back end. The system prints the name of each unit,
19420 either a compilation unit or nested unit, as it is being analyzed.
19421 @item
19422 Finally, you can start
19423 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19424 front-end of GNAT, and can be run independently (normally it is just
19425 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
19426 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19427 @code{where} command is the first line of attack; the variable
19428 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19429 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
19430 which the execution stopped, and @code{input_file name} indicates the name of
19431 the source file.
19432 @end enumerate
19434 @node Naming Conventions for GNAT Source Files
19435 @section Naming Conventions for GNAT Source Files
19437 @noindent
19438 In order to examine the workings of the GNAT system, the following
19439 brief description of its organization may be helpful:
19441 @itemize @bullet
19442 @item
19443 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19445 @item
19446 All files prefixed with @file{^par^PAR^} are components of the parser. The
19447 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
19448 parsing of select statements can be found in @file{par-ch9.adb}.
19450 @item
19451 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19452 numbers correspond to chapters of the Ada standard. For example, all
19453 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19454 addition, some features of the language require sufficient special processing
19455 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19456 dynamic dispatching, etc.
19458 @item
19459 All files prefixed with @file{^exp^EXP^} perform normalization and
19460 expansion of the intermediate representation (abstract syntax tree, or AST).
19461 these files use the same numbering scheme as the parser and semantics files.
19462 For example, the construction of record initialization procedures is done in
19463 @file{exp_ch3.adb}.
19465 @item
19466 The files prefixed with @file{^bind^BIND^} implement the binder, which
19467 verifies the consistency of the compilation, determines an order of
19468 elaboration, and generates the bind file.
19470 @item
19471 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19472 data structures used by the front-end.
19474 @item
19475 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19476 the abstract syntax tree as produced by the parser.
19478 @item
19479 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19480 all entities, computed during semantic analysis.
19482 @item
19483 Library management issues are dealt with in files with prefix
19484 @file{^lib^LIB^}.
19486 @item
19487 @findex Ada
19488 @cindex Annex A
19489 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19490 defined in Annex A.
19492 @item
19493 @findex Interfaces
19494 @cindex Annex B
19495 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19496 defined in Annex B.
19498 @item
19499 @findex System
19500 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19501 both language-defined children and GNAT run-time routines.
19503 @item
19504 @findex GNAT
19505 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19506 general-purpose packages, fully documented in their specifications. All
19507 the other @file{.c} files are modifications of common @code{gcc} files.
19508 @end itemize
19510 @node Getting Internal Debugging Information
19511 @section Getting Internal Debugging Information
19513 @noindent
19514 Most compilers have internal debugging switches and modes. GNAT
19515 does also, except GNAT internal debugging switches and modes are not
19516 secret. A summary and full description of all the compiler and binder
19517 debug flags are in the file @file{debug.adb}. You must obtain the
19518 sources of the compiler to see the full detailed effects of these flags.
19520 The switches that print the source of the program (reconstructed from
19521 the internal tree) are of general interest for user programs, as are the
19522 options to print
19523 the full internal tree, and the entity table (the symbol table
19524 information). The reconstructed source provides a readable version of the
19525 program after the front-end has completed analysis and  expansion,
19526 and is useful when studying the performance of specific constructs.
19527 For example, constraint checks are indicated, complex aggregates
19528 are replaced with loops and assignments, and tasking primitives
19529 are replaced with run-time calls.
19531 @node Stack Traceback
19532 @section Stack Traceback
19533 @cindex traceback
19534 @cindex stack traceback
19535 @cindex stack unwinding
19537 @noindent
19538 Traceback is a mechanism to display the sequence of subprogram calls that
19539 leads to a specified execution point in a program. Often (but not always)
19540 the execution point is an instruction at which an exception has been raised.
19541 This mechanism is also known as @i{stack unwinding} because it obtains
19542 its information by scanning the run-time stack and recovering the activation
19543 records of all active subprograms. Stack unwinding is one of the most
19544 important tools for program debugging.
19546 The first entry stored in traceback corresponds to the deepest calling level,
19547 that is to say the subprogram currently executing the instruction
19548 from which we want to obtain the traceback.
19550 Note that there is no runtime performance penalty when stack traceback
19551 is enabled, and no exception is raised during program execution.
19553 @menu
19554 * Non-Symbolic Traceback::
19555 * Symbolic Traceback::
19556 @end menu
19558 @node Non-Symbolic Traceback
19559 @subsection Non-Symbolic Traceback
19560 @cindex traceback, non-symbolic
19562 @noindent
19563 Note: this feature is not supported on all platforms. See
19564 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19565 platforms.
19567 @menu
19568 * Tracebacks From an Unhandled Exception::
19569 * Tracebacks From Exception Occurrences (non-symbolic)::
19570 * Tracebacks From Anywhere in a Program (non-symbolic)::
19571 @end menu
19573 @node Tracebacks From an Unhandled Exception
19574 @subsubsection Tracebacks From an Unhandled Exception
19576 @noindent
19577 A runtime non-symbolic traceback is a list of addresses of call instructions.
19578 To enable this feature you must use the @option{-E}
19579 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19580 of exception information. You can retrieve this information using the
19581 @code{addr2line} tool.
19583 Here is a simple example:
19585 @smallexample @c ada
19586 @cartouche
19587 procedure STB is
19589    procedure P1 is
19590    begin
19591       raise Constraint_Error;
19592    end P1;
19594    procedure P2 is
19595    begin
19596       P1;
19597    end P2;
19599 begin
19600    P2;
19601 end STB;
19602 @end cartouche
19603 @end smallexample
19605 @smallexample
19606 $ gnatmake stb -bargs -E
19607 $ stb
19609 Execution terminated by unhandled exception
19610 Exception name: CONSTRAINT_ERROR
19611 Message: stb.adb:5
19612 Call stack traceback locations:
19613 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19614 @end smallexample
19616 @noindent
19617 As we see the traceback lists a sequence of addresses for the unhandled
19618 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19619 guess that this exception come from procedure P1. To translate these
19620 addresses into the source lines where the calls appear, the
19621 @code{addr2line} tool, described below, is invaluable. The use of this tool
19622 requires the program to be compiled with debug information.
19624 @smallexample
19625 $ gnatmake -g stb -bargs -E
19626 $ stb
19628 Execution terminated by unhandled exception
19629 Exception name: CONSTRAINT_ERROR
19630 Message: stb.adb:5
19631 Call stack traceback locations:
19632 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19634 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19635    0x4011f1 0x77e892a4
19637 00401373 at d:/stb/stb.adb:5
19638 0040138B at d:/stb/stb.adb:10
19639 0040139C at d:/stb/stb.adb:14
19640 00401335 at d:/stb/b~stb.adb:104
19641 004011C4 at /build/.../crt1.c:200
19642 004011F1 at /build/.../crt1.c:222
19643 77E892A4 in ?? at ??:0
19644 @end smallexample
19646 @noindent
19647 The @code{addr2line} tool has several other useful options:
19649 @table @code
19650 @item --functions
19651 to get the function name corresponding to any location
19653 @item --demangle=gnat
19654 to use the gnat decoding mode for the function names. Note that
19655 for binutils version 2.9.x the option is simply @option{--demangle}.
19656 @end table
19658 @smallexample
19659 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19660    0x40139c 0x401335 0x4011c4 0x4011f1
19662 00401373 in stb.p1 at d:/stb/stb.adb:5
19663 0040138B in stb.p2 at d:/stb/stb.adb:10
19664 0040139C in stb at d:/stb/stb.adb:14
19665 00401335 in main at d:/stb/b~stb.adb:104
19666 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19667 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19668 @end smallexample
19670 @noindent
19671 From this traceback we can see that the exception was raised in
19672 @file{stb.adb} at line 5, which was reached from a procedure call in
19673 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19674 which contains the call to the main program.
19675 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
19676 and the output will vary from platform to platform.
19678 It is also possible to use @code{GDB} with these traceback addresses to debug
19679 the program. For example, we can break at a given code location, as reported
19680 in the stack traceback:
19682 @smallexample
19683 $ gdb -nw stb
19684 @ifclear vms
19685 @noindent
19686 Furthermore, this feature is not implemented inside Windows DLL. Only
19687 the non-symbolic traceback is reported in this case.
19688 @end ifclear
19690 (gdb) break *0x401373
19691 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19692 @end smallexample
19694 @noindent
19695 It is important to note that the stack traceback addresses
19696 do not change when debug information is included. This is particularly useful
19697 because it makes it possible to release software without debug information (to
19698 minimize object size), get a field report that includes a stack traceback
19699 whenever an internal bug occurs, and then be able to retrieve the sequence
19700 of calls with the same program compiled with debug information.
19702 @node Tracebacks From Exception Occurrences (non-symbolic)
19703 @subsubsection Tracebacks From Exception Occurrences
19705 @noindent
19706 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19707 The stack traceback is attached to the exception information string, and can
19708 be retrieved in an exception handler within the Ada program, by means of the
19709 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19711 @smallexample @c ada
19712 with Ada.Text_IO;
19713 with Ada.Exceptions;
19715 procedure STB is
19717    use Ada;
19718    use Ada.Exceptions;
19720    procedure P1 is
19721       K : Positive := 1;
19722    begin
19723       K := K - 1;
19724    exception
19725       when E : others =>
19726          Text_IO.Put_Line (Exception_Information (E));
19727    end P1;
19729    procedure P2 is
19730    begin
19731       P1;
19732    end P2;
19734 begin
19735    P2;
19736 end STB;
19737 @end smallexample
19739 @noindent
19740 This program will output:
19742 @smallexample
19743 $ stb
19745 Exception name: CONSTRAINT_ERROR
19746 Message: stb.adb:12
19747 Call stack traceback locations:
19748 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19749 @end smallexample
19751 @node Tracebacks From Anywhere in a Program (non-symbolic)
19752 @subsubsection Tracebacks From Anywhere in a Program
19754 @noindent
19755 It is also possible to retrieve a stack traceback from anywhere in a
19756 program. For this you need to
19757 use the @code{GNAT.Traceback} API. This package includes a procedure called
19758 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19759 display procedures described below. It is not necessary to use the
19760 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19761 is invoked explicitly.
19763 @noindent
19764 In the following example we compute a traceback at a specific location in
19765 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19766 convert addresses to strings:
19768 @smallexample @c ada
19769 with Ada.Text_IO;
19770 with GNAT.Traceback;
19771 with GNAT.Debug_Utilities;
19773 procedure STB is
19775    use Ada;
19776    use GNAT;
19777    use GNAT.Traceback;
19779    procedure P1 is
19780       TB  : Tracebacks_Array (1 .. 10);
19781       --  We are asking for a maximum of 10 stack frames.
19782       Len : Natural;
19783       --  Len will receive the actual number of stack frames returned.
19784    begin
19785       Call_Chain (TB, Len);
19787       Text_IO.Put ("In STB.P1 : ");
19789       for K in 1 .. Len loop
19790          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19791          Text_IO.Put (' ');
19792       end loop;
19794       Text_IO.New_Line;
19795    end P1;
19797    procedure P2 is
19798    begin
19799       P1;
19800    end P2;
19802 begin
19803    P2;
19804 end STB;
19805 @end smallexample
19807 @smallexample
19808 $ gnatmake -g stb
19809 $ stb
19811 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19812 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19813 @end smallexample
19815 @noindent
19816 You can then get further information by invoking the @code{addr2line}
19817 tool as described earlier (note that the hexadecimal addresses
19818 need to be specified in C format, with a leading ``0x'').
19820 @node Symbolic Traceback
19821 @subsection Symbolic Traceback
19822 @cindex traceback, symbolic
19824 @noindent
19825 A symbolic traceback is a stack traceback in which procedure names are
19826 associated with each code location.
19828 @noindent
19829 Note that this feature is not supported on all platforms. See
19830 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19831 list of currently supported platforms.
19833 @noindent
19834 Note that the symbolic traceback requires that the program be compiled
19835 with debug information. If it is not compiled with debug information
19836 only the non-symbolic information will be valid.
19838 @menu
19839 * Tracebacks From Exception Occurrences (symbolic)::
19840 * Tracebacks From Anywhere in a Program (symbolic)::
19841 @end menu
19843 @node Tracebacks From Exception Occurrences (symbolic)
19844 @subsubsection Tracebacks From Exception Occurrences
19846 @smallexample @c ada
19847 with Ada.Text_IO;
19848 with GNAT.Traceback.Symbolic;
19850 procedure STB is
19852    procedure P1 is
19853    begin
19854       raise Constraint_Error;
19855    end P1;
19857    procedure P2 is
19858    begin
19859       P1;
19860    end P2;
19862    procedure P3 is
19863    begin
19864       P2;
19865    end P3;
19867 begin
19868    P3;
19869 exception
19870    when E : others =>
19871       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19872 end STB;
19873 @end smallexample
19875 @smallexample
19876 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19877 $ stb
19879 0040149F in stb.p1 at stb.adb:8
19880 004014B7 in stb.p2 at stb.adb:13
19881 004014CF in stb.p3 at stb.adb:18
19882 004015DD in ada.stb at stb.adb:22
19883 00401461 in main at b~stb.adb:168
19884 004011C4 in __mingw_CRTStartup at crt1.c:200
19885 004011F1 in mainCRTStartup at crt1.c:222
19886 77E892A4 in ?? at ??:0
19887 @end smallexample
19889 @noindent
19890 In the above example the ``.\'' syntax in the @command{gnatmake} command
19891 is currently required by @command{addr2line} for files that are in
19892 the current working directory.
19893 Moreover, the exact sequence of linker options may vary from platform
19894 to platform.
19895 The above @option{-largs} section is for Windows platforms. By contrast,
19896 under Unix there is no need for the @option{-largs} section.
19897 Differences across platforms are due to details of linker implementation.
19899 @node Tracebacks From Anywhere in a Program (symbolic)
19900 @subsubsection Tracebacks From Anywhere in a Program
19902 @noindent
19903 It is possible to get a symbolic stack traceback
19904 from anywhere in a program, just as for non-symbolic tracebacks.
19905 The first step is to obtain a non-symbolic
19906 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19907 information. Here is an example:
19909 @smallexample @c ada
19910 with Ada.Text_IO;
19911 with GNAT.Traceback;
19912 with GNAT.Traceback.Symbolic;
19914 procedure STB is
19916    use Ada;
19917    use GNAT.Traceback;
19918    use GNAT.Traceback.Symbolic;
19920    procedure P1 is
19921       TB  : Tracebacks_Array (1 .. 10);
19922       --  We are asking for a maximum of 10 stack frames.
19923       Len : Natural;
19924       --  Len will receive the actual number of stack frames returned.
19925    begin
19926       Call_Chain (TB, Len);
19927       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19928    end P1;
19930    procedure P2 is
19931    begin
19932       P1;
19933    end P2;
19935 begin
19936    P2;
19937 end STB;
19938 @end smallexample
19940 @ifset vms
19941 @node Compatibility with DEC Ada
19942 @chapter Compatibility with DEC Ada
19943 @cindex Compatibility
19945 @noindent
19946 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
19947 OpenVMS Alpha. GNAT achieves a high level of compatibility
19948 with DEC Ada, and it should generally be straightforward to port code
19949 from the DEC Ada environment to GNAT. However, there are a few language
19950 and implementation differences of which the user must be aware. These
19951 differences are discussed in this section. In
19952 addition, the operating environment and command structure for the
19953 compiler are different, and these differences are also discussed.
19955 Note that this discussion addresses specifically the implementation
19956 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
19957 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
19958 GNAT always follows the Alpha implementation.
19960 @menu
19961 * Ada 95 Compatibility::
19962 * Differences in the Definition of Package System::
19963 * Language-Related Features::
19964 * The Package STANDARD::
19965 * The Package SYSTEM::
19966 * Tasking and Task-Related Features::
19967 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
19968 * Pragmas and Pragma-Related Features::
19969 * Library of Predefined Units::
19970 * Bindings::
19971 * Main Program Definition::
19972 * Implementation-Defined Attributes::
19973 * Compiler and Run-Time Interfacing::
19974 * Program Compilation and Library Management::
19975 * Input-Output::
19976 * Implementation Limits::
19977 * Tools::
19978 @end menu
19980 @node Ada 95 Compatibility
19981 @section Ada 95 Compatibility
19983 @noindent
19984 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
19985 compiler. Ada 95 is almost completely upwards compatible
19986 with Ada 83, and therefore Ada 83 programs will compile
19987 and run under GNAT with
19988 no changes or only minor changes. The Ada 95 Reference
19989 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
19990 incompatibilities.
19992 GNAT provides the switch /83 on the GNAT COMPILE command,
19993 as well as the pragma ADA_83, to force the compiler to
19994 operate in Ada 83 mode. This mode does not guarantee complete
19995 conformance to Ada 83, but in practice is sufficient to
19996 eliminate most sources of incompatibilities.
19997 In particular, it eliminates the recognition of the
19998 additional Ada 95 keywords, so that their use as identifiers
19999 in Ada83 program is legal, and handles the cases of packages
20000 with optional bodies, and generics that instantiate unconstrained
20001 types without the use of @code{(<>)}.
20003 @node Differences in the Definition of Package System
20004 @section Differences in the Definition of Package System
20006 @noindent
20007 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
20008 implementation-dependent declarations to package System. In normal mode,
20009 GNAT does not take advantage of this permission, and the version of System
20010 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
20012 However, DEC Ada adds an extensive set of declarations to package System,
20013 as fully documented in the DEC Ada manuals. To minimize changes required
20014 for programs that make use of these extensions, GNAT provides the pragma
20015 Extend_System for extending the definition of package System. By using:
20017 @smallexample @c ada
20018 @group
20019 @cartouche
20020 pragma Extend_System (Aux_DEC);
20021 @end cartouche
20022 @end group
20023 @end smallexample
20025 @noindent
20026 The set of definitions in System is extended to include those in package
20027 @code{System.Aux_DEC}.
20028 These definitions are incorporated directly into package
20029 System, as though they had been declared there in the first place. For a
20030 list of the declarations added, see the specification of this package,
20031 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
20032 The pragma Extend_System is a configuration pragma, which means that
20033 it can be placed in the file @file{gnat.adc}, so that it will automatically
20034 apply to all subsequent compilations. See the section on Configuration
20035 Pragmas for further details.
20037 An alternative approach that avoids the use of the non-standard
20038 Extend_System pragma is to add a context clause to the unit that
20039 references these facilities:
20041 @smallexample @c ada
20042 @group
20043 @cartouche
20044 with System.Aux_DEC;
20045 use  System.Aux_DEC;
20046 @end cartouche
20047 @end group
20048 @end smallexample
20050 @noindent
20051 The effect is not quite semantically identical to incorporating
20052 the declarations directly into package @code{System},
20053 but most programs will not notice a difference
20054 unless they use prefix notation (e.g. @code{System.Integer_8})
20055 to reference the
20056 entities directly in package @code{System}.
20057 For units containing such references,
20058 the prefixes must either be removed, or the pragma @code{Extend_System}
20059 must be used.
20061 @node Language-Related Features
20062 @section Language-Related Features
20064 @noindent
20065 The following sections highlight differences in types,
20066 representations of types, operations, alignment, and
20067 related topics.
20069 @menu
20070 * Integer Types and Representations::
20071 * Floating-Point Types and Representations::
20072 * Pragmas Float_Representation and Long_Float::
20073 * Fixed-Point Types and Representations::
20074 * Record and Array Component Alignment::
20075 * Address Clauses::
20076 * Other Representation Clauses::
20077 @end menu
20079 @node Integer Types and Representations
20080 @subsection Integer Types and Representations
20082 @noindent
20083 The set of predefined integer types is identical in DEC Ada and GNAT.
20084 Furthermore the representation of these integer types is also identical,
20085 including the capability of size clauses forcing biased representation.
20087 In addition,
20088 DEC Ada for OpenVMS Alpha systems has defined the
20089 following additional integer types in package System:
20091 @itemize @bullet
20093 @item
20094 INTEGER_8
20096 @item
20097 INTEGER_16
20099 @item
20100 INTEGER_32
20102 @item
20103 INTEGER_64
20105 @item
20106 LARGEST_INTEGER
20107 @end itemize
20109 @noindent
20110 When using GNAT, the first four of these types may be obtained from the
20111 standard Ada 95 package @code{Interfaces}.
20112 Alternatively, by use of the pragma
20113 @code{Extend_System}, identical
20114 declarations can be referenced directly in package @code{System}.
20115 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
20117 @node Floating-Point Types and Representations
20118 @subsection Floating-Point Types and Representations
20119 @cindex Floating-Point types
20121 @noindent
20122 The set of predefined floating-point types is identical in DEC Ada and GNAT.
20123 Furthermore the representation of these floating-point
20124 types is also identical. One important difference is that the default
20125 representation for DEC Ada is VAX_Float, but the default representation
20126 for GNAT is IEEE.
20128 Specific types may be declared to be VAX_Float or IEEE, using the pragma
20129 @code{Float_Representation} as described in the DEC Ada documentation.
20130 For example, the declarations:
20132 @smallexample @c ada
20133 @group
20134 @cartouche
20135 type F_Float is digits 6;
20136 pragma Float_Representation (VAX_Float, F_Float);
20137 @end cartouche
20138 @end group
20139 @end smallexample
20141 @noindent
20142 declare a type F_Float that will be represented in VAX_Float format.
20143 This set of declarations actually appears in System.Aux_DEC, which provides
20144 the full set of additional floating-point declarations provided in
20145 the DEC Ada version of package
20146 System. This and similar declarations may be accessed in a user program
20147 by using pragma @code{Extend_System}. The use of this
20148 pragma, and the related pragma @code{Long_Float} is described in further
20149 detail in the following section.
20151 @node Pragmas Float_Representation and Long_Float
20152 @subsection Pragmas Float_Representation and Long_Float
20154 @noindent
20155 DEC Ada provides the pragma @code{Float_Representation}, which
20156 acts as a program library switch to allow control over
20157 the internal representation chosen for the predefined
20158 floating-point types declared in the package @code{Standard}.
20159 The format of this pragma is as follows:
20161 @smallexample
20162 @group
20163 @cartouche
20164 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
20165 @end cartouche
20166 @end group
20167 @end smallexample
20169 @noindent
20170 This pragma controls the representation of floating-point
20171 types as follows:
20173 @itemize @bullet
20174 @item
20175 @code{VAX_Float} specifies that floating-point
20176 types are represented by default with the VAX hardware types
20177 F-floating, D-floating, G-floating. Note that the H-floating
20178 type is available only on DIGITAL Vax systems, and is not available
20179 in either DEC Ada or GNAT for Alpha systems.
20181 @item
20182 @code{IEEE_Float} specifies that floating-point
20183 types are represented by default with the IEEE single and
20184 double floating-point types.
20185 @end itemize
20187 @noindent
20188 GNAT provides an identical implementation of the pragma
20189 @code{Float_Representation}, except that it functions as a
20190 configuration pragma, as defined by Ada 95. Note that the
20191 notion of configuration pragma corresponds closely to the
20192 DEC Ada notion of a program library switch.
20194 When no pragma is used in GNAT, the default is IEEE_Float, which is different
20195 from DEC Ada 83, where the default is VAX_Float. In addition, the
20196 predefined libraries in GNAT are built using IEEE_Float, so it is not
20197 advisable to change the format of numbers passed to standard library
20198 routines, and if necessary explicit type conversions may be needed.
20200 The use of IEEE_Float is recommended in GNAT since it is more efficient,
20201 and (given that it conforms to an international standard) potentially more
20202 portable. The situation in which VAX_Float may be useful is in interfacing
20203 to existing code and data that expects the use of VAX_Float. There are
20204 two possibilities here. If the requirement for the use of VAX_Float is
20205 localized, then the best approach is to use the predefined VAX_Float
20206 types in package @code{System}, as extended by
20207 @code{Extend_System}. For example, use @code{System.F_Float}
20208 to specify the 32-bit @code{F-Float} format.
20210 Alternatively, if an entire program depends heavily on the use of
20211 the @code{VAX_Float} and in particular assumes that the types in
20212 package @code{Standard} are in @code{Vax_Float} format, then it
20213 may be desirable to reconfigure GNAT to assume Vax_Float by default.
20214 This is done by using the GNAT LIBRARY command to rebuild the library, and
20215 then using the general form of the @code{Float_Representation}
20216 pragma to ensure that this default format is used throughout.
20217 The form of the GNAT LIBRARY command is:
20219 @smallexample
20220 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
20221 @end smallexample
20223 @noindent
20224 where @i{file} contains the new configuration pragmas
20225 and @i{directory} is the directory to be created to contain
20226 the new library.
20228 @noindent
20229 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
20230 to allow control over the internal representation chosen
20231 for the predefined type @code{Long_Float} and for floating-point
20232 type declarations with digits specified in the range 7 .. 15.
20233 The format of this pragma is as follows:
20235 @smallexample @c ada
20236 @cartouche
20237 pragma Long_Float (D_FLOAT | G_FLOAT);
20238 @end cartouche
20239 @end smallexample
20241 @node Fixed-Point Types and Representations
20242 @subsection Fixed-Point Types and Representations
20244 @noindent
20245 On DEC Ada for OpenVMS Alpha systems, rounding is
20246 away from zero for both positive and negative numbers.
20247 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
20249 On GNAT for OpenVMS Alpha, the results of operations
20250 on fixed-point types are in accordance with the Ada 95
20251 rules. In particular, results of operations on decimal
20252 fixed-point types are truncated.
20254 @node Record and Array Component Alignment
20255 @subsection Record and Array Component Alignment
20257 @noindent
20258 On DEC Ada for OpenVMS Alpha, all non composite components
20259 are aligned on natural boundaries. For example, 1-byte
20260 components are aligned on byte boundaries, 2-byte
20261 components on 2-byte boundaries, 4-byte components on 4-byte
20262 byte boundaries, and so on. The OpenVMS Alpha hardware
20263 runs more efficiently with naturally aligned data.
20265 ON GNAT for OpenVMS Alpha, alignment rules are compatible
20266 with DEC Ada for OpenVMS Alpha.
20268 @node Address Clauses
20269 @subsection Address Clauses
20271 @noindent
20272 In DEC Ada and GNAT, address clauses are supported for
20273 objects and imported subprograms.
20274 The predefined type @code{System.Address} is a private type
20275 in both compilers, with the same representation (it is simply
20276 a machine pointer). Addition, subtraction, and comparison
20277 operations are available in the standard Ada 95 package
20278 @code{System.Storage_Elements}, or in package @code{System}
20279 if it is extended to include @code{System.Aux_DEC} using a
20280 pragma @code{Extend_System} as previously described.
20282 Note that code that with's both this extended package @code{System}
20283 and the package @code{System.Storage_Elements} should not @code{use}
20284 both packages, or ambiguities will result. In general it is better
20285 not to mix these two sets of facilities. The Ada 95 package was
20286 designed specifically to provide the kind of features that DEC Ada
20287 adds directly to package @code{System}.
20289 GNAT is compatible with DEC Ada in its handling of address
20290 clauses, except for some limitations in
20291 the form of address clauses for composite objects with
20292 initialization. Such address clauses are easily replaced
20293 by the use of an explicitly-defined constant as described
20294 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
20295 of declarations:
20297 @smallexample @c ada
20298 @cartouche
20299 X, Y : Integer := Init_Func;
20300 Q : String (X .. Y) := "abc";
20302 for Q'Address use Compute_Address;
20303 @end cartouche
20304 @end smallexample
20306 @noindent
20307 will be rejected by GNAT, since the address cannot be computed at the time
20308 that Q is declared. To achieve the intended effect, write instead:
20310 @smallexample @c ada
20311 @group
20312 @cartouche
20313 X, Y : Integer := Init_Func;
20314 Q_Address : constant Address := Compute_Address;
20315 Q : String (X .. Y) := "abc";
20317 for Q'Address use Q_Address;
20318 @end cartouche
20319 @end group
20320 @end smallexample
20322 @noindent
20323 which will be accepted by GNAT (and other Ada 95 compilers), and is also
20324 backwards compatible with Ada 83. A fuller description of the restrictions
20325 on address specifications is found in the GNAT Reference Manual.
20327 @node Other Representation Clauses
20328 @subsection Other Representation Clauses
20330 @noindent
20331 GNAT supports in a compatible manner all the representation
20332 clauses supported by DEC Ada. In addition, it
20333 supports representation clause forms that are new in Ada 95
20334 including COMPONENT_SIZE and SIZE clauses for objects.
20336 @node The Package STANDARD
20337 @section The Package STANDARD
20339 @noindent
20340 The package STANDARD, as implemented by DEC Ada, is fully
20341 described in the Reference Manual for the Ada Programming
20342 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
20343 Language Reference Manual. As implemented by GNAT, the
20344 package STANDARD is described in the Ada 95 Reference
20345 Manual.
20347 In addition, DEC Ada supports the Latin-1 character set in
20348 the type CHARACTER. GNAT supports the Latin-1 character set
20349 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
20350 the type WIDE_CHARACTER.
20352 The floating-point types supported by GNAT are those
20353 supported by DEC Ada, but defaults are different, and are controlled by
20354 pragmas. See @pxref{Floating-Point Types and Representations} for details.
20356 @node The Package SYSTEM
20357 @section The Package SYSTEM
20359 @noindent
20360 DEC Ada provides a system-specific version of the package
20361 SYSTEM for each platform on which the language ships.
20362 For the complete specification of the package SYSTEM, see
20363 Appendix F of the DEC Ada Language Reference Manual.
20365 On DEC Ada, the package SYSTEM includes the following conversion functions:
20366 @itemize @bullet
20367 @item TO_ADDRESS(INTEGER)
20369 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
20371 @item  TO_ADDRESS(universal_integer)
20373 @item  TO_INTEGER(ADDRESS)
20375 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
20377 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
20378                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
20379 @end itemize
20381 @noindent
20382 By default, GNAT supplies a version of SYSTEM that matches
20383 the definition given in the Ada 95 Reference Manual.
20384 This
20385 is a subset of the DIGITAL system definitions, which is as
20386 close as possible to the original definitions. The only difference
20387 is that the definition of SYSTEM_NAME is different:
20389 @smallexample @c ada
20390 @group
20391 @cartouche
20392 type Name is (SYSTEM_NAME_GNAT);
20393 System_Name : constant Name := SYSTEM_NAME_GNAT;
20394 @end cartouche
20395 @end group
20396 @end smallexample
20398 @noindent
20399 Also, GNAT adds the new Ada 95 declarations for
20400 BIT_ORDER and DEFAULT_BIT_ORDER.
20402 However, the use of the following pragma causes GNAT
20403 to extend the definition of package SYSTEM so that it
20404 encompasses the full set of DIGITAL-specific extensions,
20405 including the functions listed above:
20407 @smallexample @c ada
20408 @cartouche
20409 pragma Extend_System (Aux_DEC);
20410 @end cartouche
20411 @end smallexample
20413 @noindent
20414 The pragma Extend_System is a configuration pragma that
20415 is most conveniently placed in the @file{gnat.adc} file. See the
20416 GNAT Reference Manual for further details.
20418 DEC Ada does not allow the recompilation of the package
20419 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
20420 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
20421 the package SYSTEM. On OpenVMS Alpha systems, the pragma
20422 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
20423 its single argument.
20425 GNAT does permit the recompilation of package SYSTEM using
20426 a special switch (@option{-gnatg}) and this switch can be used if
20427 it is necessary to modify the definitions in SYSTEM. GNAT does
20428 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
20429 or MEMORY_SIZE by any other means.
20431 On GNAT systems, the pragma SYSTEM_NAME takes the
20432 enumeration literal SYSTEM_NAME_GNAT.
20434 The definitions provided by the use of
20436 @smallexample @c ada
20437 pragma Extend_System (AUX_Dec);
20438 @end smallexample
20440 @noindent
20441 are virtually identical to those provided by the DEC Ada 83 package
20442 System. One important difference is that the name of the TO_ADDRESS
20443 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
20444 See the GNAT Reference manual for a discussion of why this change was
20445 necessary.
20447 @noindent
20448 The version of TO_ADDRESS taking a universal integer argument is in fact
20449 an extension to Ada 83 not strictly compatible with the reference manual.
20450 In GNAT, we are constrained to be exactly compatible with the standard,
20451 and this means we cannot provide this capability. In DEC Ada 83, the
20452 point of this definition is to deal with a call like:
20454 @smallexample @c ada
20455 TO_ADDRESS (16#12777#);
20456 @end smallexample
20458 @noindent
20459 Normally, according to the Ada 83 standard, one would expect this to be
20460 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
20461 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
20462 definition using universal_integer takes precedence.
20464 In GNAT, since the version with universal_integer cannot be supplied, it is
20465 not possible to be 100% compatible. Since there are many programs using
20466 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
20467 to change the name of the function in the UNSIGNED_LONGWORD case, so the
20468 declarations provided in the GNAT version of AUX_Dec are:
20470 @smallexample @c ada
20471 function To_Address (X : Integer) return Address;
20472 pragma Pure_Function (To_Address);
20474 function To_Address_Long (X : Unsigned_Longword) return Address;
20475 pragma Pure_Function (To_Address_Long);
20476 @end smallexample
20478 @noindent
20479 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
20480 change the name to TO_ADDRESS_LONG.
20482 @node Tasking and Task-Related Features
20483 @section Tasking and Task-Related Features
20485 @noindent
20486 The concepts relevant to a comparison of tasking on GNAT
20487 and on DEC Ada for OpenVMS Alpha systems are discussed in
20488 the following sections.
20490 For detailed information on concepts related to tasking in
20491 DEC Ada, see the DEC Ada Language Reference Manual and the
20492 relevant run-time reference manual.
20494 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20495 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20497 @noindent
20498 On OpenVMS Alpha systems, each Ada task (except a passive
20499 task) is implemented as a single stream of execution
20500 that is created and managed by the kernel. On these
20501 systems, DEC Ada tasking support is based on DECthreads,
20502 an implementation of the POSIX standard for threads.
20504 Although tasks are implemented as threads, all tasks in
20505 an Ada program are part of the same process. As a result,
20506 resources such as open files and virtual memory can be
20507 shared easily among tasks. Having all tasks in one process
20508 allows better integration with the programming environment
20509 (the shell and the debugger, for example).
20511 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
20512 code that calls DECthreads routines can be used together.
20513 The interaction between Ada tasks and DECthreads routines
20514 can have some benefits. For example when on OpenVMS Alpha,
20515 DEC Ada can call C code that is already threaded.
20516 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
20517 and Ada tasks are mapped to threads.
20519 @menu
20520 * Assigning Task IDs::
20521 * Task IDs and Delays::
20522 * Task-Related Pragmas::
20523 * Scheduling and Task Priority::
20524 * The Task Stack::
20525 * External Interrupts::
20526 @end menu
20528 @node Assigning Task IDs
20529 @subsection Assigning Task IDs
20531 @noindent
20532 The DEC Ada Run-Time Library always assigns %TASK 1 to
20533 the environment task that executes the main program. On
20534 OpenVMS Alpha systems, %TASK 0 is often used for tasks
20535 that have been created but are not yet activated.
20537 On OpenVMS Alpha systems, task IDs are assigned at
20538 activation. On GNAT systems, task IDs are also assigned at
20539 task creation but do not have the same form or values as
20540 task ID values in DEC Ada. There is no null task, and the
20541 environment task does not have a specific task ID value.
20543 @node Task IDs and Delays
20544 @subsection Task IDs and Delays
20546 @noindent
20547 On OpenVMS Alpha systems, tasking delays are implemented
20548 using Timer System Services. The Task ID is used for the
20549 identification of the timer request (the REQIDT parameter).
20550 If Timers are used in the application take care not to use
20551 0 for the identification, because cancelling such a timer
20552 will cancel all timers and may lead to unpredictable results.
20554 @node Task-Related Pragmas
20555 @subsection Task-Related Pragmas
20557 @noindent
20558 Ada supplies the pragma TASK_STORAGE, which allows
20559 specification of the size of the guard area for a task
20560 stack. (The guard area forms an area of memory that has no
20561 read or write access and thus helps in the detection of
20562 stack overflow.) On OpenVMS Alpha systems, if the pragma
20563 TASK_STORAGE specifies a value of zero, a minimal guard
20564 area is created. In the absence of a pragma TASK_STORAGE, a default guard
20565 area is created.
20567 GNAT supplies the following task-related pragmas:
20569 @itemize @bullet
20570 @item  TASK_INFO
20572               This pragma appears within a task definition and
20573               applies to the task in which it appears. The argument
20574               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
20576 @item  TASK_STORAGE
20578               GNAT implements pragma TASK_STORAGE in the same way as
20579               DEC Ada.
20580               Both DEC Ada and GNAT supply the pragmas PASSIVE,
20581               SUPPRESS, and VOLATILE.
20582 @end itemize
20583 @node Scheduling and Task Priority
20584 @subsection Scheduling and Task Priority
20586 @noindent
20587 DEC Ada implements the Ada language requirement that
20588 when two tasks are eligible for execution and they have
20589 different priorities, the lower priority task does not
20590 execute while the higher priority task is waiting. The DEC
20591 Ada Run-Time Library keeps a task running until either the
20592 task is suspended or a higher priority task becomes ready.
20594 On OpenVMS Alpha systems, the default strategy is round-
20595 robin with preemption. Tasks of equal priority take turns
20596 at the processor. A task is run for a certain period of
20597 time and then placed at the rear of the ready queue for
20598 its priority level.
20600 DEC Ada provides the implementation-defined pragma TIME_SLICE,
20601 which can be used to enable or disable round-robin
20602 scheduling of tasks with the same priority.
20603 See the relevant DEC Ada run-time reference manual for
20604 information on using the pragmas to control DEC Ada task
20605 scheduling.
20607 GNAT follows the scheduling rules of Annex D (real-time
20608 Annex) of the Ada 95 Reference Manual. In general, this
20609 scheduling strategy is fully compatible with DEC Ada
20610 although it provides some additional constraints (as
20611 fully documented in Annex D).
20612 GNAT implements time slicing control in a manner compatible with
20613 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
20614 to the DEC Ada 83 pragma of the same name.
20615 Note that it is not possible to mix GNAT tasking and
20616 DEC Ada 83 tasking in the same program, since the two run times are
20617 not compatible.
20619 @node The Task Stack
20620 @subsection The Task Stack
20622 @noindent
20623 In DEC Ada, a task stack is allocated each time a
20624 non passive task is activated. As soon as the task is
20625 terminated, the storage for the task stack is deallocated.
20626 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
20627 a default stack size is used. Also, regardless of the size
20628 specified, some additional space is allocated for task
20629 management purposes. On OpenVMS Alpha systems, at least
20630 one page is allocated.
20632 GNAT handles task stacks in a similar manner. According to
20633 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
20634 an alternative method for controlling the task stack size.
20635 The specification of the attribute T'STORAGE_SIZE is also
20636 supported in a manner compatible with DEC Ada.
20638 @node External Interrupts
20639 @subsection External Interrupts
20641 @noindent
20642 On DEC Ada, external interrupts can be associated with task entries.
20643 GNAT is compatible with DEC Ada in its handling of external interrupts.
20645 @node Pragmas and Pragma-Related Features
20646 @section Pragmas and Pragma-Related Features
20648 @noindent
20649 Both DEC Ada and GNAT supply all language-defined pragmas
20650 as specified by the Ada 83 standard. GNAT also supplies all
20651 language-defined pragmas specified in the Ada 95 Reference Manual.
20652 In addition, GNAT implements the implementation-defined pragmas
20653 from DEC Ada 83.
20655 @itemize @bullet
20656 @item  AST_ENTRY
20658 @item  COMMON_OBJECT
20660 @item  COMPONENT_ALIGNMENT
20662 @item  EXPORT_EXCEPTION
20664 @item  EXPORT_FUNCTION
20666 @item  EXPORT_OBJECT
20668 @item  EXPORT_PROCEDURE
20670 @item  EXPORT_VALUED_PROCEDURE
20672 @item  FLOAT_REPRESENTATION
20674 @item  IDENT
20676 @item  IMPORT_EXCEPTION
20678 @item  IMPORT_FUNCTION
20680 @item  IMPORT_OBJECT
20682 @item  IMPORT_PROCEDURE
20684 @item  IMPORT_VALUED_PROCEDURE
20686 @item  INLINE_GENERIC
20688 @item  INTERFACE_NAME
20690 @item  LONG_FLOAT
20692 @item  MAIN_STORAGE
20694 @item  PASSIVE
20696 @item  PSET_OBJECT
20698 @item  SHARE_GENERIC
20700 @item  SUPPRESS_ALL
20702 @item  TASK_STORAGE
20704 @item  TIME_SLICE
20706 @item  TITLE
20707 @end itemize
20709 @noindent
20710 These pragmas are all fully implemented, with the exception of @code{Title},
20711 @code{Passive}, and @code{Share_Generic}, which are
20712 recognized, but which have no
20713 effect in GNAT. The effect of @code{Passive} may be obtained by the
20714 use of protected objects in Ada 95. In GNAT, all generics are inlined.
20716 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
20717 a separate subprogram specification which must appear before the
20718 subprogram body.
20720 GNAT also supplies a number of implementation-defined pragmas as follows:
20721 @itemize @bullet
20722 @item  C_PASS_BY_COPY
20724 @item  EXTEND_SYSTEM
20726 @item  SOURCE_FILE_NAME
20728 @item  UNSUPPRESS
20730 @item  WARNINGS
20732 @item  ABORT_DEFER
20734 @item  ADA_83
20736 @item  ADA_95
20738 @item  ANNOTATE
20740 @item  ASSERT
20742 @item  CPP_CLASS
20744 @item  CPP_CONSTRUCTOR
20746 @item  CPP_DESTRUCTOR
20748 @item  CPP_VIRTUAL
20750 @item  CP_VTABLE
20752 @item  DEBUG
20754 @item  LINKER_ALIAS
20756 @item  LINKER_SECTION
20758 @item  MACHINE_ATTRIBUTE
20760 @item  NO_RETURN
20762 @item  PURE_FUNCTION
20764 @item  SOURCE_REFERENCE
20766 @item  TASK_INFO
20768 @item  UNCHECKED_UNION
20770 @item  UNIMPLEMENTED_UNIT
20772 @item  UNIVERSAL_DATA
20774 @item  WEAK_EXTERNAL
20775 @end itemize
20777 @noindent
20778 For full details on these GNAT implementation-defined pragmas, see
20779 the GNAT Reference Manual.
20781 @menu
20782 * Restrictions on the Pragma INLINE::
20783 * Restrictions on the Pragma INTERFACE::
20784 * Restrictions on the Pragma SYSTEM_NAME::
20785 @end menu
20787 @node Restrictions on the Pragma INLINE
20788 @subsection Restrictions on the Pragma INLINE
20790 @noindent
20791 DEC Ada applies the following restrictions to the pragma INLINE:
20792 @itemize @bullet
20793 @item  Parameters cannot be a task type.
20795 @item  Function results cannot be task types, unconstrained
20796 array types, or unconstrained types with discriminants.
20798 @item  Bodies cannot declare the following:
20799 @itemize @bullet
20800 @item  Subprogram body or stub (imported subprogram is allowed)
20802 @item  Tasks
20804 @item  Generic declarations
20806 @item  Instantiations
20808 @item  Exceptions
20810 @item  Access types (types derived from access types allowed)
20812 @item  Array or record types
20814 @item  Dependent tasks
20816 @item  Direct recursive calls of subprogram or containing
20817 subprogram, directly or via a renaming
20819 @end itemize
20820 @end itemize
20822 @noindent
20823 In GNAT, the only restriction on pragma INLINE is that the
20824 body must occur before the call if both are in the same
20825 unit, and the size must be appropriately small. There are
20826 no other specific restrictions which cause subprograms to
20827 be incapable of being inlined.
20829 @node  Restrictions on the Pragma INTERFACE
20830 @subsection  Restrictions on the Pragma INTERFACE
20832 @noindent
20833 The following lists and describes the restrictions on the
20834 pragma INTERFACE on DEC Ada and GNAT:
20835 @itemize @bullet
20836 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20837 Default is the default on OpenVMS Alpha systems.
20839 @item  Parameter passing: Language specifies default
20840 mechanisms but can be overridden with an EXPORT pragma.
20842 @itemize @bullet
20843 @item  Ada: Use internal Ada rules.
20845 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20846 record or task type. Result cannot be a string, an
20847 array, or a record.
20849 @item  Fortran: Parameters cannot be a task. Result cannot
20850 be a string, an array, or a record.
20851 @end itemize
20852 @end itemize
20854 @noindent
20855 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
20856 record parameters for all languages.
20858 @node  Restrictions on the Pragma SYSTEM_NAME
20859 @subsection  Restrictions on the Pragma SYSTEM_NAME
20861 @noindent
20862 For DEC Ada for OpenVMS Alpha, the enumeration literal
20863 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
20864 literal for the type NAME is SYSTEM_NAME_GNAT.
20866 @node  Library of Predefined Units
20867 @section  Library of Predefined Units
20869 @noindent
20870 A library of predefined units is provided as part of the
20871 DEC Ada and GNAT implementations. DEC Ada does not provide
20872 the package MACHINE_CODE but instead recommends importing
20873 assembler code.
20875 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
20876 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20877 version. During GNAT installation, the DEC Ada Predefined
20878 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
20879 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
20880 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
20881 for details.
20883 The GNAT RTL is contained in
20884 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
20885 the default search path is set up to find DECLIB units in preference
20886 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
20887 for example).
20889 However, it is possible to change the default so that the
20890 reverse is true, or even to mix them using child package
20891 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
20892 is the package name, and the Ada units are available in the
20893 standard manner defined for Ada 95, that is to say as Ada.xxx. To
20894 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
20895 appropriately. For example, to change the default to use the Ada95
20896 versions do:
20898 @smallexample
20899 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
20900                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20901 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
20902                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20903 @end smallexample
20905 @menu
20906 * Changes to DECLIB::
20907 @end menu
20909 @node Changes to DECLIB
20910 @subsection Changes to DECLIB
20912 @noindent
20913 The changes made to the DEC Ada predefined library for GNAT and Ada 95
20914 compatibility are minor and include the following:
20916 @itemize @bullet
20917 @item  Adjusting the location of pragmas and record representation
20918 clauses to obey Ada 95 rules
20920 @item  Adding the proper notation to generic formal parameters
20921 that take unconstrained types in instantiation
20923 @item  Adding pragma ELABORATE_BODY to package specifications
20924 that have package bodies not otherwise allowed
20926 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
20927 @code{"PROTECTD"}.
20928 Currently these are found only in the STARLET package spec.
20929 @end itemize
20931 @noindent
20932 None of the above changes is visible to users.
20934 @node Bindings
20935 @section Bindings
20937 @noindent
20938 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
20939 @itemize @bullet
20941 @item  Command Language Interpreter (CLI interface)
20943 @item  DECtalk Run-Time Library (DTK interface)
20945 @item  Librarian utility routines (LBR interface)
20947 @item  General Purpose Run-Time Library (LIB interface)
20949 @item  Math Run-Time Library (MTH interface)
20951 @item  National Character Set Run-Time Library (NCS interface)
20953 @item  Compiled Code Support Run-Time Library (OTS interface)
20955 @item  Parallel Processing Run-Time Library (PPL interface)
20957 @item  Screen Management Run-Time Library (SMG interface)
20959 @item  Sort Run-Time Library (SOR interface)
20961 @item  String Run-Time Library (STR interface)
20963 @item STARLET System Library
20964 @findex Starlet
20966 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
20968 @item  X Windows Toolkit (XT interface)
20970 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
20971 @end itemize
20973 @noindent
20974 GNAT provides implementations of these DEC bindings in the DECLIB directory.
20976 The X/Motif bindings used to build DECLIB are whatever versions are in the
20977 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
20978 The build script will
20979 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
20980 and @code{X_Lib}
20981 causing the default X/Motif sharable image libraries to be linked in. This
20982 is done via options files named @file{xm.opt}, @file{xt.opt}, and
20983 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
20985 It may be necessary to edit these options files to update or correct the
20986 library names if, for example, the newer X/Motif bindings from
20987 @file{ADA$EXAMPLES}
20988 had been (previous to installing GNAT) copied and renamed to supersede the
20989 default @file{ADA$PREDEFINED} versions.
20991 @menu
20992 * Shared Libraries and Options Files::
20993 * Interfaces to C::
20994 @end menu
20996 @node Shared Libraries and Options Files
20997 @subsection Shared Libraries and Options Files
20999 @noindent
21000 When using the DEC Ada
21001 predefined X and Motif bindings, the linking with their sharable images is
21002 done automatically by @command{GNAT LINK}.
21003 When using other X and Motif bindings, you need
21004 to add the corresponding sharable images to the command line for
21005 @code{GNAT LINK}. When linking with shared libraries, or with
21006 @file{.OPT} files, you must
21007 also add them to the command line for @command{GNAT LINK}.
21009 A shared library to be used with GNAT is built in the same way as other
21010 libraries under VMS. The VMS Link command can be used in standard fashion.
21012 @node Interfaces to C
21013 @subsection Interfaces to C
21015 @noindent
21016 DEC Ada
21017 provides the following Ada types and operations:
21019 @itemize @bullet
21020 @item C types package (C_TYPES)
21022 @item C strings (C_TYPES.NULL_TERMINATED)
21024 @item Other_types (SHORT_INT)
21025 @end itemize
21027 @noindent
21028 Interfacing to C with GNAT, one can use the above approach
21029 described for DEC Ada or the facilities of Annex B of
21030 the Ada 95 Reference Manual (packages INTERFACES.C,
21031 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
21032 information, see the section ``Interfacing to C'' in the
21033 @cite{GNAT Reference Manual}.
21035 The @option{-gnatF} qualifier forces default and explicit
21036 @code{External_Name} parameters in pragmas Import and Export
21037 to be uppercased for compatibility with the default behavior
21038 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
21040 @node Main Program Definition
21041 @section Main Program Definition
21043 @noindent
21044 The following section discusses differences in the
21045 definition of main programs on DEC Ada and GNAT.
21046 On DEC Ada, main programs are defined to meet the
21047 following conditions:
21048 @itemize @bullet
21049 @item  Procedure with no formal parameters (returns 0 upon
21050        normal completion)
21052 @item  Procedure with no formal parameters (returns 42 when
21053        unhandled exceptions are raised)
21055 @item  Function with no formal parameters whose returned value
21056        is of a discrete type
21058 @item  Procedure with one OUT formal of a discrete type for
21059        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
21061 @end itemize
21063 @noindent
21064 When declared with the pragma EXPORT_VALUED_PROCEDURE,
21065 a main function or main procedure returns a discrete
21066 value whose size is less than 64 bits (32 on VAX systems),
21067 the value is zero- or sign-extended as appropriate.
21068 On GNAT, main programs are defined as follows:
21069 @itemize @bullet
21070 @item  Must be a non-generic, parameter-less subprogram that
21071 is either a procedure or function returning an Ada
21072 STANDARD.INTEGER (the predefined type)
21074 @item  Cannot be a generic subprogram or an instantiation of a
21075 generic subprogram
21076 @end itemize
21078 @node Implementation-Defined Attributes
21079 @section Implementation-Defined Attributes
21081 @noindent
21082 GNAT provides all DEC Ada implementation-defined
21083 attributes.
21085 @node Compiler and Run-Time Interfacing
21086 @section Compiler and Run-Time Interfacing
21088 @noindent
21089 DEC Ada provides the following ways to pass options to the linker
21090 (ACS LINK):
21091 @itemize @bullet
21092 @item  /WAIT and /SUBMIT qualifiers
21094 @item  /COMMAND qualifier
21096 @item  /[NO]MAP qualifier
21098 @item  /OUTPUT=file-spec
21100 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
21101 @end itemize
21103 @noindent
21104 To pass options to the linker, GNAT provides the following
21105 switches:
21107 @itemize @bullet
21108 @item   @option{/EXECUTABLE=exec-name}
21110 @item   @option{/VERBOSE qualifier}
21112 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
21113 @end itemize
21115 @noindent
21116 For more information on these switches, see
21117 @ref{Switches for gnatlink}.
21118 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
21119 to control optimization. DEC Ada also supplies the
21120 following pragmas:
21121 @itemize @bullet
21122 @item  @code{OPTIMIZE}
21124 @item  @code{INLINE}
21126 @item  @code{INLINE_GENERIC}
21128 @item  @code{SUPPRESS_ALL}
21130 @item  @code{PASSIVE}
21131 @end itemize
21133 @noindent
21134 In GNAT, optimization is controlled strictly by command
21135 line parameters, as described in the corresponding section of this guide.
21136 The DIGITAL pragmas for control of optimization are
21137 recognized but ignored.
21139 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
21140 the default is that optimization is turned on.
21142 @node Program Compilation and Library Management
21143 @section Program Compilation and Library Management
21145 @noindent
21146 DEC Ada and GNAT provide a comparable set of commands to
21147 build programs. DEC Ada also provides a program library,
21148 which is a concept that does not exist on GNAT. Instead,
21149 GNAT provides directories of sources that are compiled as
21150 needed.
21152 The following table summarizes
21153 the DEC Ada commands and provides
21154 equivalent GNAT commands. In this table, some GNAT
21155 equivalents reflect the fact that GNAT does not use the
21156 concept of a program library. Instead, it uses a model
21157 in which collections of source and object files are used
21158 in a manner consistent with other languages like C and
21159 Fortran. Therefore, standard system file commands are used
21160 to manipulate these elements. Those GNAT commands are marked with
21161 an asterisk.
21162 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
21164 @need 1500
21165 @multitable @columnfractions .35 .65
21167 @item @emph{DEC Ada Command}
21168 @tab @emph{GNAT Equivalent / Description}
21170 @item @command{ADA}
21171 @tab @command{GNAT COMPILE}@*
21172 Invokes the compiler to compile one or more Ada source files.
21174 @item @command{ACS ATTACH}@*
21175 @tab [No equivalent]@*
21176 Switches control of terminal from current process running the program
21177 library manager.
21179 @item @command{ACS CHECK}
21180 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21181 Forms the execution closure of one
21182 or more compiled units and checks completeness and currency.
21184 @item @command{ACS COMPILE}
21185 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21186 Forms the execution closure of one or
21187 more specified units, checks completeness and currency,
21188 identifies units that have revised source files, compiles same,
21189 and recompiles units that are or will become obsolete.
21190 Also completes incomplete generic instantiations.
21192 @item @command{ACS COPY FOREIGN}
21193 @tab Copy (*)@*
21194 Copies a foreign object file into the program library as a
21195 library unit body.
21197 @item @command{ACS COPY UNIT}
21198 @tab Copy (*)@*
21199 Copies a compiled unit from one program library to another.
21201 @item @command{ACS CREATE LIBRARY}
21202 @tab Create /directory (*)@*
21203 Creates a program library.
21205 @item @command{ACS CREATE SUBLIBRARY}
21206 @tab Create /directory (*)@*
21207 Creates a program sublibrary.
21209 @item @command{ACS DELETE LIBRARY}
21210 @tab @*
21211 Deletes a program library and its contents.
21213 @item @command{ACS DELETE SUBLIBRARY}
21214 @tab @*
21215 Deletes a program sublibrary and its contents.
21217 @item @command{ACS DELETE UNIT}
21218 @tab Delete file (*)@*
21219 On OpenVMS systems, deletes one or more compiled units from
21220 the current program library.
21222 @item @command{ACS DIRECTORY}
21223 @tab Directory (*)@*
21224 On OpenVMS systems, lists units contained in the current
21225 program library.
21227 @item @command{ACS ENTER FOREIGN}
21228 @tab Copy (*)@*
21229 Allows the import of a foreign body as an Ada library
21230 specification and enters a reference to a pointer.
21232 @item @command{ACS ENTER UNIT}
21233 @tab Copy (*)@*
21234 Enters a reference (pointer) from the current program library to
21235 a unit compiled into another program library.
21237 @item @command{ACS EXIT}
21238 @tab [No equivalent]@*
21239 Exits from the program library manager.
21241 @item @command{ACS EXPORT}
21242 @tab Copy (*)@*
21243 Creates an object file that contains system-specific object code
21244 for one or more units. With GNAT, object files can simply be copied
21245 into the desired directory.
21247 @item @command{ACS EXTRACT SOURCE}
21248 @tab Copy (*)@*
21249 Allows access to the copied source file for each Ada compilation unit
21251 @item @command{ACS HELP}
21252 @tab @command{HELP GNAT}@*
21253 Provides online help.
21255 @item @command{ACS LINK}
21256 @tab @command{GNAT LINK}@*
21257 Links an object file containing Ada units into an executable file.
21259 @item @command{ACS LOAD}
21260 @tab Copy (*)@*
21261 Loads (partially compiles) Ada units into the program library.
21262 Allows loading a program from a collection of files into a library
21263 without knowing the relationship among units.
21265 @item @command{ACS MERGE}
21266 @tab Copy (*)@*
21267 Merges into the current program library, one or more units from
21268 another library where they were modified.
21270 @item @command{ACS RECOMPILE}
21271 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21272 Recompiles from   external or copied source files any obsolete
21273 unit in the closure. Also, completes any incomplete generic
21274 instantiations.
21276 @item @command{ACS REENTER}
21277 @tab @command{GNAT MAKE}@*
21278 Reenters current references to units compiled after last entered
21279 with the @command{ACS ENTER UNIT} command.
21281 @item @command{ACS SET LIBRARY}
21282 @tab Set default (*)@*
21283 Defines a program library to be the compilation context as well
21284 as the target library for compiler output and commands in general.
21286 @item @command{ACS SET PRAGMA}
21287 @tab Edit @file{gnat.adc} (*)@*
21288 Redefines specified  values of the library characteristics
21289 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21290 and @code{Float_Representation}.
21292 @item @command{ACS SET SOURCE}
21293 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21294 Defines the source file search list for the @command{ACS COMPILE} command.
21296 @item @command{ACS SHOW LIBRARY}
21297 @tab Directory (*)@*
21298 Lists information about one or more program libraries.
21300 @item @command{ACS SHOW PROGRAM}
21301 @tab [No equivalent]@*
21302 Lists information about the execution closure of one or
21303 more units in the program library.
21305 @item @command{ACS SHOW SOURCE}
21306 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21307 Shows the source file search used when compiling units.
21309 @item @command{ACS SHOW VERSION}
21310 @tab Compile with @option{VERBOSE} option
21311 Displays the version number of the compiler and program library
21312 manager used.
21314 @item @command{ACS SPAWN}
21315 @tab [No equivalent]@*
21316 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21317 command).
21319 @item @command{ACS VERIFY}
21320 @tab [No equivalent]@*
21321 Performs a series of consistency checks on a program library to
21322 determine whether the library structure and library files are in
21323 valid form.
21324 @end multitable
21326 @noindent
21328 @node Input-Output
21329 @section Input-Output
21331 @noindent
21332 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
21333 Management Services (RMS) to perform operations on
21334 external files.
21336 @noindent
21337 DEC Ada and GNAT predefine an identical set of input-
21338 output packages. To make the use of the
21339 generic TEXT_IO operations more convenient, DEC Ada
21340 provides predefined library packages that instantiate the
21341 integer and floating-point operations for the predefined
21342 integer and floating-point types as shown in the following table.
21344 @multitable @columnfractions .45 .55
21345 @item @emph{Package Name} @tab Instantiation
21347 @item @code{INTEGER_TEXT_IO}
21348 @tab @code{INTEGER_IO(INTEGER)}
21350 @item @code{SHORT_INTEGER_TEXT_IO}
21351 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21353 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21354 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21356 @item @code{FLOAT_TEXT_IO}
21357 @tab @code{FLOAT_IO(FLOAT)}
21359 @item @code{LONG_FLOAT_TEXT_IO}
21360 @tab @code{FLOAT_IO(LONG_FLOAT)}
21361 @end multitable
21363 @noindent
21364 The DEC Ada predefined packages and their operations
21365 are implemented using OpenVMS Alpha files and input-
21366 output facilities. DEC Ada supports asynchronous input-
21367 output on OpenVMS Alpha. Familiarity with the following is
21368 recommended:
21369 @itemize @bullet
21370 @item  RMS file organizations and access methods
21372 @item  OpenVMS file specifications and directories
21374 @item  OpenVMS File Definition Language (FDL)
21375 @end itemize
21377 @noindent
21378 GNAT provides I/O facilities that are completely
21379 compatible with DEC Ada. The distribution includes the
21380 standard DEC Ada versions of all I/O packages, operating
21381 in a manner compatible with DEC Ada. In particular, the
21382 following packages are by default the DEC Ada (Ada 83)
21383 versions of these packages rather than the renamings
21384 suggested in annex J of the Ada 95 Reference Manual:
21385 @itemize @bullet
21386 @item  @code{TEXT_IO}
21388 @item  @code{SEQUENTIAL_IO}
21390 @item  @code{DIRECT_IO}
21391 @end itemize
21393 @noindent
21394 The use of the standard Ada 95 syntax for child packages (for
21395 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
21396 packages, as defined in the Ada 95 Reference Manual.
21397 GNAT provides DIGITAL-compatible predefined instantiations
21398 of the @code{TEXT_IO} packages, and also
21399 provides the standard predefined instantiations required
21400 by the Ada 95 Reference Manual.
21402 For further information on how GNAT interfaces to the file
21403 system or how I/O is implemented in programs written in
21404 mixed languages, see the chapter ``Implementation of the
21405 Standard I/O'' in the @cite{GNAT Reference Manual}.
21406 This chapter covers the following:
21407 @itemize @bullet
21408 @item  Standard I/O packages
21410 @item  @code{FORM} strings
21412 @item  @code{ADA.DIRECT_IO}
21414 @item  @code{ADA.SEQUENTIAL_IO}
21416 @item  @code{ADA.TEXT_IO}
21418 @item  Stream pointer positioning
21420 @item  Reading and writing non-regular files
21422 @item  @code{GET_IMMEDIATE}
21424 @item  Treating @code{TEXT_IO} files as streams
21426 @item  Shared files
21428 @item  Open modes
21429 @end itemize
21431 @node Implementation Limits
21432 @section Implementation Limits
21434 @noindent
21435 The following table lists implementation limits for DEC Ada
21436 and GNAT systems.
21437 @multitable @columnfractions .60 .20 .20
21438 @sp 1
21439 @item  @emph{Compilation Parameter}
21440 @tab   @emph{DEC Ada}
21441 @tab   @emph{GNAT}
21442 @sp 1
21444 @item  In a subprogram or entry  declaration, maximum number of
21445        formal parameters that are of an unconstrained record type
21446 @tab   32
21447 @tab   No set limit
21448 @sp 1
21450 @item  Maximum identifier length (number of characters)
21451 @tab   255
21452 @tab   255
21453 @sp 1
21455 @item  Maximum number of characters in a source line
21456 @tab   255
21457 @tab   255
21458 @sp 1
21460 @item  Maximum collection size   (number of bytes)
21461 @tab   2**31-1
21462 @tab   2**31-1
21463 @sp 1
21465 @item  Maximum number of discriminants for a record type
21466 @tab   245
21467 @tab   No set limit
21468 @sp 1
21470 @item  Maximum number of formal parameters in an entry or
21471        subprogram declaration
21472 @tab   246
21473 @tab    No set limit
21474 @sp 1
21476 @item  Maximum number of dimensions in an array type
21477 @tab   255
21478 @tab   No set limit
21479 @sp 1
21481 @item  Maximum number of library  units and subunits in a compilation.
21482 @tab   4095
21483 @tab   No set limit
21484 @sp 1
21486 @item  Maximum number of library units and subunits in an execution.
21487 @tab   16383
21488 @tab   No set limit
21489 @sp 1
21491 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21492        or @code{PSECT_OBJECT}
21493 @tab   32757
21494 @tab   No set limit
21495 @sp 1
21497 @item  Maximum number of enumeration literals in an enumeration type
21498        definition
21499 @tab   65535
21500 @tab   No set limit
21501 @sp 1
21503 @item  Maximum number of lines in a source file
21504 @tab   65534
21505 @tab   No set limit
21506 @sp 1
21508 @item  Maximum number of bits in any object
21509 @tab   2**31-1
21510 @tab   2**31-1
21511 @sp 1
21513 @item  Maximum size of the static portion of a stack frame (approximate)
21514 @tab   2**31-1
21515 @tab   2**31-1
21516 @end multitable
21518 @node  Tools
21519 @section Tools
21521 @end ifset
21523 @c **************************************
21524 @node Platform-Specific Information for the Run-Time Libraries
21525 @appendix Platform-Specific Information for the Run-Time Libraries
21526 @cindex Tasking and threads libraries
21527 @cindex Threads libraries and tasking
21528 @cindex Run-time libraries (platform-specific information)
21530 @noindent
21531 The GNAT run-time implementation
21532 may vary with respect to both the underlying threads library and
21533 the exception handling scheme.
21534 For threads support, one or more of the following are supplied:
21535 @itemize @bullet
21536 @item @b{native threads library}, a binding to the thread package from
21537 the underlying operating system
21539 @item @b{FSU threads library}, a binding to the Florida State University
21540 threads implementation, which complies fully with the requirements of Annex D
21542 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21543 POSIX thread package
21544 @end itemize
21546 @noindent
21547 For exception handling, either or both of two models are supplied:
21548 @itemize @bullet
21549 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21550 Most programs should experience a substantial speed improvement by
21551 being compiled with a ZCX run-time.
21552 This is especially true for
21553 tasking applications or applications with many exception handlers.}
21554 @cindex Zero-Cost Exceptions
21555 @cindex ZCX (Zero-Cost Exceptions)
21556 which uses binder-generated tables that
21557 are interrogated at run time to locate a handler
21559 @item @b{setjmp / longjmp} (``SJLJ''),
21560 @cindex setjmp/longjmp Exception Model
21561 @cindex SJLJ (setjmp/longjmp Exception Model)
21562 which uses dynamically-set data to establish
21563 the set of handlers
21564 @end itemize
21566 @noindent
21567 This appendix summarizes which combinations of threads and exception support
21568 are supplied on various GNAT platforms.
21569 It then shows how to select a particular library either
21570 permanently or temporarily,
21571 explains the properties of (and tradeoffs among) the various threads
21572 libraries, and provides some additional
21573 information about several specific platforms.
21575 @menu
21576 * Summary of Run-Time Configurations::
21577 * Specifying a Run-Time Library::
21578 * Choosing between Native and FSU Threads Libraries::
21579 * Choosing the Scheduling Policy::
21580 * Solaris-Specific Considerations::
21581 * IRIX-Specific Considerations::
21582 * Linux-Specific Considerations::
21583 * AIX-Specific Considerations::
21584 @end menu
21586 @node Summary of Run-Time Configurations
21587 @section Summary of Run-Time Configurations
21589 @multitable @columnfractions .30 .70
21590 @item @b{alpha-openvms}
21591 @item @code{@ @ }@i{rts-native (default)}
21592 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21593 @item @code{@ @ @ @ }Exceptions @tab ZCX
21595 @item @b{pa-hpux}
21596 @item @code{@ @ }@i{rts-native (default)}
21597 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
21598 @item @code{@ @ @ @ }Exceptions @tab ZCX
21600 @item @code{@ @ }@i{rts-sjlj}
21601 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
21602 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21604 @item @b{sparc-solaris}  @tab
21605 @item @code{@ @ }@i{rts-native (default)}
21606 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21607 @item @code{@ @ @ @ }Exceptions @tab ZCX
21609 @item @code{@ @ }@i{rts-fsu}    @tab
21610 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
21611 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21613 @item @code{@ @ }@i{rts-m64}
21614 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
21615 @item @code{@ @ @ @ }Exceptions  @tab ZCX
21616 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
21617 @item    @tab Use only on Solaris 8 or later.
21618 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
21620 @item @code{@ @ }@i{rts-pthread}
21621 @item @code{@ @ @ @ }Tasking    @tab pthreads library
21622 @item @code{@ @ @ @ }Exceptions @tab ZCX
21624 @item @code{@ @ }@i{rts-sjlj}
21625 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21626 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21628 @item @b{x86-linux}
21629 @item @code{@ @ }@i{rts-native (default)}
21630 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
21631 @item @code{@ @ @ @ }Exceptions @tab ZCX
21633 @item @code{@ @ }@i{rts-fsu}
21634 @item @code{@ @ @ @ }Tasking    @tab FSU threads library
21635 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21637 @item @code{@ @ }@i{rts-sjlj}
21638 @item @code{@ @ @ @ }Tasking    @tab LinuxThread library
21639 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21641 @item @b{x86-windows}
21642 @item @code{@ @ }@i{rts-native (default)}
21643 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21644 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21646 @end multitable
21648 @node Specifying a Run-Time Library
21649 @section Specifying a Run-Time Library
21651 @noindent
21652 The @file{adainclude} subdirectory containing the sources of the GNAT
21653 run-time library, and the @file{adalib} subdirectory containing the
21654 @file{ALI} files and the static and/or shared GNAT library, are located
21655 in the gcc target-dependent area:
21657 @smallexample
21658 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21659 @end smallexample
21661 @noindent
21662 As indicated above, on some platforms several run-time libraries are supplied.
21663 These libraries are installed in the target dependent area and
21664 contain a complete source and binary subdirectory. The detailed description
21665 below explains the differences between the different libraries in terms of
21666 their thread support.
21668 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21669 This default run time is selected by the means of soft links.
21670 For example on x86-linux:
21672 @smallexample
21673 @group
21674  $(target-dir)
21675      |
21676      +--- adainclude----------+
21677      |                        |
21678      +--- adalib-----------+  |
21679      |                     |  |
21680      +--- rts-native       |  |
21681      |    |                |  |
21682      |    +--- adainclude <---+
21683      |    |                |
21684      |    +--- adalib <----+
21685      |
21686      +--- rts-fsu
21687      |    |
21688      |    +--- adainclude
21689      |    |
21690      |    +--- adalib
21691      |
21692      +--- rts-sjlj
21693           |
21694           +--- adainclude
21695           |
21696           +--- adalib
21697 @end group
21698 @end smallexample
21700 @noindent
21701 If the @i{rts-fsu} library is to be selected on a permanent basis,
21702 these soft links can be modified with the following commands:
21704 @smallexample
21705 $ cd $target
21706 $ rm -f adainclude adalib
21707 $ ln -s rts-fsu/adainclude adainclude
21708 $ ln -s rts-fsu/adalib adalib
21709 @end smallexample
21711 @noindent
21712 Alternatively, you can specify @file{rts-fsu/adainclude} in the file
21713 @file{$target/ada_source_path} and @file{rts-fsu/adalib} in
21714 @file{$target/ada_object_path}.
21716 Selecting another run-time library temporarily can be
21717 achieved by the regular mechanism for GNAT object or source path selection:
21719 @itemize @bullet
21720 @item
21721 Set the environment variables:
21723 @smallexample
21724 $ ADA_INCLUDE_PATH=$target/rts-fsu/adainclude:$ADA_INCLUDE_PATH
21725 $ ADA_OBJECTS_PATH=$target/rts-fsu/adalib:$ADA_OBJECTS_PATH
21726 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
21727 @end smallexample
21729 @item
21730 Use @option{-aI$target/rts-fsu/adainclude}
21731 and @option{-aO$target/rts-fsu/adalib}
21732 on the @command{gnatmake} command line
21734 @item
21735 Use the switch @option{--RTS}; e.g., @option{--RTS=fsu}
21736 @cindex @option{--RTS} option
21737 @end itemize
21739 @noindent
21740 You can similarly switch to @emph{rts-sjlj}.
21742 @node Choosing between Native and FSU Threads Libraries
21743 @section Choosing between Native and FSU Threads Libraries
21744 @cindex Native threads library
21745 @cindex FSU threads library
21747 @noindent
21748 Some GNAT implementations offer a choice between
21749 native threads and FSU threads.
21751 @itemize @bullet
21752 @item
21753 The @emph{native threads} library correspond to the standard system threads
21754 implementation (e.g. LinuxThreads on GNU/Linux,
21755 @cindex LinuxThreads library
21756 POSIX threads on AIX, or
21757 Solaris threads on Solaris). When this option is chosen, GNAT provides
21758 a full and accurate implementation of the core language tasking model
21759 as described in Chapter 9 of the Ada Reference Manual,
21760 but might not (and probably does not) implement
21761 the exact semantics as specified in @w{Annex D} (the Real-Time Systems Annex).
21762 @cindex Annex D (Real-Time Systems Annex) compliance
21763 @cindex Real-Time Systems Annex compliance
21764 Indeed, the reason that a choice of libraries is offered
21765 on a given target is because some of the
21766 ACATS tests for @w{Annex D} fail using the native threads library.
21767 As far as possible, this library is implemented
21768 in accordance with Ada semantics (e.g., modifying priorities as required
21769 to simulate ceiling locking),
21770 but there are often slight inaccuracies, most often in the area of
21771 absolutely respecting the priority rules on a single
21772 processor.
21773 Moreover, it is not possible in general to define the exact behavior,
21774 because the native threads implementations
21775 are not well enough documented.
21777 On systems where the @code{SCHED_FIFO} POSIX scheduling policy is supported,
21778 @cindex POSIX scheduling policies
21779 @cindex @code{SCHED_FIFO} scheduling policy
21780 native threads will provide a behavior very close to the @w{Annex D}
21781 requirements (i.e., a run-till-blocked scheduler with fixed priorities), but
21782 on some systems (in particular GNU/Linux and Solaris), you need to have root
21783 privileges to use the @code{SCHED_FIFO} policy.
21785 @item
21786 The @emph{FSU threads} library provides a completely accurate implementation
21787 of @w{Annex D}.
21788 Thus, operating with this library, GNAT is 100% compliant with both the core
21789 and all @w{Annex D}
21790 requirements.
21791 The formal validations for implementations offering
21792 a choice of threads packages are always carried out using the FSU
21793 threads option.
21794 @end itemize
21796 @noindent
21797 From these considerations, it might seem that FSU threads are the
21798 better choice,
21799 but that is by no means always the case. The FSU threads package
21800 operates with all Ada tasks appearing to the system to be a single
21801 thread. This is often considerably more efficient than operating
21802 with separate threads, since for example, switching between tasks
21803 can be accomplished without the (in some cases considerable)
21804 overhead of a context switch between two system threads. However,
21805 it means that you may well lose concurrency at the system
21806 level. Notably, some system operations (such as I/O) may block all
21807 tasks in a program and not just the calling task. More
21808 significantly, the FSU threads approach likely means you cannot
21809 take advantage of multiple processors, since for this you need
21810 separate threads (or even separate processes) to operate on
21811 different processors.
21813 For most programs, the native threads library is
21814 usually the better choice. Use the FSU threads if absolute
21815 conformance to @w{Annex D} is important for your application, or if
21816 you find that the improved efficiency of FSU threads is significant to you.
21818 Note also that to take full advantage of Florist and Glade, it is highly
21819 recommended that you use native threads.
21821 @node Choosing the Scheduling Policy
21822 @section Choosing the Scheduling Policy
21824 @noindent
21825 When using a POSIX threads implementation, you have a choice of several
21826 scheduling policies: @code{SCHED_FIFO},
21827 @cindex @code{SCHED_FIFO} scheduling policy
21828 @code{SCHED_RR}
21829 @cindex @code{SCHED_RR} scheduling policy
21830 and @code{SCHED_OTHER}.
21831 @cindex @code{SCHED_OTHER} scheduling policy
21832 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21833 or @code{SCHED_RR} requires special (e.g., root) privileges.
21835 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21836 @code{SCHED_FIFO},
21837 @cindex @code{SCHED_FIFO} scheduling policy
21838 you can use one of the following:
21840 @itemize @bullet
21841 @item
21842 @code{pragma Time_Slice (0.0)}
21843 @cindex pragma Time_Slice
21844 @item
21845 the corresponding binder option @option{-T0}
21846 @cindex @option{-T0} option
21847 @item
21848 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21849 @cindex pragma Task_Dispatching_Policy
21850 @end itemize
21852 @noindent
21853 To specify @code{SCHED_RR},
21854 @cindex @code{SCHED_RR} scheduling policy
21855 you should use @code{pragma Time_Slice} with a
21856 value greater than @code{0.0}, or else use the corresponding @option{-T}
21857 binder option.
21859 @node Solaris-Specific Considerations
21860 @section Solaris-Specific Considerations
21861 @cindex Solaris Sparc threads libraries
21863 @noindent
21864 This section addresses some topics related to the various threads libraries
21865 on Sparc Solaris and then provides some information on building and
21866 debugging 64-bit applications.
21868 @menu
21869 * Solaris Threads Issues::
21870 * Building and Debugging 64-bit Applications::
21871 @end menu
21873 @node Solaris Threads Issues
21874 @subsection Solaris Threads Issues
21876 @noindent
21877 Starting with version 3.14, GNAT under Solaris comes with a new tasking
21878 run-time library based on POSIX threads --- @emph{rts-pthread}.
21879 @cindex rts-pthread threads library
21880 This run-time library has the advantage of being mostly shared across all
21881 POSIX-compliant thread implementations, and it also provides under
21882 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21883 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21884 and @code{PTHREAD_PRIO_PROTECT}
21885 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21886 semantics that can be selected using the predefined pragma
21887 @code{Locking_Policy}
21888 @cindex pragma Locking_Policy (under rts-pthread)
21889 with respectively
21890 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21891 @cindex @code{Inheritance_Locking} (under rts-pthread)
21892 @cindex @code{Ceiling_Locking} (under rts-pthread)
21894 As explained above, the native run-time library is based on the Solaris thread
21895 library (@code{libthread}) and is the default library.
21896 The FSU run-time library is based on the FSU threads.
21897 @cindex FSU threads library
21899 Starting with Solaris 2.5.1, when the Solaris threads library is used
21900 (this is the default), programs
21901 compiled with GNAT can automatically take advantage of
21902 and can thus execute on multiple processors.
21903 The user can alternatively specify a processor on which the program should run
21904 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21905 is made by
21906 setting the environment variable @code{GNAT_PROCESSOR}
21907 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21908 to one of the following:
21910 @table @code
21911 @item -2
21912 Use the default configuration (run the program on all
21913          available processors) - this is the same as having
21914          @code{GNAT_PROCESSOR} unset
21916 @item -1
21917 Let the run-time implementation choose one processor and run the program on
21918          that processor
21920 @item 0 .. Last_Proc
21921 Run the program on the specified processor.
21922   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21923 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21924 @end table
21926 @node Building and Debugging 64-bit Applications
21927 @subsection Building and Debugging 64-bit Applications
21929 @noindent
21930 In a 64-bit application, all the sources involved must be compiled with the
21931 @option{-m64} command-line option, and a specific GNAT library (compiled with
21932 this option) is required.
21933 The easiest way to build a 64bit application is to add
21934 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
21936 To debug these applications, dwarf-2 debug information is required, so you
21937 have to add @option{-gdwarf-2} to your gnatmake arguments.
21938 In addition, a special
21939 version of gdb, called @command{gdb64}, needs to be used.
21941 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
21942 amounts to:
21944 @smallexample
21945      $ gnatmake -m64 -gdwarf-2 --RTS=m64 hello.adb
21946      $ gdb64 hello
21947 @end smallexample
21949 @node IRIX-Specific Considerations
21950 @section IRIX-Specific Considerations
21951 @cindex IRIX thread library
21953 @noindent
21954 On SGI IRIX, the thread library depends on which compiler is used.
21955 The @emph{o32 ABI} compiler comes with a run-time library based on the
21956 user-level @code{athread}
21957 library. Thus kernel-level capabilities such as nonblocking system
21958 calls or time slicing can only be achieved reliably by specifying different
21959 @code{sprocs} via the pragma @code{Task_Info}
21960 @cindex pragma Task_Info (and IRIX threads)
21961 and the
21962 @code{System.Task_Info} package.
21963 @cindex @code{System.Task_Info} package (and IRIX threads)
21964 See the @cite{GNAT Reference Manual} for further information.
21966 The @emph{n32 ABI} compiler comes with a run-time library based on the
21967 kernel POSIX threads and thus does not have the limitations mentioned above.
21969 @node Linux-Specific Considerations
21970 @section Linux-Specific Considerations
21971 @cindex Linux threads libraries
21973 @noindent
21974 The default thread library under GNU/Linux has the following disadvantages
21975 compared to other native thread libraries:
21977 @itemize @bullet
21978 @item The size of the task's stack is limited to 2 megabytes.
21979 @item  The signal model is not POSIX compliant, which means that to send a
21980   signal to the process, you need to send the signal to all threads,
21981   e.g. by using @code{killpg()}.
21982 @end itemize
21984 @node AIX-Specific Considerations
21985 @section AIX-Specific Considerations
21986 @cindex AIX resolver library
21988 @noindent
21989 On AIX, the resolver library initializes some internal structure on
21990 the first call to @code{get*by*} functions, which are used to implement
21991 @code{GNAT.Sockets.Get_Host_By_Name} and
21992 @code{GNAT.Sockets.Get_Host_By_Addrss}.
21993 If such initialization occurs within an Ada task, and the stack size for
21994 the task is the default size, a stack overflow may occur.
21996 To avoid this overflow, the user should either ensure that the first call
21997 to @code{GNAT.Sockets.Get_Host_By_Name} or
21998 @code{GNAT.Sockets.Get_Host_By_Addrss}
21999 occurs in the environment task, or use @code{pragma Storage_Size} to
22000 specify a sufficiently large size for the stack of the task that contains
22001 this call.
22003 @c *******************************
22004 @node Example of Binder Output File
22005 @appendix Example of Binder Output File
22007 @noindent
22008 This Appendix displays the source code for @command{gnatbind}'s output
22009 file generated for a simple ``Hello World'' program.
22010 Comments have been added for clarification purposes.
22012 @smallexample @c adanocomment
22013 @iftex
22014 @leftskip=0cm
22015 @end iftex
22016 --  The package is called Ada_Main unless this name is actually used
22017 --  as a unit name in the partition, in which case some other unique
22018 --  name is used.
22020 with System;
22021 package ada_main is
22023    Elab_Final_Code : Integer;
22024    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22026    --  The main program saves the parameters (argument count,
22027    --  argument values, environment pointer) in global variables
22028    --  for later access by other units including
22029    --  Ada.Command_Line.
22031    gnat_argc : Integer;
22032    gnat_argv : System.Address;
22033    gnat_envp : System.Address;
22035    --  The actual variables are stored in a library routine. This
22036    --  is useful for some shared library situations, where there
22037    --  are problems if variables are not in the library.
22039    pragma Import (C, gnat_argc);
22040    pragma Import (C, gnat_argv);
22041    pragma Import (C, gnat_envp);
22043    --  The exit status is similarly an external location
22045    gnat_exit_status : Integer;
22046    pragma Import (C, gnat_exit_status);
22048    GNAT_Version : constant String :=
22049                     "GNAT Version: 3.15w (20010315)";
22050    pragma Export (C, GNAT_Version, "__gnat_version");
22052    --  This is the generated adafinal routine that performs
22053    --  finalization at the end of execution. In the case where
22054    --  Ada is the main program, this main program makes a call
22055    --  to adafinal at program termination.
22057    procedure adafinal;
22058    pragma Export (C, adafinal, "adafinal");
22060    --  This is the generated adainit routine that performs
22061    --  initialization at the start of execution. In the case
22062    --  where Ada is the main program, this main program makes
22063    --  a call to adainit at program startup.
22065    procedure adainit;
22066    pragma Export (C, adainit, "adainit");
22068    --  This routine is called at the start of execution. It is
22069    --  a dummy routine that is used by the debugger to breakpoint
22070    --  at the start of execution.
22072    procedure Break_Start;
22073    pragma Import (C, Break_Start, "__gnat_break_start");
22075    --  This is the actual generated main program (it would be
22076    --  suppressed if the no main program switch were used). As
22077    --  required by standard system conventions, this program has
22078    --  the external name main.
22080    function main
22081      (argc : Integer;
22082       argv : System.Address;
22083       envp : System.Address)
22084       return Integer;
22085    pragma Export (C, main, "main");
22087    --  The following set of constants give the version
22088    --  identification values for every unit in the bound
22089    --  partition. This identification is computed from all
22090    --  dependent semantic units, and corresponds to the
22091    --  string that would be returned by use of the
22092    --  Body_Version or Version attributes.
22094    type Version_32 is mod 2 ** 32;
22095    u00001 : constant Version_32 := 16#7880BEB3#;
22096    u00002 : constant Version_32 := 16#0D24CBD0#;
22097    u00003 : constant Version_32 := 16#3283DBEB#;
22098    u00004 : constant Version_32 := 16#2359F9ED#;
22099    u00005 : constant Version_32 := 16#664FB847#;
22100    u00006 : constant Version_32 := 16#68E803DF#;
22101    u00007 : constant Version_32 := 16#5572E604#;
22102    u00008 : constant Version_32 := 16#46B173D8#;
22103    u00009 : constant Version_32 := 16#156A40CF#;
22104    u00010 : constant Version_32 := 16#033DABE0#;
22105    u00011 : constant Version_32 := 16#6AB38FEA#;
22106    u00012 : constant Version_32 := 16#22B6217D#;
22107    u00013 : constant Version_32 := 16#68A22947#;
22108    u00014 : constant Version_32 := 16#18CC4A56#;
22109    u00015 : constant Version_32 := 16#08258E1B#;
22110    u00016 : constant Version_32 := 16#367D5222#;
22111    u00017 : constant Version_32 := 16#20C9ECA4#;
22112    u00018 : constant Version_32 := 16#50D32CB6#;
22113    u00019 : constant Version_32 := 16#39A8BB77#;
22114    u00020 : constant Version_32 := 16#5CF8FA2B#;
22115    u00021 : constant Version_32 := 16#2F1EB794#;
22116    u00022 : constant Version_32 := 16#31AB6444#;
22117    u00023 : constant Version_32 := 16#1574B6E9#;
22118    u00024 : constant Version_32 := 16#5109C189#;
22119    u00025 : constant Version_32 := 16#56D770CD#;
22120    u00026 : constant Version_32 := 16#02F9DE3D#;
22121    u00027 : constant Version_32 := 16#08AB6B2C#;
22122    u00028 : constant Version_32 := 16#3FA37670#;
22123    u00029 : constant Version_32 := 16#476457A0#;
22124    u00030 : constant Version_32 := 16#731E1B6E#;
22125    u00031 : constant Version_32 := 16#23C2E789#;
22126    u00032 : constant Version_32 := 16#0F1BD6A1#;
22127    u00033 : constant Version_32 := 16#7C25DE96#;
22128    u00034 : constant Version_32 := 16#39ADFFA2#;
22129    u00035 : constant Version_32 := 16#571DE3E7#;
22130    u00036 : constant Version_32 := 16#5EB646AB#;
22131    u00037 : constant Version_32 := 16#4249379B#;
22132    u00038 : constant Version_32 := 16#0357E00A#;
22133    u00039 : constant Version_32 := 16#3784FB72#;
22134    u00040 : constant Version_32 := 16#2E723019#;
22135    u00041 : constant Version_32 := 16#623358EA#;
22136    u00042 : constant Version_32 := 16#107F9465#;
22137    u00043 : constant Version_32 := 16#6843F68A#;
22138    u00044 : constant Version_32 := 16#63305874#;
22139    u00045 : constant Version_32 := 16#31E56CE1#;
22140    u00046 : constant Version_32 := 16#02917970#;
22141    u00047 : constant Version_32 := 16#6CCBA70E#;
22142    u00048 : constant Version_32 := 16#41CD4204#;
22143    u00049 : constant Version_32 := 16#572E3F58#;
22144    u00050 : constant Version_32 := 16#20729FF5#;
22145    u00051 : constant Version_32 := 16#1D4F93E8#;
22146    u00052 : constant Version_32 := 16#30B2EC3D#;
22147    u00053 : constant Version_32 := 16#34054F96#;
22148    u00054 : constant Version_32 := 16#5A199860#;
22149    u00055 : constant Version_32 := 16#0E7F912B#;
22150    u00056 : constant Version_32 := 16#5760634A#;
22151    u00057 : constant Version_32 := 16#5D851835#;
22153    --  The following Export pragmas export the version numbers
22154    --  with symbolic names ending in B (for body) or S
22155    --  (for spec) so that they can be located in a link. The
22156    --  information provided here is sufficient to track down
22157    --  the exact versions of units used in a given build.
22159    pragma Export (C, u00001, "helloB");
22160    pragma Export (C, u00002, "system__standard_libraryB");
22161    pragma Export (C, u00003, "system__standard_libraryS");
22162    pragma Export (C, u00004, "adaS");
22163    pragma Export (C, u00005, "ada__text_ioB");
22164    pragma Export (C, u00006, "ada__text_ioS");
22165    pragma Export (C, u00007, "ada__exceptionsB");
22166    pragma Export (C, u00008, "ada__exceptionsS");
22167    pragma Export (C, u00009, "gnatS");
22168    pragma Export (C, u00010, "gnat__heap_sort_aB");
22169    pragma Export (C, u00011, "gnat__heap_sort_aS");
22170    pragma Export (C, u00012, "systemS");
22171    pragma Export (C, u00013, "system__exception_tableB");
22172    pragma Export (C, u00014, "system__exception_tableS");
22173    pragma Export (C, u00015, "gnat__htableB");
22174    pragma Export (C, u00016, "gnat__htableS");
22175    pragma Export (C, u00017, "system__exceptionsS");
22176    pragma Export (C, u00018, "system__machine_state_operationsB");
22177    pragma Export (C, u00019, "system__machine_state_operationsS");
22178    pragma Export (C, u00020, "system__machine_codeS");
22179    pragma Export (C, u00021, "system__storage_elementsB");
22180    pragma Export (C, u00022, "system__storage_elementsS");
22181    pragma Export (C, u00023, "system__secondary_stackB");
22182    pragma Export (C, u00024, "system__secondary_stackS");
22183    pragma Export (C, u00025, "system__parametersB");
22184    pragma Export (C, u00026, "system__parametersS");
22185    pragma Export (C, u00027, "system__soft_linksB");
22186    pragma Export (C, u00028, "system__soft_linksS");
22187    pragma Export (C, u00029, "system__stack_checkingB");
22188    pragma Export (C, u00030, "system__stack_checkingS");
22189    pragma Export (C, u00031, "system__tracebackB");
22190    pragma Export (C, u00032, "system__tracebackS");
22191    pragma Export (C, u00033, "ada__streamsS");
22192    pragma Export (C, u00034, "ada__tagsB");
22193    pragma Export (C, u00035, "ada__tagsS");
22194    pragma Export (C, u00036, "system__string_opsB");
22195    pragma Export (C, u00037, "system__string_opsS");
22196    pragma Export (C, u00038, "interfacesS");
22197    pragma Export (C, u00039, "interfaces__c_streamsB");
22198    pragma Export (C, u00040, "interfaces__c_streamsS");
22199    pragma Export (C, u00041, "system__file_ioB");
22200    pragma Export (C, u00042, "system__file_ioS");
22201    pragma Export (C, u00043, "ada__finalizationB");
22202    pragma Export (C, u00044, "ada__finalizationS");
22203    pragma Export (C, u00045, "system__finalization_rootB");
22204    pragma Export (C, u00046, "system__finalization_rootS");
22205    pragma Export (C, u00047, "system__finalization_implementationB");
22206    pragma Export (C, u00048, "system__finalization_implementationS");
22207    pragma Export (C, u00049, "system__string_ops_concat_3B");
22208    pragma Export (C, u00050, "system__string_ops_concat_3S");
22209    pragma Export (C, u00051, "system__stream_attributesB");
22210    pragma Export (C, u00052, "system__stream_attributesS");
22211    pragma Export (C, u00053, "ada__io_exceptionsS");
22212    pragma Export (C, u00054, "system__unsigned_typesS");
22213    pragma Export (C, u00055, "system__file_control_blockS");
22214    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22215    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22217    -- BEGIN ELABORATION ORDER
22218    -- ada (spec)
22219    -- gnat (spec)
22220    -- gnat.heap_sort_a (spec)
22221    -- gnat.heap_sort_a (body)
22222    -- gnat.htable (spec)
22223    -- gnat.htable (body)
22224    -- interfaces (spec)
22225    -- system (spec)
22226    -- system.machine_code (spec)
22227    -- system.parameters (spec)
22228    -- system.parameters (body)
22229    -- interfaces.c_streams (spec)
22230    -- interfaces.c_streams (body)
22231    -- system.standard_library (spec)
22232    -- ada.exceptions (spec)
22233    -- system.exception_table (spec)
22234    -- system.exception_table (body)
22235    -- ada.io_exceptions (spec)
22236    -- system.exceptions (spec)
22237    -- system.storage_elements (spec)
22238    -- system.storage_elements (body)
22239    -- system.machine_state_operations (spec)
22240    -- system.machine_state_operations (body)
22241    -- system.secondary_stack (spec)
22242    -- system.stack_checking (spec)
22243    -- system.soft_links (spec)
22244    -- system.soft_links (body)
22245    -- system.stack_checking (body)
22246    -- system.secondary_stack (body)
22247    -- system.standard_library (body)
22248    -- system.string_ops (spec)
22249    -- system.string_ops (body)
22250    -- ada.tags (spec)
22251    -- ada.tags (body)
22252    -- ada.streams (spec)
22253    -- system.finalization_root (spec)
22254    -- system.finalization_root (body)
22255    -- system.string_ops_concat_3 (spec)
22256    -- system.string_ops_concat_3 (body)
22257    -- system.traceback (spec)
22258    -- system.traceback (body)
22259    -- ada.exceptions (body)
22260    -- system.unsigned_types (spec)
22261    -- system.stream_attributes (spec)
22262    -- system.stream_attributes (body)
22263    -- system.finalization_implementation (spec)
22264    -- system.finalization_implementation (body)
22265    -- ada.finalization (spec)
22266    -- ada.finalization (body)
22267    -- ada.finalization.list_controller (spec)
22268    -- ada.finalization.list_controller (body)
22269    -- system.file_control_block (spec)
22270    -- system.file_io (spec)
22271    -- system.file_io (body)
22272    -- ada.text_io (spec)
22273    -- ada.text_io (body)
22274    -- hello (body)
22275    -- END ELABORATION ORDER
22277 end ada_main;
22279 --  The following source file name pragmas allow the generated file
22280 --  names to be unique for different main programs. They are needed
22281 --  since the package name will always be Ada_Main.
22283 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22284 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22286 --  Generated package body for Ada_Main starts here
22288 package body ada_main is
22290    --  The actual finalization is performed by calling the
22291    --  library routine in System.Standard_Library.Adafinal
22293    procedure Do_Finalize;
22294    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22296    -------------
22297    -- adainit --
22298    -------------
22300 @findex adainit
22301    procedure adainit is
22303       --  These booleans are set to True once the associated unit has
22304       --  been elaborated. It is also used to avoid elaborating the
22305       --  same unit twice.
22307       E040 : Boolean;
22308       pragma Import (Ada, E040, "interfaces__c_streams_E");
22310       E008 : Boolean;
22311       pragma Import (Ada, E008, "ada__exceptions_E");
22313       E014 : Boolean;
22314       pragma Import (Ada, E014, "system__exception_table_E");
22316       E053 : Boolean;
22317       pragma Import (Ada, E053, "ada__io_exceptions_E");
22319       E017 : Boolean;
22320       pragma Import (Ada, E017, "system__exceptions_E");
22322       E024 : Boolean;
22323       pragma Import (Ada, E024, "system__secondary_stack_E");
22325       E030 : Boolean;
22326       pragma Import (Ada, E030, "system__stack_checking_E");
22328       E028 : Boolean;
22329       pragma Import (Ada, E028, "system__soft_links_E");
22331       E035 : Boolean;
22332       pragma Import (Ada, E035, "ada__tags_E");
22334       E033 : Boolean;
22335       pragma Import (Ada, E033, "ada__streams_E");
22337       E046 : Boolean;
22338       pragma Import (Ada, E046, "system__finalization_root_E");
22340       E048 : Boolean;
22341       pragma Import (Ada, E048, "system__finalization_implementation_E");
22343       E044 : Boolean;
22344       pragma Import (Ada, E044, "ada__finalization_E");
22346       E057 : Boolean;
22347       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22349       E055 : Boolean;
22350       pragma Import (Ada, E055, "system__file_control_block_E");
22352       E042 : Boolean;
22353       pragma Import (Ada, E042, "system__file_io_E");
22355       E006 : Boolean;
22356       pragma Import (Ada, E006, "ada__text_io_E");
22358       --  Set_Globals is a library routine that stores away the
22359       --  value of the indicated set of global values in global
22360       --  variables within the library.
22362       procedure Set_Globals
22363         (Main_Priority            : Integer;
22364          Time_Slice_Value         : Integer;
22365          WC_Encoding              : Character;
22366          Locking_Policy           : Character;
22367          Queuing_Policy           : Character;
22368          Task_Dispatching_Policy  : Character;
22369          Adafinal                 : System.Address;
22370          Unreserve_All_Interrupts : Integer;
22371          Exception_Tracebacks     : Integer);
22372 @findex __gnat_set_globals
22373       pragma Import (C, Set_Globals, "__gnat_set_globals");
22375       --  SDP_Table_Build is a library routine used to build the
22376       --  exception tables. See unit Ada.Exceptions in files
22377       --  a-except.ads/adb for full details of how zero cost
22378       --  exception handling works. This procedure, the call to
22379       --  it, and the two following tables are all omitted if the
22380       --  build is in longjmp/setjump exception mode.
22382 @findex SDP_Table_Build
22383 @findex Zero Cost Exceptions
22384       procedure SDP_Table_Build
22385         (SDP_Addresses   : System.Address;
22386          SDP_Count       : Natural;
22387          Elab_Addresses  : System.Address;
22388          Elab_Addr_Count : Natural);
22389       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22391       --  Table of Unit_Exception_Table addresses. Used for zero
22392       --  cost exception handling to build the top level table.
22394       ST : aliased constant array (1 .. 23) of System.Address := (
22395         Hello'UET_Address,
22396         Ada.Text_Io'UET_Address,
22397         Ada.Exceptions'UET_Address,
22398         Gnat.Heap_Sort_A'UET_Address,
22399         System.Exception_Table'UET_Address,
22400         System.Machine_State_Operations'UET_Address,
22401         System.Secondary_Stack'UET_Address,
22402         System.Parameters'UET_Address,
22403         System.Soft_Links'UET_Address,
22404         System.Stack_Checking'UET_Address,
22405         System.Traceback'UET_Address,
22406         Ada.Streams'UET_Address,
22407         Ada.Tags'UET_Address,
22408         System.String_Ops'UET_Address,
22409         Interfaces.C_Streams'UET_Address,
22410         System.File_Io'UET_Address,
22411         Ada.Finalization'UET_Address,
22412         System.Finalization_Root'UET_Address,
22413         System.Finalization_Implementation'UET_Address,
22414         System.String_Ops_Concat_3'UET_Address,
22415         System.Stream_Attributes'UET_Address,
22416         System.File_Control_Block'UET_Address,
22417         Ada.Finalization.List_Controller'UET_Address);
22419       --  Table of addresses of elaboration routines. Used for
22420       --  zero cost exception handling to make sure these
22421       --  addresses are included in the top level procedure
22422       --  address table.
22424       EA : aliased constant array (1 .. 23) of System.Address := (
22425         adainit'Code_Address,
22426         Do_Finalize'Code_Address,
22427         Ada.Exceptions'Elab_Spec'Address,
22428         System.Exceptions'Elab_Spec'Address,
22429         Interfaces.C_Streams'Elab_Spec'Address,
22430         System.Exception_Table'Elab_Body'Address,
22431         Ada.Io_Exceptions'Elab_Spec'Address,
22432         System.Stack_Checking'Elab_Spec'Address,
22433         System.Soft_Links'Elab_Body'Address,
22434         System.Secondary_Stack'Elab_Body'Address,
22435         Ada.Tags'Elab_Spec'Address,
22436         Ada.Tags'Elab_Body'Address,
22437         Ada.Streams'Elab_Spec'Address,
22438         System.Finalization_Root'Elab_Spec'Address,
22439         Ada.Exceptions'Elab_Body'Address,
22440         System.Finalization_Implementation'Elab_Spec'Address,
22441         System.Finalization_Implementation'Elab_Body'Address,
22442         Ada.Finalization'Elab_Spec'Address,
22443         Ada.Finalization.List_Controller'Elab_Spec'Address,
22444         System.File_Control_Block'Elab_Spec'Address,
22445         System.File_Io'Elab_Body'Address,
22446         Ada.Text_Io'Elab_Spec'Address,
22447         Ada.Text_Io'Elab_Body'Address);
22449    --  Start of processing for adainit
22451    begin
22453       --  Call SDP_Table_Build to build the top level procedure
22454       --  table for zero cost exception handling (omitted in
22455       --  longjmp/setjump mode).
22457       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22459       --  Call Set_Globals to record various information for
22460       --  this partition.  The values are derived by the binder
22461       --  from information stored in the ali files by the compiler.
22463 @findex __gnat_set_globals
22464       Set_Globals
22465         (Main_Priority            => -1,
22466          --  Priority of main program, -1 if no pragma Priority used
22468          Time_Slice_Value         => -1,
22469          --  Time slice from Time_Slice pragma, -1 if none used
22471          WC_Encoding              => 'b',
22472          --  Wide_Character encoding used, default is brackets
22474          Locking_Policy           => ' ',
22475          --  Locking_Policy used, default of space means not
22476          --  specified, otherwise it is the first character of
22477          --  the policy name.
22479          Queuing_Policy           => ' ',
22480          --  Queuing_Policy used, default of space means not
22481          --  specified, otherwise it is the first character of
22482          --  the policy name.
22484          Task_Dispatching_Policy  => ' ',
22485          --  Task_Dispatching_Policy used, default of space means
22486          --  not specified, otherwise first character of the
22487          --  policy name.
22489          Adafinal                 => System.Null_Address,
22490          --  Address of Adafinal routine, not used anymore
22492          Unreserve_All_Interrupts => 0,
22493          --  Set true if pragma Unreserve_All_Interrupts was used
22495          Exception_Tracebacks     => 0);
22496          --  Indicates if exception tracebacks are enabled
22498       Elab_Final_Code := 1;
22500       --  Now we have the elaboration calls for all units in the partition.
22501       --  The Elab_Spec and Elab_Body attributes generate references to the
22502       --  implicit elaboration procedures generated by the compiler for
22503       --  each unit that requires elaboration.
22505       if not E040 then
22506          Interfaces.C_Streams'Elab_Spec;
22507       end if;
22508       E040 := True;
22509       if not E008 then
22510          Ada.Exceptions'Elab_Spec;
22511       end if;
22512       if not E014 then
22513          System.Exception_Table'Elab_Body;
22514          E014 := True;
22515       end if;
22516       if not E053 then
22517          Ada.Io_Exceptions'Elab_Spec;
22518          E053 := True;
22519       end if;
22520       if not E017 then
22521          System.Exceptions'Elab_Spec;
22522          E017 := True;
22523       end if;
22524       if not E030 then
22525          System.Stack_Checking'Elab_Spec;
22526       end if;
22527       if not E028 then
22528          System.Soft_Links'Elab_Body;
22529          E028 := True;
22530       end if;
22531       E030 := True;
22532       if not E024 then
22533          System.Secondary_Stack'Elab_Body;
22534          E024 := True;
22535       end if;
22536       if not E035 then
22537          Ada.Tags'Elab_Spec;
22538       end if;
22539       if not E035 then
22540          Ada.Tags'Elab_Body;
22541          E035 := True;
22542       end if;
22543       if not E033 then
22544          Ada.Streams'Elab_Spec;
22545          E033 := True;
22546       end if;
22547       if not E046 then
22548          System.Finalization_Root'Elab_Spec;
22549       end if;
22550       E046 := True;
22551       if not E008 then
22552          Ada.Exceptions'Elab_Body;
22553          E008 := True;
22554       end if;
22555       if not E048 then
22556          System.Finalization_Implementation'Elab_Spec;
22557       end if;
22558       if not E048 then
22559          System.Finalization_Implementation'Elab_Body;
22560          E048 := True;
22561       end if;
22562       if not E044 then
22563          Ada.Finalization'Elab_Spec;
22564       end if;
22565       E044 := True;
22566       if not E057 then
22567          Ada.Finalization.List_Controller'Elab_Spec;
22568       end if;
22569       E057 := True;
22570       if not E055 then
22571          System.File_Control_Block'Elab_Spec;
22572          E055 := True;
22573       end if;
22574       if not E042 then
22575          System.File_Io'Elab_Body;
22576          E042 := True;
22577       end if;
22578       if not E006 then
22579          Ada.Text_Io'Elab_Spec;
22580       end if;
22581       if not E006 then
22582          Ada.Text_Io'Elab_Body;
22583          E006 := True;
22584       end if;
22586       Elab_Final_Code := 0;
22587    end adainit;
22589    --------------
22590    -- adafinal --
22591    --------------
22593 @findex adafinal
22594    procedure adafinal is
22595    begin
22596       Do_Finalize;
22597    end adafinal;
22599    ----------
22600    -- main --
22601    ----------
22603    --  main is actually a function, as in the ANSI C standard,
22604    --  defined to return the exit status. The three parameters
22605    --  are the argument count, argument values and environment
22606    --  pointer.
22608 @findex Main Program
22609    function main
22610      (argc : Integer;
22611       argv : System.Address;
22612       envp : System.Address)
22613       return Integer
22614    is
22615       --  The initialize routine performs low level system
22616       --  initialization using a standard library routine which
22617       --  sets up signal handling and performs any other
22618       --  required setup. The routine can be found in file
22619       --  a-init.c.
22621 @findex __gnat_initialize
22622       procedure initialize;
22623       pragma Import (C, initialize, "__gnat_initialize");
22625       --  The finalize routine performs low level system
22626       --  finalization using a standard library routine. The
22627       --  routine is found in file a-final.c and in the standard
22628       --  distribution is a dummy routine that does nothing, so
22629       --  really this is a hook for special user finalization.
22631 @findex __gnat_finalize
22632       procedure finalize;
22633       pragma Import (C, finalize, "__gnat_finalize");
22635       --  We get to the main program of the partition by using
22636       --  pragma Import because if we try to with the unit and
22637       --  call it Ada style, then not only do we waste time
22638       --  recompiling it, but also, we don't really know the right
22639       --  switches (e.g. identifier character set) to be used
22640       --  to compile it.
22642       procedure Ada_Main_Program;
22643       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22645    --  Start of processing for main
22647    begin
22648       --  Save global variables
22650       gnat_argc := argc;
22651       gnat_argv := argv;
22652       gnat_envp := envp;
22654       --  Call low level system initialization
22656       Initialize;
22658       --  Call our generated Ada initialization routine
22660       adainit;
22662       --  This is the point at which we want the debugger to get
22663       --  control
22665       Break_Start;
22667       --  Now we call the main program of the partition
22669       Ada_Main_Program;
22671       --  Perform Ada finalization
22673       adafinal;
22675       --  Perform low level system finalization
22677       Finalize;
22679       --  Return the proper exit status
22680       return (gnat_exit_status);
22681    end;
22683 --  This section is entirely comments, so it has no effect on the
22684 --  compilation of the Ada_Main package. It provides the list of
22685 --  object files and linker options, as well as some standard
22686 --  libraries needed for the link. The gnatlink utility parses
22687 --  this b~hello.adb file to read these comment lines to generate
22688 --  the appropriate command line arguments for the call to the
22689 --  system linker. The BEGIN/END lines are used for sentinels for
22690 --  this parsing operation.
22692 --  The exact file names will of course depend on the environment,
22693 --  host/target and location of files on the host system.
22695 @findex Object file list
22696 -- BEGIN Object file/option list
22697    --   ./hello.o
22698    --   -L./
22699    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22700    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22701 -- END Object file/option list
22703 end ada_main;
22704 @end smallexample
22706 @noindent
22707 The Ada code in the above example is exactly what is generated by the
22708 binder. We have added comments to more clearly indicate the function
22709 of each part of the generated @code{Ada_Main} package.
22711 The code is standard Ada in all respects, and can be processed by any
22712 tools that handle Ada. In particular, it is possible to use the debugger
22713 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22714 suppose that for reasons that you do not understand, your program is crashing
22715 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22716 you can place a breakpoint on the call:
22718 @smallexample @c ada
22719 Ada.Text_Io'Elab_Body;
22720 @end smallexample
22722 @noindent
22723 and trace the elaboration routine for this package to find out where
22724 the problem might be (more usually of course you would be debugging
22725 elaboration code in your own application).
22727 @node Elaboration Order Handling in GNAT
22728 @appendix Elaboration Order Handling in GNAT
22729 @cindex Order of elaboration
22730 @cindex Elaboration control
22732 @menu
22733 * Elaboration Code in Ada 95::
22734 * Checking the Elaboration Order in Ada 95::
22735 * Controlling the Elaboration Order in Ada 95::
22736 * Controlling Elaboration in GNAT - Internal Calls::
22737 * Controlling Elaboration in GNAT - External Calls::
22738 * Default Behavior in GNAT - Ensuring Safety::
22739 * Treatment of Pragma Elaborate::
22740 * Elaboration Issues for Library Tasks::
22741 * Mixing Elaboration Models::
22742 * What to Do If the Default Elaboration Behavior Fails::
22743 * Elaboration for Access-to-Subprogram Values::
22744 * Summary of Procedures for Elaboration Control::
22745 * Other Elaboration Order Considerations::
22746 @end menu
22748 @noindent
22749 This chapter describes the handling of elaboration code in Ada 95 and
22750 in GNAT, and discusses how the order of elaboration of program units can
22751 be controlled in GNAT, either automatically or with explicit programming
22752 features.
22754 @node Elaboration Code in Ada 95
22755 @section Elaboration Code in Ada 95
22757 @noindent
22758 Ada 95 provides rather general mechanisms for executing code at elaboration
22759 time, that is to say before the main program starts executing. Such code arises
22760 in three contexts:
22762 @table @asis
22763 @item Initializers for variables.
22764 Variables declared at the library level, in package specs or bodies, can
22765 require initialization that is performed at elaboration time, as in:
22766 @smallexample @c ada
22767 @cartouche
22768 Sqrt_Half : Float := Sqrt (0.5);
22769 @end cartouche
22770 @end smallexample
22772 @item Package initialization code
22773 Code in a @code{BEGIN-END} section at the outer level of a package body is
22774 executed as part of the package body elaboration code.
22776 @item Library level task allocators
22777 Tasks that are declared using task allocators at the library level
22778 start executing immediately and hence can execute at elaboration time.
22779 @end table
22781 @noindent
22782 Subprogram calls are possible in any of these contexts, which means that
22783 any arbitrary part of the program may be executed as part of the elaboration
22784 code. It is even possible to write a program which does all its work at
22785 elaboration time, with a null main program, although stylistically this
22786 would usually be considered an inappropriate way to structure
22787 a program.
22789 An important concern arises in the context of elaboration code:
22790 we have to be sure that it is executed in an appropriate order. What we
22791 have is a series of elaboration code sections, potentially one section
22792 for each unit in the program. It is important that these execute
22793 in the correct order. Correctness here means that, taking the above
22794 example of the declaration of @code{Sqrt_Half},
22795 if some other piece of
22796 elaboration code references @code{Sqrt_Half},
22797 then it must run after the
22798 section of elaboration code that contains the declaration of
22799 @code{Sqrt_Half}.
22801 There would never be any order of elaboration problem if we made a rule
22802 that whenever you @code{with} a unit, you must elaborate both the spec and body
22803 of that unit before elaborating the unit doing the @code{with}'ing:
22805 @smallexample @c ada
22806 @group
22807 @cartouche
22808 with Unit_1;
22809 package Unit_2 is ...
22810 @end cartouche
22811 @end group
22812 @end smallexample
22814 @noindent
22815 would require that both the body and spec of @code{Unit_1} be elaborated
22816 before the spec of @code{Unit_2}. However, a rule like that would be far too
22817 restrictive. In particular, it would make it impossible to have routines
22818 in separate packages that were mutually recursive.
22820 You might think that a clever enough compiler could look at the actual
22821 elaboration code and determine an appropriate correct order of elaboration,
22822 but in the general case, this is not possible. Consider the following
22823 example.
22825 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22826 that references
22827 the variable @code{Sqrt_1}, which is declared in the elaboration code
22828 of the body of @code{Unit_1}:
22830 @smallexample @c ada
22831 @cartouche
22832 Sqrt_1 : Float := Sqrt (0.1);
22833 @end cartouche
22834 @end smallexample
22836 @noindent
22837 The elaboration code of the body of @code{Unit_1} also contains:
22839 @smallexample @c ada
22840 @group
22841 @cartouche
22842 if expression_1 = 1 then
22843    Q := Unit_2.Func_2;
22844 end if;
22845 @end cartouche
22846 @end group
22847 @end smallexample
22849 @noindent
22850 @code{Unit_2} is exactly parallel,
22851 it has a procedure @code{Func_2} that references
22852 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22853 the body @code{Unit_2}:
22855 @smallexample @c ada
22856 @cartouche
22857 Sqrt_2 : Float := Sqrt (0.1);
22858 @end cartouche
22859 @end smallexample
22861 @noindent
22862 The elaboration code of the body of @code{Unit_2} also contains:
22864 @smallexample @c ada
22865 @group
22866 @cartouche
22867 if expression_2 = 2 then
22868    Q := Unit_1.Func_1;
22869 end if;
22870 @end cartouche
22871 @end group
22872 @end smallexample
22874 @noindent
22875 Now the question is, which of the following orders of elaboration is
22876 acceptable:
22878 @smallexample
22879 @group
22880 Spec of Unit_1
22881 Spec of Unit_2
22882 Body of Unit_1
22883 Body of Unit_2
22884 @end group
22885 @end smallexample
22887 @noindent
22890 @smallexample
22891 @group
22892 Spec of Unit_2
22893 Spec of Unit_1
22894 Body of Unit_2
22895 Body of Unit_1
22896 @end group
22897 @end smallexample
22899 @noindent
22900 If you carefully analyze the flow here, you will see that you cannot tell
22901 at compile time the answer to this question.
22902 If @code{expression_1} is not equal to 1,
22903 and @code{expression_2} is not equal to 2,
22904 then either order is acceptable, because neither of the function calls is
22905 executed. If both tests evaluate to true, then neither order is acceptable
22906 and in fact there is no correct order.
22908 If one of the two expressions is true, and the other is false, then one
22909 of the above orders is correct, and the other is incorrect. For example,
22910 if @code{expression_1} = 1 and @code{expression_2} /= 2,
22911 then the call to @code{Func_2}
22912 will occur, but not the call to @code{Func_1.}
22913 This means that it is essential
22914 to elaborate the body of @code{Unit_1} before
22915 the body of @code{Unit_2}, so the first
22916 order of elaboration is correct and the second is wrong.
22918 By making @code{expression_1} and @code{expression_2}
22919 depend on input data, or perhaps
22920 the time of day, we can make it impossible for the compiler or binder
22921 to figure out which of these expressions will be true, and hence it
22922 is impossible to guarantee a safe order of elaboration at run time.
22924 @node Checking the Elaboration Order in Ada 95
22925 @section Checking the Elaboration Order in Ada 95
22927 @noindent
22928 In some languages that involve the same kind of elaboration problems,
22929 e.g. Java and C++, the programmer is expected to worry about these
22930 ordering problems himself, and it is common to
22931 write a program in which an incorrect elaboration order  gives
22932 surprising results, because it references variables before they
22933 are initialized.
22934 Ada 95 is designed to be a safe language, and a programmer-beware approach is
22935 clearly not sufficient. Consequently, the language provides three lines
22936 of defense:
22938 @table @asis
22939 @item Standard rules
22940 Some standard rules restrict the possible choice of elaboration
22941 order. In particular, if you @code{with} a unit, then its spec is always
22942 elaborated before the unit doing the @code{with}. Similarly, a parent
22943 spec is always elaborated before the child spec, and finally
22944 a spec is always elaborated before its corresponding body.
22946 @item Dynamic elaboration checks
22947 @cindex Elaboration checks
22948 @cindex Checks, elaboration
22949 Dynamic checks are made at run time, so that if some entity is accessed
22950 before it is elaborated (typically  by means of a subprogram call)
22951 then the exception (@code{Program_Error}) is raised.
22953 @item Elaboration control
22954 Facilities are provided for the programmer to specify the desired order
22955 of elaboration.
22956 @end table
22958 Let's look at these facilities in more detail. First, the rules for
22959 dynamic checking. One possible rule would be simply to say that the
22960 exception is raised if you access a variable which has not yet been
22961 elaborated. The trouble with this approach is that it could require
22962 expensive checks on every variable reference. Instead Ada 95 has two
22963 rules which are a little more restrictive, but easier to check, and
22964 easier to state:
22966 @table @asis
22967 @item Restrictions on calls
22968 A subprogram can only be called at elaboration time if its body
22969 has been elaborated. The rules for elaboration given above guarantee
22970 that the spec of the subprogram has been elaborated before the
22971 call, but not the body. If this rule is violated, then the
22972 exception @code{Program_Error} is raised.
22974 @item Restrictions on instantiations
22975 A generic unit can only be instantiated if the body of the generic
22976 unit has been elaborated. Again, the rules for elaboration given above
22977 guarantee that the spec of the generic unit has been elaborated
22978 before the instantiation, but not the body. If this rule is
22979 violated, then the exception @code{Program_Error} is raised.
22980 @end table
22982 @noindent
22983 The idea is that if the body has been elaborated, then any variables
22984 it references must have been elaborated; by checking for the body being
22985 elaborated we guarantee that none of its references causes any
22986 trouble. As we noted above, this is a little too restrictive, because a
22987 subprogram that has no non-local references in its body may in fact be safe
22988 to call. However, it really would be unsafe to rely on this, because
22989 it would mean that the caller was aware of details of the implementation
22990 in the body. This goes against the basic tenets of Ada.
22992 A plausible implementation can be described as follows.
22993 A Boolean variable is associated with each subprogram
22994 and each generic unit. This variable is initialized to False, and is set to
22995 True at the point body is elaborated. Every call or instantiation checks the
22996 variable, and raises @code{Program_Error} if the variable is False.
22998 Note that one might think that it would be good enough to have one Boolean
22999 variable for each package, but that would not deal with cases of trying
23000 to call a body in the same package as the call
23001 that has not been elaborated yet.
23002 Of course a compiler may be able to do enough analysis to optimize away
23003 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
23004 does such optimizations, but still the easiest conceptual model is to
23005 think of there being one variable per subprogram.
23007 @node Controlling the Elaboration Order in Ada 95
23008 @section Controlling the Elaboration Order in Ada 95
23010 @noindent
23011 In the previous section we discussed the rules in Ada 95 which ensure
23012 that @code{Program_Error} is raised if an incorrect elaboration order is
23013 chosen. This prevents erroneous executions, but we need mechanisms to
23014 specify a correct execution and avoid the exception altogether.
23015 To achieve this, Ada 95 provides a number of features for controlling
23016 the order of elaboration. We discuss these features in this section.
23018 First, there are several ways of indicating to the compiler that a given
23019 unit has no elaboration problems:
23021 @table @asis
23022 @item packages that do not require a body
23023 In Ada 95, a library package that does not require a body does not permit
23024 a body. This means that if we have a such a package, as in:
23026 @smallexample @c ada
23027 @group
23028 @cartouche
23029 package Definitions is
23030    generic
23031       type m is new integer;
23032    package Subp is
23033       type a is array (1 .. 10) of m;
23034       type b is array (1 .. 20) of m;
23035    end Subp;
23036 end Definitions;
23037 @end cartouche
23038 @end group
23039 @end smallexample
23041 @noindent
23042 A package that @code{with}'s @code{Definitions} may safely instantiate
23043 @code{Definitions.Subp} because the compiler can determine that there
23044 definitely is no package body to worry about in this case
23046 @item pragma Pure
23047 @cindex pragma Pure
23048 @findex Pure
23049 Places sufficient restrictions on a unit to guarantee that
23050 no call to any subprogram in the unit can result in an
23051 elaboration problem. This means that the compiler does not need
23052 to worry about the point of elaboration of such units, and in
23053 particular, does not need to check any calls to any subprograms
23054 in this unit.
23056 @item pragma Preelaborate
23057 @findex Preelaborate
23058 @cindex pragma Preelaborate
23059 This pragma places slightly less stringent restrictions on a unit than
23060 does pragma Pure,
23061 but these restrictions are still sufficient to ensure that there
23062 are no elaboration problems with any calls to the unit.
23064 @item pragma Elaborate_Body
23065 @findex Elaborate_Body
23066 @cindex pragma Elaborate_Body
23067 This pragma requires that the body of a unit be elaborated immediately
23068 after its spec. Suppose a unit @code{A} has such a pragma,
23069 and unit @code{B} does
23070 a @code{with} of unit @code{A}. Recall that the standard rules require
23071 the spec of unit @code{A}
23072 to be elaborated before the @code{with}'ing unit; given the pragma in
23073 @code{A}, we also know that the body of @code{A}
23074 will be elaborated before @code{B}, so
23075 that calls to @code{A} are safe and do not need a check.
23076 @end table
23078 @noindent
23079 Note that,
23080 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23081 the use of
23082 @code{Elaborate_Body} does not guarantee that the program is
23083 free of elaboration problems, because it may not be possible
23084 to satisfy the requested elaboration order.
23085 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23086 If a programmer
23087 marks @code{Unit_1} as @code{Elaborate_Body},
23088 and not @code{Unit_2,} then the order of
23089 elaboration will be:
23091 @smallexample
23092 @group
23093 Spec of Unit_2
23094 Spec of Unit_1
23095 Body of Unit_1
23096 Body of Unit_2
23097 @end group
23098 @end smallexample
23100 @noindent
23101 Now that means that the call to @code{Func_1} in @code{Unit_2}
23102 need not be checked,
23103 it must be safe. But the call to @code{Func_2} in
23104 @code{Unit_1} may still fail if
23105 @code{Expression_1} is equal to 1,
23106 and the programmer must still take
23107 responsibility for this not being the case.
23109 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23110 eliminated, except for calls entirely within a body, which are
23111 in any case fully under programmer control. However, using the pragma
23112 everywhere is not always possible.
23113 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23114 we marked both of them as having pragma @code{Elaborate_Body}, then
23115 clearly there would be no possible elaboration order.
23117 The above pragmas allow a server to guarantee safe use by clients, and
23118 clearly this is the preferable approach. Consequently a good rule in
23119 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23120 and if this is not possible,
23121 mark them as @code{Elaborate_Body} if possible.
23122 As we have seen, there are situations where neither of these
23123 three pragmas can be used.
23124 So we also provide methods for clients to control the
23125 order of elaboration of the servers on which they depend:
23127 @table @asis
23128 @item pragma Elaborate (unit)
23129 @findex Elaborate
23130 @cindex pragma Elaborate
23131 This pragma is placed in the context clause, after a @code{with} clause,
23132 and it requires that the body of the named unit be elaborated before
23133 the unit in which the pragma occurs. The idea is to use this pragma
23134 if the current unit calls at elaboration time, directly or indirectly,
23135 some subprogram in the named unit.
23137 @item pragma Elaborate_All (unit)
23138 @findex Elaborate_All
23139 @cindex pragma Elaborate_All
23140 This is a stronger version of the Elaborate pragma. Consider the
23141 following example:
23143 @smallexample
23144 Unit A @code{with}'s unit B and calls B.Func in elab code
23145 Unit B @code{with}'s unit C, and B.Func calls C.Func
23146 @end smallexample
23148 @noindent
23149 Now if we put a pragma @code{Elaborate (B)}
23150 in unit @code{A}, this ensures that the
23151 body of @code{B} is elaborated before the call, but not the
23152 body of @code{C}, so
23153 the call to @code{C.Func} could still cause @code{Program_Error} to
23154 be raised.
23156 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23157 not only that the body of the named unit be elaborated before the
23158 unit doing the @code{with}, but also the bodies of all units that the
23159 named unit uses, following @code{with} links transitively. For example,
23160 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23161 then it requires
23162 not only that the body of @code{B} be elaborated before @code{A},
23163 but also the
23164 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23165 @end table
23167 @noindent
23168 We are now in a position to give a usage rule in Ada 95 for avoiding
23169 elaboration problems, at least if dynamic dispatching and access to
23170 subprogram values are not used. We will handle these cases separately
23171 later.
23173 The rule is simple. If a unit has elaboration code that can directly or
23174 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23175 a generic unit in a @code{with}'ed unit,
23176 then if the @code{with}'ed unit does not have
23177 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23178 a pragma @code{Elaborate_All}
23179 for the @code{with}'ed unit. By following this rule a client is
23180 assured that calls can be made without risk of an exception.
23181 If this rule is not followed, then a program may be in one of four
23182 states:
23184 @table @asis
23185 @item No order exists
23186 No order of elaboration exists which follows the rules, taking into
23187 account any @code{Elaborate}, @code{Elaborate_All},
23188 or @code{Elaborate_Body} pragmas. In
23189 this case, an Ada 95 compiler must diagnose the situation at bind
23190 time, and refuse to build an executable program.
23192 @item One or more orders exist, all incorrect
23193 One or more acceptable elaboration orders exists, and all of them
23194 generate an elaboration order problem. In this case, the binder
23195 can build an executable program, but @code{Program_Error} will be raised
23196 when the program is run.
23198 @item Several orders exist, some right, some incorrect
23199 One or more acceptable elaboration orders exists, and some of them
23200 work, and some do not. The programmer has not controlled
23201 the order of elaboration, so the binder may or may not pick one of
23202 the correct orders, and the program may or may not raise an
23203 exception when it is run. This is the worst case, because it means
23204 that the program may fail when moved to another compiler, or even
23205 another version of the same compiler.
23207 @item One or more orders exists, all correct
23208 One ore more acceptable elaboration orders exist, and all of them
23209 work. In this case the program runs successfully. This state of
23210 affairs can be guaranteed by following the rule we gave above, but
23211 may be true even if the rule is not followed.
23212 @end table
23214 @noindent
23215 Note that one additional advantage of following our Elaborate_All rule
23216 is that the program continues to stay in the ideal (all orders OK) state
23217 even if maintenance
23218 changes some bodies of some subprograms. Conversely, if a program that does
23219 not follow this rule happens to be safe at some point, this state of affairs
23220 may deteriorate silently as a result of maintenance changes.
23222 You may have noticed that the above discussion did not mention
23223 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23224 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23225 code in the body makes calls to some other unit, so it is still necessary
23226 to use @code{Elaborate_All} on such units.
23228 @node Controlling Elaboration in GNAT - Internal Calls
23229 @section Controlling Elaboration in GNAT - Internal Calls
23231 @noindent
23232 In the case of internal calls, i.e. calls within a single package, the
23233 programmer has full control over the order of elaboration, and it is up
23234 to the programmer to elaborate declarations in an appropriate order. For
23235 example writing:
23237 @smallexample @c ada
23238 @group
23239 @cartouche
23240 function One return Float;
23242 Q : Float := One;
23244 function One return Float is
23245 begin
23246      return 1.0;
23247 end One;
23248 @end cartouche
23249 @end group
23250 @end smallexample
23252 @noindent
23253 will obviously raise @code{Program_Error} at run time, because function
23254 One will be called before its body is elaborated. In this case GNAT will
23255 generate a warning that the call will raise @code{Program_Error}:
23257 @smallexample
23258 @group
23259 @cartouche
23260  1. procedure y is
23261  2.    function One return Float;
23262  3.
23263  4.    Q : Float := One;
23264                     |
23265     >>> warning: cannot call "One" before body is elaborated
23266     >>> warning: Program_Error will be raised at run time
23268  5.
23269  6.    function One return Float is
23270  7.    begin
23271  8.         return 1.0;
23272  9.    end One;
23274 11. begin
23275 12.    null;
23276 13. end;
23277 @end cartouche
23278 @end group
23279 @end smallexample
23281 @noindent
23282 Note that in this particular case, it is likely that the call is safe, because
23283 the function @code{One} does not access any global variables.
23284 Nevertheless in Ada 95, we do not want the validity of the check to depend on
23285 the contents of the body (think about the separate compilation case), so this
23286 is still wrong, as we discussed in the previous sections.
23288 The error is easily corrected by rearranging the declarations so that the
23289 body of One appears before the declaration containing the call
23290 (note that in Ada 95,
23291 declarations can appear in any order, so there is no restriction that
23292 would prevent this reordering, and if we write:
23294 @smallexample @c ada
23295 @group
23296 @cartouche
23297 function One return Float;
23299 function One return Float is
23300 begin
23301      return 1.0;
23302 end One;
23304 Q : Float := One;
23305 @end cartouche
23306 @end group
23307 @end smallexample
23309 @noindent
23310 then all is well, no warning is generated, and no
23311 @code{Program_Error} exception
23312 will be raised.
23313 Things are more complicated when a chain of subprograms is executed:
23315 @smallexample @c ada
23316 @group
23317 @cartouche
23318 function A return Integer;
23319 function B return Integer;
23320 function C return Integer;
23322 function B return Integer is begin return A; end;
23323 function C return Integer is begin return B; end;
23325 X : Integer := C;
23327 function A return Integer is begin return 1; end;
23328 @end cartouche
23329 @end group
23330 @end smallexample
23332 @noindent
23333 Now the call to @code{C}
23334 at elaboration time in the declaration of @code{X} is correct, because
23335 the body of @code{C} is already elaborated,
23336 and the call to @code{B} within the body of
23337 @code{C} is correct, but the call
23338 to @code{A} within the body of @code{B} is incorrect, because the body
23339 of @code{A} has not been elaborated, so @code{Program_Error}
23340 will be raised on the call to @code{A}.
23341 In this case GNAT will generate a
23342 warning that @code{Program_Error} may be
23343 raised at the point of the call. Let's look at the warning:
23345 @smallexample
23346 @group
23347 @cartouche
23348  1. procedure x is
23349  2.    function A return Integer;
23350  3.    function B return Integer;
23351  4.    function C return Integer;
23352  5.
23353  6.    function B return Integer is begin return A; end;
23354                                                     |
23355     >>> warning: call to "A" before body is elaborated may
23356                  raise Program_Error
23357     >>> warning: "B" called at line 7
23358     >>> warning: "C" called at line 9
23360  7.    function C return Integer is begin return B; end;
23361  8.
23362  9.    X : Integer := C;
23364 11.    function A return Integer is begin return 1; end;
23366 13. begin
23367 14.    null;
23368 15. end;
23369 @end cartouche
23370 @end group
23371 @end smallexample
23373 @noindent
23374 Note that the message here says ``may raise'', instead of the direct case,
23375 where the message says ``will be raised''. That's because whether
23376 @code{A} is
23377 actually called depends in general on run-time flow of control.
23378 For example, if the body of @code{B} said
23380 @smallexample @c ada
23381 @group
23382 @cartouche
23383 function B return Integer is
23384 begin
23385    if some-condition-depending-on-input-data then
23386       return A;
23387    else
23388       return 1;
23389    end if;
23390 end B;
23391 @end cartouche
23392 @end group
23393 @end smallexample
23395 @noindent
23396 then we could not know until run time whether the incorrect call to A would
23397 actually occur, so @code{Program_Error} might
23398 or might not be raised. It is possible for a compiler to
23399 do a better job of analyzing bodies, to
23400 determine whether or not @code{Program_Error}
23401 might be raised, but it certainly
23402 couldn't do a perfect job (that would require solving the halting problem
23403 and is provably impossible), and because this is a warning anyway, it does
23404 not seem worth the effort to do the analysis. Cases in which it
23405 would be relevant are rare.
23407 In practice, warnings of either of the forms given
23408 above will usually correspond to
23409 real errors, and should be examined carefully and eliminated.
23410 In the rare case where a warning is bogus, it can be suppressed by any of
23411 the following methods:
23413 @itemize @bullet
23414 @item
23415 Compile with the @option{-gnatws} switch set
23417 @item
23418 Suppress @code{Elaboration_Check} for the called subprogram
23420 @item
23421 Use pragma @code{Warnings_Off} to turn warnings off for the call
23422 @end itemize
23424 @noindent
23425 For the internal elaboration check case,
23426 GNAT by default generates the
23427 necessary run-time checks to ensure
23428 that @code{Program_Error} is raised if any
23429 call fails an elaboration check. Of course this can only happen if a
23430 warning has been issued as described above. The use of pragma
23431 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23432 some of these checks, meaning that it may be possible (but is not
23433 guaranteed) for a program to be able to call a subprogram whose body
23434 is not yet elaborated, without raising a @code{Program_Error} exception.
23436 @node Controlling Elaboration in GNAT - External Calls
23437 @section Controlling Elaboration in GNAT - External Calls
23439 @noindent
23440 The previous section discussed the case in which the execution of a
23441 particular thread of elaboration code occurred entirely within a
23442 single unit. This is the easy case to handle, because a programmer
23443 has direct and total control over the order of elaboration, and
23444 furthermore, checks need only be generated in cases which are rare
23445 and which the compiler can easily detect.
23446 The situation is more complex when separate compilation is taken into account.
23447 Consider the following:
23449 @smallexample @c ada
23450 @cartouche
23451 @group
23452 package Math is
23453    function Sqrt (Arg : Float) return Float;
23454 end Math;
23456 package body Math is
23457    function Sqrt (Arg : Float) return Float is
23458    begin
23459          ...
23460    end Sqrt;
23461 end Math;
23462 @end group
23463 @group
23464 with Math;
23465 package Stuff is
23466    X : Float := Math.Sqrt (0.5);
23467 end Stuff;
23469 with Stuff;
23470 procedure Main is
23471 begin
23472    ...
23473 end Main;
23474 @end group
23475 @end cartouche
23476 @end smallexample
23478 @noindent
23479 where @code{Main} is the main program. When this program is executed, the
23480 elaboration code must first be executed, and one of the jobs of the
23481 binder is to determine the order in which the units of a program are
23482 to be elaborated. In this case we have four units: the spec and body
23483 of @code{Math},
23484 the spec of @code{Stuff} and the body of @code{Main}).
23485 In what order should the four separate sections of elaboration code
23486 be executed?
23488 There are some restrictions in the order of elaboration that the binder
23489 can choose. In particular, if unit U has a @code{with}
23490 for a package @code{X}, then you
23491 are assured that the spec of @code{X}
23492 is elaborated before U , but you are
23493 not assured that the body of @code{X}
23494 is elaborated before U.
23495 This means that in the above case, the binder is allowed to choose the
23496 order:
23498 @smallexample
23499 spec of Math
23500 spec of Stuff
23501 body of Math
23502 body of Main
23503 @end smallexample
23505 @noindent
23506 but that's not good, because now the call to @code{Math.Sqrt}
23507 that happens during
23508 the elaboration of the @code{Stuff}
23509 spec happens before the body of @code{Math.Sqrt} is
23510 elaborated, and hence causes @code{Program_Error} exception to be raised.
23511 At first glance, one might say that the binder is misbehaving, because
23512 obviously you want to elaborate the body of something you @code{with}
23513 first, but
23514 that is not a general rule that can be followed in all cases. Consider
23516 @smallexample @c ada
23517 @group
23518 @cartouche
23519 package X is ...
23521 package Y is ...
23523 with X;
23524 package body Y is ...
23526 with Y;
23527 package body X is ...
23528 @end cartouche
23529 @end group
23530 @end smallexample
23532 @noindent
23533 This is a common arrangement, and, apart from the order of elaboration
23534 problems that might arise in connection with elaboration code, this works fine.
23535 A rule that says that you must first elaborate the body of anything you
23536 @code{with} cannot work in this case:
23537 the body of @code{X} @code{with}'s @code{Y},
23538 which means you would have to
23539 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23540 which means
23541 you have to elaborate the body of @code{X} first, but ... and we have a
23542 loop that cannot be broken.
23544 It is true that the binder can in many cases guess an order of elaboration
23545 that is unlikely to cause a @code{Program_Error}
23546 exception to be raised, and it tries to do so (in the
23547 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23548 by default
23549 elaborate the body of @code{Math} right after its spec, so all will be well).
23551 However, a program that blindly relies on the binder to be helpful can
23552 get into trouble, as we discussed in the previous sections, so
23553 GNAT
23554 provides a number of facilities for assisting the programmer in
23555 developing programs that are robust with respect to elaboration order.
23557 @node Default Behavior in GNAT - Ensuring Safety
23558 @section Default Behavior in GNAT - Ensuring Safety
23560 @noindent
23561 The default behavior in GNAT ensures elaboration safety. In its
23562 default mode GNAT implements the
23563 rule we previously described as the right approach. Let's restate it:
23565 @itemize
23566 @item
23567 @emph{If a unit has elaboration code that can directly or indirectly make a
23568 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
23569 in a @code{with}'ed unit, then if the @code{with}'ed unit
23570 does not have pragma @code{Pure} or
23571 @code{Preelaborate}, then the client should have an
23572 @code{Elaborate_All} for the @code{with}'ed unit.}
23573 @end itemize
23575 @noindent
23576 By following this rule a client is assured that calls and instantiations
23577 can be made without risk of an exception.
23579 In this mode GNAT traces all calls that are potentially made from
23580 elaboration code, and puts in any missing implicit @code{Elaborate_All}
23581 pragmas.
23582 The advantage of this approach is that no elaboration problems
23583 are possible if the binder can find an elaboration order that is
23584 consistent with these implicit @code{Elaborate_All} pragmas. The
23585 disadvantage of this approach is that no such order may exist.
23587 If the binder does not generate any diagnostics, then it means that it
23588 has found an elaboration order that is guaranteed to be safe. However,
23589 the binder may still be relying on implicitly generated
23590 @code{Elaborate_All} pragmas so portability to other compilers than
23591 GNAT is not guaranteed.
23593 If it is important to guarantee portability, then the compilations should
23594 use the
23595 @option{-gnatwl}
23596 (warn on elaboration problems) switch. This will cause warning messages
23597 to be generated indicating the missing @code{Elaborate_All} pragmas.
23598 Consider the following source program:
23600 @smallexample @c ada
23601 @group
23602 @cartouche
23603 with k;
23604 package j is
23605   m : integer := k.r;
23606 end;
23607 @end cartouche
23608 @end group
23609 @end smallexample
23611 @noindent
23612 where it is clear that there
23613 should be a pragma @code{Elaborate_All}
23614 for unit @code{k}. An implicit pragma will be generated, and it is
23615 likely that the binder will be able to honor it. However, if you want
23616 to port this program to some other Ada compiler than GNAT.
23617 it is safer to include the pragma explicitly in the source. If this
23618 unit is compiled with the
23619 @option{-gnatwl}
23620 switch, then the compiler outputs a warning:
23622 @smallexample
23623 @group
23624 @cartouche
23625 1. with k;
23626 2. package j is
23627 3.   m : integer := k.r;
23628                      |
23629    >>> warning: call to "r" may raise Program_Error
23630    >>> warning: missing pragma Elaborate_All for "k"
23632 4. end;
23633 @end cartouche
23634 @end group
23635 @end smallexample
23637 @noindent
23638 and these warnings can be used as a guide for supplying manually
23639 the missing pragmas. It is usually a bad idea to use this warning
23640 option during development. That's because it will warn you when
23641 you need to put in a pragma, but cannot warn you when it is time
23642 to take it out. So the use of pragma Elaborate_All may lead to
23643 unnecessary dependencies and even false circularities.
23645 This default mode is more restrictive than the Ada Reference
23646 Manual, and it is possible to construct programs which will compile
23647 using the dynamic model described there, but will run into a
23648 circularity using the safer static model we have described.
23650 Of course any Ada compiler must be able to operate in a mode
23651 consistent with the requirements of the Ada Reference Manual,
23652 and in particular must have the capability of implementing the
23653 standard dynamic model of elaboration with run-time checks.
23655 In GNAT, this standard mode can be achieved either by the use of
23656 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
23657 command, or by the use of the configuration pragma:
23659 @smallexample @c ada
23660 pragma Elaboration_Checks (RM);
23661 @end smallexample
23663 @noindent
23664 Either approach will cause the unit affected to be compiled using the
23665 standard dynamic run-time elaboration checks described in the Ada
23666 Reference Manual. The static model is generally preferable, since it
23667 is clearly safer to rely on compile and link time checks rather than
23668 run-time checks. However, in the case of legacy code, it may be
23669 difficult to meet the requirements of the static model. This
23670 issue is further discussed in
23671 @ref{What to Do If the Default Elaboration Behavior Fails}.
23673 Note that the static model provides a strict subset of the allowed
23674 behavior and programs of the Ada Reference Manual, so if you do
23675 adhere to the static model and no circularities exist,
23676 then you are assured that your program will
23677 work using the dynamic model, providing that you remove any
23678 pragma Elaborate statements from the source.
23680 @node Treatment of Pragma Elaborate
23681 @section Treatment of Pragma Elaborate
23682 @cindex Pragma Elaborate
23684 @noindent
23685 The use of @code{pragma Elaborate}
23686 should generally be avoided in Ada 95 programs.
23687 The reason for this is that there is no guarantee that transitive calls
23688 will be properly handled. Indeed at one point, this pragma was placed
23689 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23691 Now that's a bit restrictive. In practice, the case in which
23692 @code{pragma Elaborate} is useful is when the caller knows that there
23693 are no transitive calls, or that the called unit contains all necessary
23694 transitive @code{pragma Elaborate} statements, and legacy code often
23695 contains such uses.
23697 Strictly speaking the static mode in GNAT should ignore such pragmas,
23698 since there is no assurance at compile time that the necessary safety
23699 conditions are met. In practice, this would cause GNAT to be incompatible
23700 with correctly written Ada 83 code that had all necessary
23701 @code{pragma Elaborate} statements in place. Consequently, we made the
23702 decision that GNAT in its default mode will believe that if it encounters
23703 a @code{pragma Elaborate} then the programmer knows what they are doing,
23704 and it will trust that no elaboration errors can occur.
23706 The result of this decision is two-fold. First to be safe using the
23707 static mode, you should remove all @code{pragma Elaborate} statements.
23708 Second, when fixing circularities in existing code, you can selectively
23709 use @code{pragma Elaborate} statements to convince the static mode of
23710 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23711 statement.
23713 When using the static mode with @option{-gnatwl}, any use of
23714 @code{pragma Elaborate} will generate a warning about possible
23715 problems.
23717 @node Elaboration Issues for Library Tasks
23718 @section Elaboration Issues for Library Tasks
23719 @cindex Library tasks, elaboration issues
23720 @cindex Elaboration of library tasks
23722 @noindent
23723 In this section we examine special elaboration issues that arise for
23724 programs that declare library level tasks.
23726 Generally the model of execution of an Ada program is that all units are
23727 elaborated, and then execution of the program starts. However, the
23728 declaration of library tasks definitely does not fit this model. The
23729 reason for this is that library tasks start as soon as they are declared
23730 (more precisely, as soon as the statement part of the enclosing package
23731 body is reached), that is to say before elaboration
23732 of the program is complete. This means that if such a task calls a
23733 subprogram, or an entry in another task, the callee may or may not be
23734 elaborated yet, and in the standard
23735 Reference Manual model of dynamic elaboration checks, you can even
23736 get timing dependent Program_Error exceptions, since there can be
23737 a race between the elaboration code and the task code.
23739 The static model of elaboration in GNAT seeks to avoid all such
23740 dynamic behavior, by being conservative, and the conservative
23741 approach in this particular case is to assume that all the code
23742 in a task body is potentially executed at elaboration time if
23743 a task is declared at the library level.
23745 This can definitely result in unexpected circularities. Consider
23746 the following example
23748 @smallexample @c ada
23749 package Decls is
23750   task Lib_Task is
23751      entry Start;
23752   end Lib_Task;
23754   type My_Int is new Integer;
23756   function Ident (M : My_Int) return My_Int;
23757 end Decls;
23759 with Utils;
23760 package body Decls is
23761   task body Lib_Task is
23762   begin
23763      accept Start;
23764      Utils.Put_Val (2);
23765   end Lib_Task;
23767   function Ident (M : My_Int) return My_Int is
23768   begin
23769      return M;
23770   end Ident;
23771 end Decls;
23773 with Decls;
23774 package Utils is
23775   procedure Put_Val (Arg : Decls.My_Int);
23776 end Utils;
23778 with Text_IO;
23779 package body Utils is
23780   procedure Put_Val (Arg : Decls.My_Int) is
23781   begin
23782      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23783   end Put_Val;
23784 end Utils;
23786 with Decls;
23787 procedure Main is
23788 begin
23789    Decls.Lib_Task.Start;
23790 end;
23791 @end smallexample
23793 @noindent
23794 If the above example is compiled in the default static elaboration
23795 mode, then a circularity occurs. The circularity comes from the call
23796 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23797 this call occurs in elaboration code, we need an implicit pragma
23798 @code{Elaborate_All} for @code{Utils}. This means that not only must
23799 the spec and body of @code{Utils} be elaborated before the body
23800 of @code{Decls}, but also the spec and body of any unit that is
23801 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23802 the body of @code{Decls}. This is the transitive implication of
23803 pragma @code{Elaborate_All} and it makes sense, because in general
23804 the body of @code{Put_Val} might have a call to something in a
23805 @code{with'ed} unit.
23807 In this case, the body of Utils (actually its spec) @code{with's}
23808 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23809 must be elaborated before itself, in case there is a call from the
23810 body of @code{Utils}.
23812 Here is the exact chain of events we are worrying about:
23814 @enumerate
23815 @item
23816 In the body of @code{Decls} a call is made from within the body of a library
23817 task to a subprogram in the package @code{Utils}. Since this call may
23818 occur at elaboration time (given that the task is activated at elaboration
23819 time), we have to assume the worst, i.e. that the
23820 call does happen at elaboration time.
23822 @item
23823 This means that the body and spec of @code{Util} must be elaborated before
23824 the body of @code{Decls} so that this call does not cause an access before
23825 elaboration.
23827 @item
23828 Within the body of @code{Util}, specifically within the body of
23829 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23830 by this package.
23832 @item
23833 One such @code{with}'ed package is package @code{Decls}, so there
23834 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23835 In fact there is such a call in this example, but we would have to
23836 assume that there was such a call even if it were not there, since
23837 we are not supposed to write the body of @code{Decls} knowing what
23838 is in the body of @code{Utils}; certainly in the case of the
23839 static elaboration model, the compiler does not know what is in
23840 other bodies and must assume the worst.
23842 @item
23843 This means that the spec and body of @code{Decls} must also be
23844 elaborated before we elaborate the unit containing the call, but
23845 that unit is @code{Decls}! This means that the body of @code{Decls}
23846 must be elaborated before itself, and that's a circularity.
23847 @end enumerate
23849 @noindent
23850 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
23851 the body of @code{Decls} you will get a true Ada Reference Manual
23852 circularity that makes the program illegal.
23854 In practice, we have found that problems with the static model of
23855 elaboration in existing code often arise from library tasks, so
23856 we must address this particular situation.
23858 Note that if we compile and run the program above, using the dynamic model of
23859 elaboration (that is to say use the @option{-gnatE} switch),
23860 then it compiles, binds,
23861 links, and runs, printing the expected result of 2. Therefore in some sense
23862 the circularity here is only apparent, and we need to capture
23863 the properties of this program that  distinguish it from other library-level
23864 tasks that have real elaboration problems.
23866 We have four possible answers to this question:
23868 @itemize @bullet
23870 @item
23871 Use the dynamic model of elaboration.
23873 If we use the @option{-gnatE} switch, then as noted above, the program works.
23874 Why is this? If we examine the task body, it is apparent that the task cannot
23875 proceed past the
23876 @code{accept} statement until after elaboration has been completed, because
23877 the corresponding entry call comes from the main program, not earlier.
23878 This is why the dynamic model works here. But that's really giving
23879 up on a precise analysis, and we prefer to take this approach only if we cannot
23880 solve the
23881 problem in any other manner. So let us examine two ways to reorganize
23882 the program to avoid the potential elaboration problem.
23884 @item
23885 Split library tasks into separate packages.
23887 Write separate packages, so that library tasks are isolated from
23888 other declarations as much as possible. Let us look at a variation on
23889 the above program.
23891 @smallexample @c ada
23892 package Decls1 is
23893   task Lib_Task is
23894      entry Start;
23895   end Lib_Task;
23896 end Decls1;
23898 with Utils;
23899 package body Decls1 is
23900   task body Lib_Task is
23901   begin
23902      accept Start;
23903      Utils.Put_Val (2);
23904   end Lib_Task;
23905 end Decls1;
23907 package Decls2 is
23908   type My_Int is new Integer;
23909   function Ident (M : My_Int) return My_Int;
23910 end Decls2;
23912 with Utils;
23913 package body Decls2 is
23914   function Ident (M : My_Int) return My_Int is
23915   begin
23916      return M;
23917   end Ident;
23918 end Decls2;
23920 with Decls2;
23921 package Utils is
23922   procedure Put_Val (Arg : Decls2.My_Int);
23923 end Utils;
23925 with Text_IO;
23926 package body Utils is
23927   procedure Put_Val (Arg : Decls2.My_Int) is
23928   begin
23929      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23930   end Put_Val;
23931 end Utils;
23933 with Decls1;
23934 procedure Main is
23935 begin
23936    Decls1.Lib_Task.Start;
23937 end;
23938 @end smallexample
23940 @noindent
23941 All we have done is to split @code{Decls} into two packages, one
23942 containing the library task, and one containing everything else. Now
23943 there is no cycle, and the program compiles, binds, links and executes
23944 using the default static model of elaboration.
23946 @item
23947 Declare separate task types.
23949 A significant part of the problem arises because of the use of the
23950 single task declaration form. This means that the elaboration of
23951 the task type, and the elaboration of the task itself (i.e. the
23952 creation of the task) happen at the same time. A good rule
23953 of style in Ada 95 is to always create explicit task types. By
23954 following the additional step of placing task objects in separate
23955 packages from the task type declaration, many elaboration problems
23956 are avoided. Here is another modified example of the example program:
23958 @smallexample @c ada
23959 package Decls is
23960   task type Lib_Task_Type is
23961      entry Start;
23962   end Lib_Task_Type;
23964   type My_Int is new Integer;
23966   function Ident (M : My_Int) return My_Int;
23967 end Decls;
23969 with Utils;
23970 package body Decls is
23971   task body Lib_Task_Type is
23972   begin
23973      accept Start;
23974      Utils.Put_Val (2);
23975   end Lib_Task_Type;
23977   function Ident (M : My_Int) return My_Int is
23978   begin
23979      return M;
23980   end Ident;
23981 end Decls;
23983 with Decls;
23984 package Utils is
23985   procedure Put_Val (Arg : Decls.My_Int);
23986 end Utils;
23988 with Text_IO;
23989 package body Utils is
23990   procedure Put_Val (Arg : Decls.My_Int) is
23991   begin
23992      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23993   end Put_Val;
23994 end Utils;
23996 with Decls;
23997 package Declst is
23998    Lib_Task : Decls.Lib_Task_Type;
23999 end Declst;
24001 with Declst;
24002 procedure Main is
24003 begin
24004    Declst.Lib_Task.Start;
24005 end;
24006 @end smallexample
24008 @noindent
24009 What we have done here is to replace the @code{task} declaration in
24010 package @code{Decls} with a @code{task type} declaration. Then we
24011 introduce a separate package @code{Declst} to contain the actual
24012 task object. This separates the elaboration issues for
24013 the @code{task type}
24014 declaration, which causes no trouble, from the elaboration issues
24015 of the task object, which is also unproblematic, since it is now independent
24016 of the elaboration of  @code{Utils}.
24017 This separation of concerns also corresponds to
24018 a generally sound engineering principle of separating declarations
24019 from instances. This version of the program also compiles, binds, links,
24020 and executes, generating the expected output.
24022 @item
24023 Use No_Entry_Calls_In_Elaboration_Code restriction.
24024 @cindex No_Entry_Calls_In_Elaboration_Code
24026 The previous two approaches described how a program can be restructured
24027 to avoid the special problems caused by library task bodies. in practice,
24028 however, such restructuring may be difficult to apply to existing legacy code,
24029 so we must consider solutions that do not require massive rewriting.
24031 Let us consider more carefully why our original sample program works
24032 under the dynamic model of elaboration. The reason is that the code
24033 in the task body blocks immediately on the @code{accept}
24034 statement. Now of course there is nothing to prohibit elaboration
24035 code from making entry calls (for example from another library level task),
24036 so we cannot tell in isolation that
24037 the task will not execute the accept statement  during elaboration.
24039 However, in practice it is very unusual to see elaboration code
24040 make any entry calls, and the pattern of tasks starting
24041 at elaboration time and then immediately blocking on @code{accept} or
24042 @code{select} statements is very common. What this means is that
24043 the compiler is being too pessimistic when it analyzes the
24044 whole package body as though it might be executed at elaboration
24045 time.
24047 If we know that the elaboration code contains no entry calls, (a very safe
24048 assumption most of the time, that could almost be made the default
24049 behavior), then we can compile all units of the program under control
24050 of the following configuration pragma:
24052 @smallexample
24053 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24054 @end smallexample
24056 @noindent
24057 This pragma can be placed in the @file{gnat.adc} file in the usual
24058 manner. If we take our original unmodified program and compile it
24059 in the presence of a @file{gnat.adc} containing the above pragma,
24060 then once again, we can compile, bind, link, and execute, obtaining
24061 the expected result. In the presence of this pragma, the compiler does
24062 not trace calls in a task body, that appear after the first @code{accept}
24063 or @code{select} statement, and therefore does not report a potential
24064 circularity in the original program.
24066 The compiler will check to the extent it can that the above
24067 restriction is not violated, but it is not always possible to do a
24068 complete check at compile time, so it is important to use this
24069 pragma only if the stated restriction is in fact met, that is to say
24070 no task receives an entry call before elaboration of all units is completed.
24072 @end itemize
24074 @node Mixing Elaboration Models
24075 @section Mixing Elaboration Models
24076 @noindent
24077 So far, we have assumed that the entire program is either compiled
24078 using the dynamic model or static model, ensuring consistency. It
24079 is possible to mix the two models, but rules have to be followed
24080 if this mixing is done to ensure that elaboration checks are not
24081 omitted.
24083 The basic rule is that @emph{a unit compiled with the static model cannot
24084 be @code{with'ed} by a unit compiled with the dynamic model}. The
24085 reason for this is that in the static model, a unit assumes that
24086 its clients guarantee to use (the equivalent of) pragma
24087 @code{Elaborate_All} so that no elaboration checks are required
24088 in inner subprograms, and this assumption is violated if the
24089 client is compiled with dynamic checks.
24091 The precise rule is as follows. A unit that is compiled with dynamic
24092 checks can only @code{with} a unit that meets at least one of the
24093 following criteria:
24095 @itemize @bullet
24097 @item
24098 The @code{with'ed} unit is itself compiled with dynamic elaboration
24099 checks (that is with the @option{-gnatE} switch.
24101 @item
24102 The @code{with'ed} unit is an internal GNAT implementation unit from
24103 the System, Interfaces, Ada, or GNAT hierarchies.
24105 @item
24106 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24108 @item
24109 The @code{with'ing} unit (that is the client) has an explicit pragma
24110 @code{Elaborate_All} for the @code{with'ed} unit.
24112 @end itemize
24114 @noindent
24115 If this rule is violated, that is if a unit with dynamic elaboration
24116 checks @code{with's} a unit that does not meet one of the above four
24117 criteria, then the binder (@code{gnatbind}) will issue a warning
24118 similar to that in the following example:
24120 @smallexample
24121 warning: "x.ads" has dynamic elaboration checks and with's
24122 warning:   "y.ads" which has static elaboration checks
24123 @end smallexample
24125 @noindent
24126 These warnings indicate that the rule has been violated, and that as a result
24127 elaboration checks may be missed in the resulting executable file.
24128 This warning may be suppressed using the @option{-ws} binder switch
24129 in the usual manner.
24131 One useful application of this mixing rule is in the case of a subsystem
24132 which does not itself @code{with} units from the remainder of the
24133 application. In this case, the entire subsystem can be compiled with
24134 dynamic checks to resolve a circularity in the subsystem, while
24135 allowing the main application that uses this subsystem to be compiled
24136 using the more reliable default static model.
24138 @node What to Do If the Default Elaboration Behavior Fails
24139 @section What to Do If the Default Elaboration Behavior Fails
24141 @noindent
24142 If the binder cannot find an acceptable order, it outputs detailed
24143 diagnostics. For example:
24144 @smallexample
24145 @group
24146 @iftex
24147 @leftskip=0cm
24148 @end iftex
24149 error: elaboration circularity detected
24150 info:   "proc (body)" must be elaborated before "pack (body)"
24151 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24152 info:     recompile "pack (body)" with -gnatwl
24153 info:                             for full details
24154 info:       "proc (body)"
24155 info:         is needed by its spec:
24156 info:       "proc (spec)"
24157 info:         which is withed by:
24158 info:       "pack (body)"
24159 info:  "pack (body)" must be elaborated before "proc (body)"
24160 info:     reason: pragma Elaborate in unit "proc (body)"
24161 @end group
24163 @end smallexample
24165 @noindent
24166 In this case we have a cycle that the binder cannot break. On the one
24167 hand, there is an explicit pragma Elaborate in @code{proc} for
24168 @code{pack}. This means that the body of @code{pack} must be elaborated
24169 before the body of @code{proc}. On the other hand, there is elaboration
24170 code in @code{pack} that calls a subprogram in @code{proc}. This means
24171 that for maximum safety, there should really be a pragma
24172 Elaborate_All in @code{pack} for @code{proc} which would require that
24173 the body of @code{proc} be elaborated before the body of
24174 @code{pack}. Clearly both requirements cannot be satisfied.
24175 Faced with a circularity of this kind, you have three different options.
24177 @table @asis
24178 @item Fix the program
24179 The most desirable option from the point of view of long-term maintenance
24180 is to rearrange the program so that the elaboration problems are avoided.
24181 One useful technique is to place the elaboration code into separate
24182 child packages. Another is to move some of the initialization code to
24183 explicitly called subprograms, where the program controls the order
24184 of initialization explicitly. Although this is the most desirable option,
24185 it may be impractical and involve too much modification, especially in
24186 the case of complex legacy code.
24188 @item Perform dynamic checks
24189 If the compilations are done using the
24190 @option{-gnatE}
24191 (dynamic elaboration check) switch, then GNAT behaves in
24192 a quite different manner. Dynamic checks are generated for all calls
24193 that could possibly result in raising an exception. With this switch,
24194 the compiler does not generate implicit @code{Elaborate_All} pragmas.
24195 The behavior then is exactly as specified in the Ada 95 Reference Manual.
24196 The binder will generate an executable program that may or may not
24197 raise @code{Program_Error}, and then it is the programmer's job to ensure
24198 that it does not raise an exception. Note that it is important to
24199 compile all units with the switch, it cannot be used selectively.
24201 @item Suppress checks
24202 The drawback of dynamic checks is that they generate a
24203 significant overhead at run time, both in space and time. If you
24204 are absolutely sure that your program cannot raise any elaboration
24205 exceptions, and you still want to use the dynamic elaboration model,
24206 then you can use the configuration pragma
24207 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24208 example this pragma could be placed in the @file{gnat.adc} file.
24210 @item Suppress checks selectively
24211 When you know that certain calls in elaboration code cannot possibly
24212 lead to an elaboration error, and the binder nevertheless generates warnings
24213 on those calls and inserts Elaborate_All pragmas that lead to elaboration
24214 circularities, it is possible to remove those warnings locally and obtain
24215 a program that will bind. Clearly this can be unsafe, and it is the
24216 responsibility of the programmer to make sure that the resulting program has
24217 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
24218 be used with different granularity to suppress warnings and break
24219 elaboration circularities:
24221 @itemize @bullet
24222 @item
24223 Place the pragma that names the called subprogram in the declarative part
24224 that contains the call.
24226 @item
24227 Place the pragma in the declarative part, without naming an entity. This
24228 disables warnings on all calls in the corresponding  declarative region.
24230 @item
24231 Place the pragma in the package spec that declares the called subprogram,
24232 and name the subprogram. This disables warnings on all elaboration calls to
24233 that subprogram.
24235 @item
24236 Place the pragma in the package spec that declares the called subprogram,
24237 without naming any entity. This disables warnings on all elaboration calls to
24238 all subprograms declared in this spec.
24240 @item Use Pragma Elaborate
24241 As previously described in section @xref{Treatment of Pragma Elaborate},
24242 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24243 that no elaboration checks are required on calls to the designated unit.
24244 There may be cases in which the caller knows that no transitive calls
24245 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24246 case where @code{pragma Elaborate_All} would cause a circularity.
24247 @end itemize
24249 @noindent
24250 These five cases are listed in order of decreasing safety, and therefore
24251 require increasing programmer care in their application. Consider the
24252 following program:
24254 @smallexample @c adanocomment
24255 package Pack1 is
24256   function F1 return Integer;
24257   X1 : Integer;
24258 end Pack1;
24260 package Pack2 is
24261   function F2 return Integer;
24262   function Pure (x : integer) return integer;
24263   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24264   --  pragma Suppress (Elaboration_Check);              -- (4)
24265 end Pack2;
24267 with Pack2;
24268 package body Pack1 is
24269   function F1 return Integer is
24270   begin
24271     return 100;
24272   end F1;
24273   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24274 begin
24275   declare
24276     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24277     --  pragma Suppress(Elaboration_Check);             -- (2)
24278   begin
24279     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24280   end;
24281 end Pack1;
24283 with Pack1;
24284 package body Pack2 is
24285   function F2 return Integer is
24286   begin
24287      return Pack1.F1;
24288   end F2;
24289   function Pure (x : integer) return integer is
24290   begin
24291      return x ** 3 - 3 * x;
24292   end;
24293 end Pack2;
24295 with Pack1, Ada.Text_IO;
24296 procedure Proc3 is
24297 begin
24298   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24299 end Proc3;
24300 @end smallexample
24301 In the absence of any pragmas, an attempt to bind this program produces
24302 the following diagnostics:
24303 @smallexample
24304 @group
24305 @iftex
24306 @leftskip=.5cm
24307 @end iftex
24308 error: elaboration circularity detected
24309 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24310 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24311 info:       recompile "pack1 (body)" with -gnatwl for full details
24312 info:          "pack1 (body)"
24313 info:             must be elaborated along with its spec:
24314 info:          "pack1 (spec)"
24315 info:             which is withed by:
24316 info:          "pack2 (body)"
24317 info:             which must be elaborated along with its spec:
24318 info:          "pack2 (spec)"
24319 info:             which is withed by:
24320 info:          "pack1 (body)"
24321 @end group
24322 @end smallexample
24323 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24324 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24325 F2 is safe, even though F2 calls F1, because the call appears after the
24326 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24327 remove the warning on the call. It is also possible to use pragma (2)
24328 because there are no other potentially unsafe calls in the block.
24330 @noindent
24331 The call to @code{Pure} is safe because this function does not depend on the
24332 state of @code{Pack2}. Therefore any call to this function is safe, and it
24333 is correct to place pragma (3) in the corresponding package spec.
24335 @noindent
24336 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24337 warnings on all calls to functions declared therein. Note that this is not
24338 necessarily safe, and requires more detailed examination of the subprogram
24339 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24340 be already elaborated.
24341 @end table
24343 @noindent
24344 It is hard to generalize on which of these four approaches should be
24345 taken. Obviously if it is possible to fix the program so that the default
24346 treatment works, this is preferable, but this may not always be practical.
24347 It is certainly simple enough to use
24348 @option{-gnatE}
24349 but the danger in this case is that, even if the GNAT binder
24350 finds a correct elaboration order, it may not always do so,
24351 and certainly a binder from another Ada compiler might not. A
24352 combination of testing and analysis (for which the warnings generated
24353 with the
24354 @option{-gnatwl}
24355 switch can be useful) must be used to ensure that the program is free
24356 of errors. One switch that is useful in this testing is the
24357 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24358 switch for
24359 @code{gnatbind}.
24360 Normally the binder tries to find an order that has the best chance of
24361 of avoiding elaboration problems. With this switch, the binder
24362 plays a devil's advocate role, and tries to choose the order that
24363 has the best chance of failing. If your program works even with this
24364 switch, then it has a better chance of being error free, but this is still
24365 not a guarantee.
24367 For an example of this approach in action, consider the C-tests (executable
24368 tests) from the ACVC suite. If these are compiled and run with the default
24369 treatment, then all but one of them succeed without generating any error
24370 diagnostics from the binder. However, there is one test that fails, and
24371 this is not surprising, because the whole point of this test is to ensure
24372 that the compiler can handle cases where it is impossible to determine
24373 a correct order statically, and it checks that an exception is indeed
24374 raised at run time.
24376 This one test must be compiled and run using the
24377 @option{-gnatE}
24378 switch, and then it passes. Alternatively, the entire suite can
24379 be run using this switch. It is never wrong to run with the dynamic
24380 elaboration switch if your code is correct, and we assume that the
24381 C-tests are indeed correct (it is less efficient, but efficiency is
24382 not a factor in running the ACVC tests.)
24384 @node Elaboration for Access-to-Subprogram Values
24385 @section Elaboration for Access-to-Subprogram Values
24386 @cindex Access-to-subprogram
24388 @noindent
24389 The introduction of access-to-subprogram types in Ada 95 complicates
24390 the handling of elaboration. The trouble is that it becomes
24391 impossible to tell at compile time which procedure
24392 is being called. This means that it is not possible for the binder
24393 to analyze the elaboration requirements in this case.
24395 If at the point at which the access value is created
24396 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24397 the body of the subprogram is
24398 known to have been elaborated, then the access value is safe, and its use
24399 does not require a check. This may be achieved by appropriate arrangement
24400 of the order of declarations if the subprogram is in the current unit,
24401 or, if the subprogram is in another unit, by using pragma
24402 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24403 on the referenced unit.
24405 If the referenced body is not known to have been elaborated at the point
24406 the access value is created, then any use of the access value must do a
24407 dynamic check, and this dynamic check will fail and raise a
24408 @code{Program_Error} exception if the body has not been elaborated yet.
24409 GNAT will generate the necessary checks, and in addition, if the
24410 @option{-gnatwl}
24411 switch is set, will generate warnings that such checks are required.
24413 The use of dynamic dispatching for tagged types similarly generates
24414 a requirement for dynamic checks, and premature calls to any primitive
24415 operation of a tagged type before the body of the operation has been
24416 elaborated, will result in the raising of @code{Program_Error}.
24418 @node Summary of Procedures for Elaboration Control
24419 @section Summary of Procedures for Elaboration Control
24420 @cindex Elaboration control
24422 @noindent
24423 First, compile your program with the default options, using none of
24424 the special elaboration control switches. If the binder successfully
24425 binds your program, then you can be confident that, apart from issues
24426 raised by the use of access-to-subprogram types and dynamic dispatching,
24427 the program is free of elaboration errors. If it is important that the
24428 program be portable, then use the
24429 @option{-gnatwl}
24430 switch to generate warnings about missing @code{Elaborate_All}
24431 pragmas, and supply the missing pragmas.
24433 If the program fails to bind using the default static elaboration
24434 handling, then you can fix the program to eliminate the binder
24435 message, or recompile the entire program with the
24436 @option{-gnatE} switch to generate dynamic elaboration checks,
24437 and, if you are sure there really are no elaboration problems,
24438 use a global pragma @code{Suppress (Elaboration_Check)}.
24440 @node Other Elaboration Order Considerations
24441 @section Other Elaboration Order Considerations
24442 @noindent
24443 This section has been entirely concerned with the issue of finding a valid
24444 elaboration order, as defined by the Ada Reference Manual. In a case
24445 where several elaboration orders are valid, the task is to find one
24446 of the possible valid elaboration orders (and the static model in GNAT
24447 will ensure that this is achieved).
24449 The purpose of the elaboration rules in the Ada Reference Manual is to
24450 make sure that no entity is accessed before it has been elaborated. For
24451 a subprogram, this means that the spec and body must have been elaborated
24452 before the subprogram is called. For an object, this means that the object
24453 must have been elaborated before its value is read or written. A violation
24454 of either of these two requirements is an access before elaboration order,
24455 and this section has been all about avoiding such errors.
24457 In the case where more than one order of elaboration is possible, in the
24458 sense that access before elaboration errors are avoided, then any one of
24459 the orders is ``correct'' in the sense that it meets the requirements of
24460 the Ada Reference Manual, and no such error occurs.
24462 However, it may be the case for a given program, that there are
24463 constraints on the order of elaboration that come not from consideration
24464 of avoiding elaboration errors, but rather from extra-lingual logic
24465 requirements. Consider this example:
24467 @smallexample @c ada
24468 with Init_Constants;
24469 package Constants is
24470    X : Integer := 0;
24471    Y : Integer := 0;
24472 end Constants;
24474 package Init_Constants is
24475    procedure P; -- require a body
24476 end Init_Constants;
24478 with Constants;
24479 package body Init_Constants is
24480    procedure P is begin null; end;
24481 begin
24482    Constants.X := 3;
24483    Constants.Y := 4;
24484 end Init_Constants;
24486 with Constants;
24487 package Calc is
24488    Z : Integer := Constants.X + Constants.Y;
24489 end Calc;
24491 with Calc;
24492 with Text_IO; use Text_IO;
24493 procedure Main is
24494 begin
24495    Put_Line (Calc.Z'Img);
24496 end Main;
24497 @end smallexample
24499 @noindent
24500 In this example, there is more than one valid order of elaboration. For
24501 example both the following are correct orders:
24503 @smallexample
24504 Init_Constants spec
24505 Constants spec
24506 Calc spec
24507 Init_Constants body
24508 Main body
24510   and
24512 Init_Constants spec
24513 Init_Constants body
24514 Constants spec
24515 Calc spec
24516 Main body
24517 @end smallexample
24519 @noindent
24520 There is no language rule to prefer one or the other, both are correct
24521 from an order of elaboration point of view. But the programmatic effects
24522 of the two orders are very different. In the first, the elaboration routine
24523 of @code{Calc} initializes @code{Z} to zero, and then the main program
24524 runs with this value of zero. But in the second order, the elaboration
24525 routine of @code{Calc} runs after the body of Init_Constants has set
24526 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24527 runs.
24529 One could perhaps by applying pretty clever non-artificial intelligence
24530 to the situation guess that it is more likely that the second order of
24531 elaboration is the one desired, but there is no formal linguistic reason
24532 to prefer one over the other. In fact in this particular case, GNAT will
24533 prefer the second order, because of the rule that bodies are elaborated
24534 as soon as possible, but it's just luck that this is what was wanted
24535 (if indeed the second order was preferred).
24537 If the program cares about the order of elaboration routines in a case like
24538 this, it is important to specify the order required. In this particular
24539 case, that could have been achieved by adding to the spec of Calc:
24541 @smallexample @c ada
24542 pragma Elaborate_All (Constants);
24543 @end smallexample
24545 @noindent
24546 which requires that the body (if any) and spec of @code{Constants},
24547 as well as the body and spec of any unit @code{with}'ed by
24548 @code{Constants} be elaborated before @code{Calc} is elaborated.
24550 Clearly no automatic method can always guess which alternative you require,
24551 and if you are working with legacy code that had constraints of this kind
24552 which were not properly specified by adding @code{Elaborate} or
24553 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24554 compilers can choose different orders.
24556 The @code{gnatbind}
24557 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24558 out problems. This switch causes bodies to be elaborated as late as possible
24559 instead of as early as possible. In the example above, it would have forced
24560 the choice of the first elaboration order. If you get different results
24561 when using this switch, and particularly if one set of results is right,
24562 and one is wrong as far as you are concerned, it shows that you have some
24563 missing @code{Elaborate} pragmas. For the example above, we have the
24564 following output:
24566 @smallexample
24567 gnatmake -f -q main
24568 main
24570 gnatmake -f -q main -bargs -p
24571 main
24573 @end smallexample
24575 @noindent
24576 It is of course quite unlikely that both these results are correct, so
24577 it is up to you in a case like this to investigate the source of the
24578 difference, by looking at the two elaboration orders that are chosen,
24579 and figuring out which is correct, and then adding the necessary
24580 @code{Elaborate_All} pragmas to ensure the desired order.
24582 @node Inline Assembler
24583 @appendix Inline Assembler
24585 @noindent
24586 If you need to write low-level software that interacts directly
24587 with the hardware, Ada provides two ways to incorporate assembly
24588 language code into your program.  First, you can import and invoke
24589 external routines written in assembly language, an Ada feature fully
24590 supported by GNAT.  However, for small sections of code it may be simpler
24591 or more efficient to include assembly language statements directly
24592 in your Ada source program, using the facilities of the implementation-defined
24593 package @code{System.Machine_Code}, which incorporates the gcc
24594 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
24595 including the following:
24597 @itemize @bullet
24598 @item No need to use non-Ada tools
24599 @item Consistent interface over different targets
24600 @item Automatic usage of the proper calling conventions
24601 @item Access to Ada constants and variables
24602 @item Definition of intrinsic routines
24603 @item Possibility of inlining a subprogram comprising assembler code
24604 @item Code optimizer can take Inline Assembler code into account
24605 @end itemize
24607 This chapter presents a series of examples to show you how to use
24608 the Inline Assembler.  Although it focuses on the Intel x86,
24609 the general approach applies also to other processors.
24610 It is assumed that you are familiar with Ada
24611 and with assembly language programming.
24613 @menu
24614 * Basic Assembler Syntax::
24615 * A Simple Example of Inline Assembler::
24616 * Output Variables in Inline Assembler::
24617 * Input Variables in Inline Assembler::
24618 * Inlining Inline Assembler Code::
24619 * Other Asm Functionality::
24620 * A Complete Example::
24621 @end menu
24623 @c ---------------------------------------------------------------------------
24624 @node Basic Assembler Syntax
24625 @section Basic Assembler Syntax
24627 @noindent
24628 The assembler used by GNAT and gcc is based not on the Intel assembly
24629 language, but rather on a language that descends from the AT&T Unix
24630 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24631 The following table summarizes the main features of @emph{as} syntax
24632 and points out the differences from the Intel conventions.
24633 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24634 pre-processor) documentation for further information.
24636 @table @asis
24637 @item Register names
24638 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24640 Intel: No extra punctuation; for example @code{eax}
24642 @item Immediate operand
24643 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24645 Intel: No extra punctuation; for example @code{4}
24647 @item Address
24648 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24650 Intel: No extra punctuation; for example @code{loc}
24652 @item Memory contents
24653 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24655 Intel: Square brackets; for example @code{[loc]}
24657 @item Register contents
24658 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24660 Intel: Square brackets; for example @code{[eax]}
24662 @item Hexadecimal numbers
24663 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24665 Intel: Trailing ``h''; for example @code{A0h}
24667 @item Operand size
24668 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24669 a 16-bit word
24671 Intel: Implicit, deduced by assembler; for example @code{mov}
24673 @item Instruction repetition
24674 gcc / @emph{as}: Split into two lines; for example
24676 @code{rep}
24678 @code{stosl}
24680 Intel: Keep on one line; for example @code{rep stosl}
24682 @item Order of operands
24683 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24685 Intel: Destination first; for example @code{mov eax, 4}
24686 @end table
24688 @c ---------------------------------------------------------------------------
24689 @node A Simple Example of Inline Assembler
24690 @section A Simple Example of Inline Assembler
24692 @noindent
24693 The following example will generate a single assembly language statement,
24694 @code{nop}, which does nothing.  Despite its lack of run-time effect,
24695 the example will be useful in illustrating the basics of
24696 the Inline Assembler facility.
24698 @smallexample @c ada
24699 @group
24700 with System.Machine_Code; use System.Machine_Code;
24701 procedure Nothing is
24702 begin
24703    Asm ("nop");
24704 end Nothing;
24705 @end group
24706 @end smallexample
24708 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24709 here it takes one parameter, a @emph{template string} that must be a static
24710 expression and that will form the generated instruction.
24711 @code{Asm} may be regarded as a compile-time procedure that parses
24712 the template string and additional parameters (none here),
24713 from which it generates a sequence of assembly language instructions.
24715 The examples in this chapter will illustrate several of the forms
24716 for invoking @code{Asm}; a complete specification of the syntax
24717 is found in the @cite{GNAT Reference Manual}.
24719 Under the standard GNAT conventions, the @code{Nothing} procedure
24720 should be in a file named @file{nothing.adb}.
24721 You can build the executable in the usual way:
24722 @smallexample
24723 gnatmake nothing
24724 @end smallexample
24725 However, the interesting aspect of this example is not its run-time behavior
24726 but rather the generated assembly code.
24727 To see this output, invoke the compiler as follows:
24728 @smallexample
24729    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24730 @end smallexample
24731 where the options are:
24733 @table @code
24734 @item -c
24735 compile only (no bind or link)
24736 @item -S
24737 generate assembler listing
24738 @item -fomit-frame-pointer
24739 do not set up separate stack frames
24740 @item -gnatp
24741 do not add runtime checks
24742 @end table
24744 This gives a human-readable assembler version of the code. The resulting
24745 file will have the same name as the Ada source file, but with a @code{.s}
24746 extension. In our example, the file @file{nothing.s} has the following
24747 contents:
24749 @smallexample
24750 @group
24751 .file "nothing.adb"
24752 gcc2_compiled.:
24753 ___gnu_compiled_ada:
24754 .text
24755    .align 4
24756 .globl __ada_nothing
24757 __ada_nothing:
24758 #APP
24759    nop
24760 #NO_APP
24761    jmp L1
24762    .align 2,0x90
24764    ret
24765 @end group
24766 @end smallexample
24768 The assembly code you included is clearly indicated by
24769 the compiler, between the @code{#APP} and @code{#NO_APP}
24770 delimiters. The character before the 'APP' and 'NOAPP'
24771 can differ on different targets. For example, GNU/Linux uses '#APP' while
24772 on NT you will see '/APP'.
24774 If you make a mistake in your assembler code (such as using the
24775 wrong size modifier, or using a wrong operand for the instruction) GNAT
24776 will report this error in a temporary file, which will be deleted when
24777 the compilation is finished.  Generating an assembler file will help
24778 in such cases, since you can assemble this file separately using the
24779 @emph{as} assembler that comes with gcc.
24781 Assembling the file using the command
24783 @smallexample
24784 as @file{nothing.s}
24785 @end smallexample
24786 @noindent
24787 will give you error messages whose lines correspond to the assembler
24788 input file, so you can easily find and correct any mistakes you made.
24789 If there are no errors, @emph{as} will generate an object file
24790 @file{nothing.out}.
24792 @c ---------------------------------------------------------------------------
24793 @node Output Variables in Inline Assembler
24794 @section Output Variables in Inline Assembler
24796 @noindent
24797 The examples in this section, showing how to access the processor flags,
24798 illustrate how to specify the destination operands for assembly language
24799 statements.
24801 @smallexample @c ada
24802 @group
24803 with Interfaces; use Interfaces;
24804 with Ada.Text_IO; use Ada.Text_IO;
24805 with System.Machine_Code; use System.Machine_Code;
24806 procedure Get_Flags is
24807    Flags : Unsigned_32;
24808    use ASCII;
24809 begin
24810    Asm ("pushfl"          & LF & HT & -- push flags on stack
24811         "popl %%eax"      & LF & HT & -- load eax with flags
24812         "movl %%eax, %0",             -- store flags in variable
24813         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24814    Put_Line ("Flags register:" & Flags'Img);
24815 end Get_Flags;
24816 @end group
24817 @end smallexample
24819 In order to have a nicely aligned assembly listing, we have separated
24820 multiple assembler statements in the Asm template string with linefeed
24821 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24822 The resulting section of the assembly output file is:
24824 @smallexample
24825 @group
24826 #APP
24827    pushfl
24828    popl %eax
24829    movl %eax, -40(%ebp)
24830 #NO_APP
24831 @end group
24832 @end smallexample
24834 It would have been legal to write the Asm invocation as:
24836 @smallexample
24837 Asm ("pushfl popl %%eax movl %%eax, %0")
24838 @end smallexample
24840 but in the generated assembler file, this would come out as:
24842 @smallexample
24843 #APP
24844    pushfl popl %eax movl %eax, -40(%ebp)
24845 #NO_APP
24846 @end smallexample
24848 which is not so convenient for the human reader.
24850 We use Ada comments
24851 at the end of each line to explain what the assembler instructions
24852 actually do.  This is a useful convention.
24854 When writing Inline Assembler instructions, you need to precede each register
24855 and variable name with a percent sign.  Since the assembler already requires
24856 a percent sign at the beginning of a register name, you need two consecutive
24857 percent signs for such names in the Asm template string, thus @code{%%eax}.
24858 In the generated assembly code, one of the percent signs will be stripped off.
24860 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24861 variables: operands you later define using @code{Input} or @code{Output}
24862 parameters to @code{Asm}.
24863 An output variable is illustrated in
24864 the third statement in the Asm template string:
24865 @smallexample
24866 movl %%eax, %0
24867 @end smallexample
24868 The intent is to store the contents of the eax register in a variable that can
24869 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
24870 necessarily work, since the compiler might optimize by using a register
24871 to hold Flags, and the expansion of the @code{movl} instruction would not be
24872 aware of this optimization.  The solution is not to store the result directly
24873 but rather to advise the compiler to choose the correct operand form;
24874 that is the purpose of the @code{%0} output variable.
24876 Information about the output variable is supplied in the @code{Outputs}
24877 parameter to @code{Asm}:
24878 @smallexample
24879 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24880 @end smallexample
24882 The output is defined by the @code{Asm_Output} attribute of the target type;
24883 the general format is
24884 @smallexample
24885 Type'Asm_Output (constraint_string, variable_name)
24886 @end smallexample
24888 The constraint string directs the compiler how
24889 to store/access the associated variable.  In the example
24890 @smallexample
24891 Unsigned_32'Asm_Output ("=m", Flags);
24892 @end smallexample
24893 the @code{"m"} (memory) constraint tells the compiler that the variable
24894 @code{Flags} should be stored in a memory variable, thus preventing
24895 the optimizer from keeping it in a register.  In contrast,
24896 @smallexample
24897 Unsigned_32'Asm_Output ("=r", Flags);
24898 @end smallexample
24899 uses the @code{"r"} (register) constraint, telling the compiler to
24900 store the variable in a register.
24902 If the constraint is preceded by the equal character (@strong{=}), it tells
24903 the compiler that the variable will be used to store data into it.
24905 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
24906 allowing the optimizer to choose whatever it deems best.
24908 There are a fairly large number of constraints, but the ones that are
24909 most useful (for the Intel x86 processor) are the following:
24911 @table @code
24912 @item =
24913 output constraint
24914 @item g
24915 global (i.e. can be stored anywhere)
24916 @item m
24917 in memory
24918 @item I
24919 a constant
24920 @item a
24921 use eax
24922 @item b
24923 use ebx
24924 @item c
24925 use ecx
24926 @item d
24927 use edx
24928 @item S
24929 use esi
24930 @item D
24931 use edi
24932 @item r
24933 use one of eax, ebx, ecx or edx
24934 @item q
24935 use one of eax, ebx, ecx, edx, esi or edi
24936 @end table
24938 The full set of constraints is described in the gcc and @emph{as}
24939 documentation; note that it is possible to combine certain constraints
24940 in one constraint string.
24942 You specify the association of an output variable with an assembler operand
24943 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24944 integer.  Thus in
24945 @smallexample @c ada
24946 @group
24947 Asm ("pushfl"          & LF & HT & -- push flags on stack
24948      "popl %%eax"      & LF & HT & -- load eax with flags
24949      "movl %%eax, %0",             -- store flags in variable
24950      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24951 @end group
24952 @end smallexample
24953 @noindent
24954 @code{%0} will be replaced in the expanded code by the appropriate operand,
24955 whatever
24956 the compiler decided for the @code{Flags} variable.
24958 In general, you may have any number of output variables:
24959 @itemize @bullet
24960 @item
24961 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24962 @item
24963 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24964 of @code{Asm_Output} attributes
24965 @end itemize
24967 For example:
24968 @smallexample @c ada
24969 @group
24970 Asm ("movl %%eax, %0" & LF & HT &
24971      "movl %%ebx, %1" & LF & HT &
24972      "movl %%ecx, %2",
24973      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
24974                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
24975                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
24976 @end group
24977 @end smallexample
24978 @noindent
24979 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
24980 in the Ada program.
24982 As a variation on the @code{Get_Flags} example, we can use the constraints
24983 string to direct the compiler to store the eax register into the @code{Flags}
24984 variable, instead of including the store instruction explicitly in the
24985 @code{Asm} template string:
24987 @smallexample @c ada
24988 @group
24989 with Interfaces; use Interfaces;
24990 with Ada.Text_IO; use Ada.Text_IO;
24991 with System.Machine_Code; use System.Machine_Code;
24992 procedure Get_Flags_2 is
24993    Flags : Unsigned_32;
24994    use ASCII;
24995 begin
24996    Asm ("pushfl"      & LF & HT & -- push flags on stack
24997         "popl %%eax",             -- save flags in eax
24998         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
24999    Put_Line ("Flags register:" & Flags'Img);
25000 end Get_Flags_2;
25001 @end group
25002 @end smallexample
25004 @noindent
25005 The @code{"a"} constraint tells the compiler that the @code{Flags}
25006 variable will come from the eax register. Here is the resulting code:
25008 @smallexample
25009 @group
25010 #APP
25011    pushfl
25012    popl %eax
25013 #NO_APP
25014    movl %eax,-40(%ebp)
25015 @end group
25016 @end smallexample
25018 @noindent
25019 The compiler generated the store of eax into Flags after
25020 expanding the assembler code.
25022 Actually, there was no need to pop the flags into the eax register;
25023 more simply, we could just pop the flags directly into the program variable:
25025 @smallexample @c ada
25026 @group
25027 with Interfaces; use Interfaces;
25028 with Ada.Text_IO; use Ada.Text_IO;
25029 with System.Machine_Code; use System.Machine_Code;
25030 procedure Get_Flags_3 is
25031    Flags : Unsigned_32;
25032    use ASCII;
25033 begin
25034    Asm ("pushfl"  & LF & HT & -- push flags on stack
25035         "pop %0",             -- save flags in Flags
25036         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25037    Put_Line ("Flags register:" & Flags'Img);
25038 end Get_Flags_3;
25039 @end group
25040 @end smallexample
25042 @c ---------------------------------------------------------------------------
25043 @node Input Variables in Inline Assembler
25044 @section Input Variables in Inline Assembler
25046 @noindent
25047 The example in this section illustrates how to specify the source operands
25048 for assembly language statements.
25049 The program simply increments its input value by 1:
25051 @smallexample @c ada
25052 @group
25053 with Interfaces; use Interfaces;
25054 with Ada.Text_IO; use Ada.Text_IO;
25055 with System.Machine_Code; use System.Machine_Code;
25056 procedure Increment is
25058    function Incr (Value : Unsigned_32) return Unsigned_32 is
25059       Result : Unsigned_32;
25060    begin
25061       Asm ("incl %0",
25062            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25063            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25064       return Result;
25065    end Incr;
25067    Value : Unsigned_32;
25069 begin
25070    Value := 5;
25071    Put_Line ("Value before is" & Value'Img);
25072    Value := Incr (Value);
25073    Put_Line ("Value after is" & Value'Img);
25074 end Increment;
25075 @end group
25076 @end smallexample
25078 The @code{Outputs} parameter to @code{Asm} specifies
25079 that the result will be in the eax register and that it is to be stored
25080 in the @code{Result} variable.
25082 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25083 but with an @code{Asm_Input} attribute.
25084 The @code{"="} constraint, indicating an output value, is not present.
25086 You can have multiple input variables, in the same way that you can have more
25087 than one output variable.
25089 The parameter count (%0, %1) etc, now starts at the first input
25090 statement, and continues with the output statements.
25091 When both parameters use the same variable, the
25092 compiler will treat them as the same %n operand, which is the case here.
25094 Just as the @code{Outputs} parameter causes the register to be stored into the
25095 target variable after execution of the assembler statements, so does the
25096 @code{Inputs} parameter cause its variable to be loaded into the register
25097 before execution of the assembler statements.
25099 Thus the effect of the @code{Asm} invocation is:
25100 @enumerate
25101 @item load the 32-bit value of @code{Value} into eax
25102 @item execute the @code{incl %eax} instruction
25103 @item store the contents of eax into the @code{Result} variable
25104 @end enumerate
25106 The resulting assembler file (with @option{-O2} optimization) contains:
25107 @smallexample
25108 @group
25109 _increment__incr.1:
25110    subl $4,%esp
25111    movl 8(%esp),%eax
25112 #APP
25113    incl %eax
25114 #NO_APP
25115    movl %eax,%edx
25116    movl %ecx,(%esp)
25117    addl $4,%esp
25118    ret
25119 @end group
25120 @end smallexample
25122 @c ---------------------------------------------------------------------------
25123 @node Inlining Inline Assembler Code
25124 @section Inlining Inline Assembler Code
25126 @noindent
25127 For a short subprogram such as the @code{Incr} function in the previous
25128 section, the overhead of the call and return (creating / deleting the stack
25129 frame) can be significant, compared to the amount of code in the subprogram
25130 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25131 which directs the compiler to expand invocations of the subprogram at the
25132 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25133 Here is the resulting program:
25135 @smallexample @c ada
25136 @group
25137 with Interfaces; use Interfaces;
25138 with Ada.Text_IO; use Ada.Text_IO;
25139 with System.Machine_Code; use System.Machine_Code;
25140 procedure Increment_2 is
25142    function Incr (Value : Unsigned_32) return Unsigned_32 is
25143       Result : Unsigned_32;
25144    begin
25145       Asm ("incl %0",
25146            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25147            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25148       return Result;
25149    end Incr;
25150    pragma Inline (Increment);
25152    Value : Unsigned_32;
25154 begin
25155    Value := 5;
25156    Put_Line ("Value before is" & Value'Img);
25157    Value := Increment (Value);
25158    Put_Line ("Value after is" & Value'Img);
25159 end Increment_2;
25160 @end group
25161 @end smallexample
25163 Compile the program with both optimization (@option{-O2}) and inlining
25164 enabled (@option{-gnatpn} instead of @option{-gnatp}).
25166 The @code{Incr} function is still compiled as usual, but at the
25167 point in @code{Increment} where our function used to be called:
25169 @smallexample
25170 @group
25171 pushl %edi
25172 call _increment__incr.1
25173 @end group
25174 @end smallexample
25176 @noindent
25177 the code for the function body directly appears:
25179 @smallexample
25180 @group
25181 movl %esi,%eax
25182 #APP
25183    incl %eax
25184 #NO_APP
25185    movl %eax,%edx
25186 @end group
25187 @end smallexample
25189 @noindent
25190 thus saving the overhead of stack frame setup and an out-of-line call.
25192 @c ---------------------------------------------------------------------------
25193 @node Other Asm Functionality
25194 @section Other @code{Asm} Functionality
25196 @noindent
25197 This section describes two important parameters to the @code{Asm}
25198 procedure: @code{Clobber}, which identifies register usage;
25199 and @code{Volatile}, which inhibits unwanted optimizations.
25201 @menu
25202 * The Clobber Parameter::
25203 * The Volatile Parameter::
25204 @end menu
25206 @c ---------------------------------------------------------------------------
25207 @node The Clobber Parameter
25208 @subsection The @code{Clobber} Parameter
25210 @noindent
25211 One of the dangers of intermixing assembly language and a compiled language
25212 such as Ada is that the compiler needs to be aware of which registers are
25213 being used by the assembly code.  In some cases, such as the earlier examples,
25214 the constraint string is sufficient to indicate register usage (e.g.,
25215 @code{"a"} for
25216 the eax register).  But more generally, the compiler needs an explicit
25217 identification of the registers that are used by the Inline Assembly
25218 statements.
25220 Using a register that the compiler doesn't know about
25221 could be a side effect of an instruction (like @code{mull}
25222 storing its result in both eax and edx).
25223 It can also arise from explicit register usage in your
25224 assembly code; for example:
25225 @smallexample
25226 @group
25227 Asm ("movl %0, %%ebx" & LF & HT &
25228      "movl %%ebx, %1",
25229      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25230      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25231 @end group
25232 @end smallexample
25233 @noindent
25234 where the compiler (since it does not analyze the @code{Asm} template string)
25235 does not know you are using the ebx register.
25237 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25238 to identify the registers that will be used by your assembly code:
25240 @smallexample
25241 @group
25242 Asm ("movl %0, %%ebx" & LF & HT &
25243      "movl %%ebx, %1",
25244      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25245      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25246      Clobber => "ebx");
25247 @end group
25248 @end smallexample
25250 The Clobber parameter is a static string expression specifying the
25251 register(s) you are using.  Note that register names are @emph{not} prefixed
25252 by a percent sign. Also, if more than one register is used then their names
25253 are separated by commas; e.g., @code{"eax, ebx"}
25255 The @code{Clobber} parameter has several additional uses:
25256 @enumerate
25257 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25258 @item Use ``register'' name @code{memory} if you changed a memory location
25259 @end enumerate
25261 @c ---------------------------------------------------------------------------
25262 @node The Volatile Parameter
25263 @subsection The @code{Volatile} Parameter
25264 @cindex Volatile parameter
25266 @noindent
25267 Compiler optimizations in the presence of Inline Assembler may sometimes have
25268 unwanted effects.  For example, when an @code{Asm} invocation with an input
25269 variable is inside a loop, the compiler might move the loading of the input
25270 variable outside the loop, regarding it as a one-time initialization.
25272 If this effect is not desired, you can disable such optimizations by setting
25273 the @code{Volatile} parameter to @code{True}; for example:
25275 @smallexample @c ada
25276 @group
25277 Asm ("movl %0, %%ebx" & LF & HT &
25278      "movl %%ebx, %1",
25279      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25280      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25281      Clobber  => "ebx",
25282      Volatile => True);
25283 @end group
25284 @end smallexample
25286 By default, @code{Volatile} is set to @code{False} unless there is no
25287 @code{Outputs} parameter.
25289 Although setting @code{Volatile} to @code{True} prevents unwanted
25290 optimizations, it will also disable other optimizations that might be
25291 important for efficiency. In general, you should set @code{Volatile}
25292 to @code{True} only if the compiler's optimizations have created
25293 problems.
25295 @c ---------------------------------------------------------------------------
25296 @node A Complete Example
25297 @section A Complete Example
25299 @noindent
25300 This section contains a complete program illustrating a realistic usage
25301 of GNAT's Inline Assembler capabilities.  It comprises a main procedure
25302 @code{Check_CPU} and a package @code{Intel_CPU}.
25303 The package declares a collection of functions that detect the properties
25304 of the 32-bit x86 processor that is running the program.
25305 The main procedure invokes these functions and displays the information.
25307 The Intel_CPU package could be enhanced by adding functions to
25308 detect the type of x386 co-processor, the processor caching options and
25309 special operations such as the SIMD extensions.
25311 Although the Intel_CPU package has been written for 32-bit Intel
25312 compatible CPUs, it is OS neutral. It has been tested on DOS,
25313 Windows/NT and GNU/Linux.
25315 @menu
25316 * Check_CPU Procedure::
25317 * Intel_CPU Package Specification::
25318 * Intel_CPU Package Body::
25319 @end menu
25321 @c ---------------------------------------------------------------------------
25322 @node Check_CPU Procedure
25323 @subsection @code{Check_CPU} Procedure
25324 @cindex Check_CPU procedure
25326 @smallexample @c adanocomment
25327 ---------------------------------------------------------------------
25328 --                                                                 --
25329 --  Uses the Intel_CPU package to identify the CPU the program is  --
25330 --  running on, and some of the features it supports.              --
25331 --                                                                 --
25332 ---------------------------------------------------------------------
25334 with Intel_CPU;                     --  Intel CPU detection functions
25335 with Ada.Text_IO;                   --  Standard text I/O
25336 with Ada.Command_Line;              --  To set the exit status
25338 procedure Check_CPU is
25340    Type_Found : Boolean := False;
25341    --  Flag to indicate that processor was identified
25343    Features   : Intel_CPU.Processor_Features;
25344    --  The processor features
25346    Signature  : Intel_CPU.Processor_Signature;
25347    --  The processor type signature
25349 begin
25351    -----------------------------------
25352    --  Display the program banner.  --
25353    -----------------------------------
25355    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
25356                          ": check Intel CPU version and features, v1.0");
25357    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
25358    Ada.Text_IO.New_Line;
25360    -----------------------------------------------------------------------
25361    --  We can safely start with the assumption that we are on at least  --
25362    --  a x386 processor. If the CPUID instruction is present, then we   --
25363    --  have a later processor type.                                     --
25364    -----------------------------------------------------------------------
25366    if Intel_CPU.Has_CPUID = False then
25368       --  No CPUID instruction, so we assume this is indeed a x386
25369       --  processor. We can still check if it has a FP co-processor.
25370       if Intel_CPU.Has_FPU then
25371          Ada.Text_IO.Put_Line
25372            ("x386-type processor with a FP co-processor");
25373       else
25374          Ada.Text_IO.Put_Line
25375            ("x386-type processor without a FP co-processor");
25376       end if;  --  check for FPU
25378       --  Program done
25379       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
25380       return;
25382    end if;  --  check for CPUID
25384    -----------------------------------------------------------------------
25385    --  If CPUID is supported, check if this is a true Intel processor,  --
25386    --  if it is not, display a warning.                                 --
25387    -----------------------------------------------------------------------
25389    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
25390       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
25391       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
25392    end if;  --  check if Intel
25394    ----------------------------------------------------------------------
25395    --  With the CPUID instruction present, we can assume at least a    --
25396    --  x486 processor. If the CPUID support level is < 1 then we have  --
25397    --  to leave it at that.                                            --
25398    ----------------------------------------------------------------------
25400    if Intel_CPU.CPUID_Level < 1 then
25402       --  Ok, this is a x486 processor. we still can get the Vendor ID
25403       Ada.Text_IO.Put_Line ("x486-type processor");
25404       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
25406       --  We can also check if there is a FPU present
25407       if Intel_CPU.Has_FPU then
25408          Ada.Text_IO.Put_Line ("Floating-Point support");
25409       else
25410          Ada.Text_IO.Put_Line ("No Floating-Point support");
25411       end if;  --  check for FPU
25413       --  Program done
25414       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
25415       return;
25417    end if;  --  check CPUID level
25419    ---------------------------------------------------------------------
25420    --  With a CPUID level of 1 we can use the processor signature to  --
25421    --  determine it's exact type.                                     --
25422    ---------------------------------------------------------------------
25424    Signature := Intel_CPU.Signature;
25426    ----------------------------------------------------------------------
25427    --  Ok, now we go into a lot of messy comparisons to get the        --
25428    --  processor type. For clarity, no attememt to try to optimize the --
25429    --  comparisons has been made. Note that since Intel_CPU does not   --
25430    --  support getting cache info, we cannot distinguish between P5    --
25431    --  and Celeron types yet.                                          --
25432    ----------------------------------------------------------------------
25434    --  x486SL
25435    if Signature.Processor_Type = 2#00#   and
25436      Signature.Family          = 2#0100# and
25437      Signature.Model           = 2#0100# then
25438       Type_Found := True;
25439       Ada.Text_IO.Put_Line ("x486SL processor");
25440    end if;
25442    --  x486DX2 Write-Back
25443    if Signature.Processor_Type = 2#00#   and
25444      Signature.Family          = 2#0100# and
25445      Signature.Model           = 2#0111# then
25446       Type_Found := True;
25447       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
25448    end if;
25450    --  x486DX4
25451    if Signature.Processor_Type = 2#00#   and
25452      Signature.Family          = 2#0100# and
25453      Signature.Model           = 2#1000# then
25454       Type_Found := True;
25455       Ada.Text_IO.Put_Line ("x486DX4 processor");
25456    end if;
25458    --  x486DX4 Overdrive
25459    if Signature.Processor_Type = 2#01#   and
25460      Signature.Family          = 2#0100# and
25461      Signature.Model           = 2#1000# then
25462       Type_Found := True;
25463       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
25464    end if;
25466    --  Pentium (60, 66)
25467    if Signature.Processor_Type = 2#00#   and
25468      Signature.Family          = 2#0101# and
25469      Signature.Model           = 2#0001# then
25470       Type_Found := True;
25471       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
25472    end if;
25474    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
25475    if Signature.Processor_Type = 2#00#   and
25476      Signature.Family          = 2#0101# and
25477      Signature.Model           = 2#0010# then
25478       Type_Found := True;
25479       Ada.Text_IO.Put_Line
25480         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
25481    end if;
25483    --  Pentium OverDrive (60, 66)
25484    if Signature.Processor_Type = 2#01#   and
25485      Signature.Family          = 2#0101# and
25486      Signature.Model           = 2#0001# then
25487       Type_Found := True;
25488       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
25489    end if;
25491    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
25492    if Signature.Processor_Type = 2#01#   and
25493      Signature.Family          = 2#0101# and
25494      Signature.Model           = 2#0010# then
25495       Type_Found := True;
25496       Ada.Text_IO.Put_Line
25497         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
25498    end if;
25500    --  Pentium OverDrive processor for x486 processor-based systems
25501    if Signature.Processor_Type = 2#01#   and
25502      Signature.Family          = 2#0101# and
25503      Signature.Model           = 2#0011# then
25504       Type_Found := True;
25505       Ada.Text_IO.Put_Line
25506         ("Pentium OverDrive processor for x486 processor-based systems");
25507    end if;
25509    --  Pentium processor with MMX technology (166, 200)
25510    if Signature.Processor_Type = 2#00#   and
25511      Signature.Family          = 2#0101# and
25512      Signature.Model           = 2#0100# then
25513       Type_Found := True;
25514       Ada.Text_IO.Put_Line
25515         ("Pentium processor with MMX technology (166, 200)");
25516    end if;
25518    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
25519    if Signature.Processor_Type = 2#01#   and
25520      Signature.Family          = 2#0101# and
25521      Signature.Model           = 2#0100# then
25522       Type_Found := True;
25523       Ada.Text_IO.Put_Line
25524         ("Pentium OverDrive processor with MMX " &
25525          "technology for Pentium processor (75, 90, 100, 120, 133)");
25526    end if;
25528    --  Pentium Pro processor
25529    if Signature.Processor_Type = 2#00#   and
25530      Signature.Family          = 2#0110# and
25531      Signature.Model           = 2#0001# then
25532       Type_Found := True;
25533       Ada.Text_IO.Put_Line ("Pentium Pro processor");
25534    end if;
25536    --  Pentium II processor, model 3
25537    if Signature.Processor_Type = 2#00#   and
25538      Signature.Family          = 2#0110# and
25539      Signature.Model           = 2#0011# then
25540       Type_Found := True;
25541       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
25542    end if;
25544    --  Pentium II processor, model 5 or Celeron processor
25545    if Signature.Processor_Type = 2#00#   and
25546      Signature.Family          = 2#0110# and
25547      Signature.Model           = 2#0101# then
25548       Type_Found := True;
25549       Ada.Text_IO.Put_Line
25550         ("Pentium II processor, model 5 or Celeron processor");
25551    end if;
25553    --  Pentium Pro OverDrive processor
25554    if Signature.Processor_Type = 2#01#   and
25555      Signature.Family          = 2#0110# and
25556      Signature.Model           = 2#0011# then
25557       Type_Found := True;
25558       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
25559    end if;
25561    --  If no type recognized, we have an unknown. Display what
25562    --  we _do_ know
25563    if Type_Found = False then
25564       Ada.Text_IO.Put_Line ("Unknown processor");
25565    end if;
25567    -----------------------------------------
25568    --  Display processor stepping level.  --
25569    -----------------------------------------
25571    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
25573    ---------------------------------
25574    --  Display vendor ID string.  --
25575    ---------------------------------
25577    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
25579    ------------------------------------
25580    --  Get the processors features.  --
25581    ------------------------------------
25583    Features := Intel_CPU.Features;
25585    -----------------------------
25586    --  Check for a FPU unit.  --
25587    -----------------------------
25589    if Features.FPU = True then
25590       Ada.Text_IO.Put_Line ("Floating-Point unit available");
25591    else
25592       Ada.Text_IO.Put_Line ("no Floating-Point unit");
25593    end if;  --  check for FPU
25595    --------------------------------
25596    --  List processor features.  --
25597    --------------------------------
25599    Ada.Text_IO.Put_Line ("Supported features: ");
25601    --  Virtual Mode Extension
25602    if Features.VME = True then
25603       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
25604    end if;
25606    --  Debugging Extension
25607    if Features.DE = True then
25608       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
25609    end if;
25611    --  Page Size Extension
25612    if Features.PSE = True then
25613       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
25614    end if;
25616    --  Time Stamp Counter
25617    if Features.TSC = True then
25618       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
25619    end if;
25621    --  Model Specific Registers
25622    if Features.MSR = True then
25623       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
25624    end if;
25626    --  Physical Address Extension
25627    if Features.PAE = True then
25628       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
25629    end if;
25631    --  Machine Check Extension
25632    if Features.MCE = True then
25633       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
25634    end if;
25636    --  CMPXCHG8 instruction supported
25637    if Features.CX8 = True then
25638       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
25639    end if;
25641    --  on-chip APIC hardware support
25642    if Features.APIC = True then
25643       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
25644    end if;
25646    --  Fast System Call
25647    if Features.SEP = True then
25648       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
25649    end if;
25651    --  Memory Type Range Registers
25652    if Features.MTRR = True then
25653       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
25654    end if;
25656    --  Page Global Enable
25657    if Features.PGE = True then
25658       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
25659    end if;
25661    --  Machine Check Architecture
25662    if Features.MCA = True then
25663       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
25664    end if;
25666    --  Conditional Move Instruction Supported
25667    if Features.CMOV = True then
25668       Ada.Text_IO.Put_Line
25669         ("    CMOV   - Conditional Move Instruction Supported");
25670    end if;
25672    --  Page Attribute Table
25673    if Features.PAT = True then
25674       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
25675    end if;
25677    --  36-bit Page Size Extension
25678    if Features.PSE_36 = True then
25679       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
25680    end if;
25682    --  MMX technology supported
25683    if Features.MMX = True then
25684       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
25685    end if;
25687    --  Fast FP Save and Restore
25688    if Features.FXSR = True then
25689       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
25690    end if;
25692    ---------------------
25693    --  Program done.  --
25694    ---------------------
25696    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
25698 exception
25700    when others =>
25701       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
25702       raise;
25704 end Check_CPU;
25705 @end smallexample
25707 @c ---------------------------------------------------------------------------
25708 @node Intel_CPU Package Specification
25709 @subsection @code{Intel_CPU} Package Specification
25710 @cindex Intel_CPU package specification
25712 @smallexample @c adanocomment
25713 -------------------------------------------------------------------------
25714 --                                                                     --
25715 --  file: intel_cpu.ads                                                --
25716 --                                                                     --
25717 --           *********************************************             --
25718 --           * WARNING: for 32-bit Intel processors only *             --
25719 --           *********************************************             --
25720 --                                                                     --
25721 --  This package contains a number of subprograms that are useful in   --
25722 --  determining the Intel x86 CPU (and the features it supports) on    --
25723 --  which the program is running.                                      --
25724 --                                                                     --
25725 --  The package is based upon the information given in the Intel       --
25726 --  Application Note AP-485: "Intel Processor Identification and the   --
25727 --  CPUID Instruction" as of April 1998. This application note can be  --
25728 --  found on www.intel.com.                                            --
25729 --                                                                     --
25730 --  It currently deals with 32-bit processors only, will not detect    --
25731 --  features added after april 1998, and does not guarantee proper     --
25732 --  results on Intel-compatible processors.                            --
25733 --                                                                     --
25734 --  Cache info and x386 fpu type detection are not supported.          --
25735 --                                                                     --
25736 --  This package does not use any privileged instructions, so should   --
25737 --  work on any OS running on a 32-bit Intel processor.                --
25738 --                                                                     --
25739 -------------------------------------------------------------------------
25741 with Interfaces;             use Interfaces;
25742 --  for using unsigned types
25744 with System.Machine_Code;    use System.Machine_Code;
25745 --  for using inline assembler code
25747 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
25748 --  for inserting control characters
25750 package Intel_CPU is
25752    ----------------------
25753    --  Processor bits  --
25754    ----------------------
25756    subtype Num_Bits is Natural range 0 .. 31;
25757    --  the number of processor bits (32)
25759    --------------------------
25760    --  Processor register  --
25761    --------------------------
25763    --  define a processor register type for easy access to
25764    --  the individual bits
25766    type Processor_Register is array (Num_Bits) of Boolean;
25767    pragma Pack (Processor_Register);
25768    for Processor_Register'Size use 32;
25770    -------------------------
25771    --  Unsigned register  --
25772    -------------------------
25774    --  define a processor register type for easy access to
25775    --  the individual bytes
25777    type Unsigned_Register is
25778       record
25779          L1 : Unsigned_8;
25780          H1 : Unsigned_8;
25781          L2 : Unsigned_8;
25782          H2 : Unsigned_8;
25783       end record;
25785    for Unsigned_Register use
25786       record
25787          L1 at 0 range  0 ..  7;
25788          H1 at 0 range  8 .. 15;
25789          L2 at 0 range 16 .. 23;
25790          H2 at 0 range 24 .. 31;
25791       end record;
25793    for Unsigned_Register'Size use 32;
25795    ---------------------------------
25796    --  Intel processor vendor ID  --
25797    ---------------------------------
25799    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
25800    --  indicates an Intel manufactured processor
25802    ------------------------------------
25803    --  Processor signature register  --
25804    ------------------------------------
25806    --  a register type to hold the processor signature
25808    type Processor_Signature is
25809       record
25810          Stepping       : Natural range 0 .. 15;
25811          Model          : Natural range 0 .. 15;
25812          Family         : Natural range 0 .. 15;
25813          Processor_Type : Natural range 0 .. 3;
25814          Reserved       : Natural range 0 .. 262143;
25815       end record;
25817    for Processor_Signature use
25818       record
25819          Stepping       at 0 range  0 ..  3;
25820          Model          at 0 range  4 ..  7;
25821          Family         at 0 range  8 .. 11;
25822          Processor_Type at 0 range 12 .. 13;
25823          Reserved       at 0 range 14 .. 31;
25824       end record;
25826    for Processor_Signature'Size use 32;
25828    -----------------------------------
25829    --  Processor features register  --
25830    -----------------------------------
25832    --  a processor register to hold the processor feature flags
25834    type Processor_Features is
25835       record
25836          FPU    : Boolean;                --  floating point unit on chip
25837          VME    : Boolean;                --  virtual mode extension
25838          DE     : Boolean;                --  debugging extension
25839          PSE    : Boolean;                --  page size extension
25840          TSC    : Boolean;                --  time stamp counter
25841          MSR    : Boolean;                --  model specific registers
25842          PAE    : Boolean;                --  physical address extension
25843          MCE    : Boolean;                --  machine check extension
25844          CX8    : Boolean;                --  cmpxchg8 instruction
25845          APIC   : Boolean;                --  on-chip apic hardware
25846          Res_1  : Boolean;                --  reserved for extensions
25847          SEP    : Boolean;                --  fast system call
25848          MTRR   : Boolean;                --  memory type range registers
25849          PGE    : Boolean;                --  page global enable
25850          MCA    : Boolean;                --  machine check architecture
25851          CMOV   : Boolean;                --  conditional move supported
25852          PAT    : Boolean;                --  page attribute table
25853          PSE_36 : Boolean;                --  36-bit page size extension
25854          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
25855          MMX    : Boolean;                --  MMX technology supported
25856          FXSR   : Boolean;                --  fast FP save and restore
25857          Res_3  : Natural range 0 .. 127; --  reserved for extensions
25858       end record;
25860    for Processor_Features use
25861       record
25862          FPU    at 0 range  0 ..  0;
25863          VME    at 0 range  1 ..  1;
25864          DE     at 0 range  2 ..  2;
25865          PSE    at 0 range  3 ..  3;
25866          TSC    at 0 range  4 ..  4;
25867          MSR    at 0 range  5 ..  5;
25868          PAE    at 0 range  6 ..  6;
25869          MCE    at 0 range  7 ..  7;
25870          CX8    at 0 range  8 ..  8;
25871          APIC   at 0 range  9 ..  9;
25872          Res_1  at 0 range 10 .. 10;
25873          SEP    at 0 range 11 .. 11;
25874          MTRR   at 0 range 12 .. 12;
25875          PGE    at 0 range 13 .. 13;
25876          MCA    at 0 range 14 .. 14;
25877          CMOV   at 0 range 15 .. 15;
25878          PAT    at 0 range 16 .. 16;
25879          PSE_36 at 0 range 17 .. 17;
25880          Res_2  at 0 range 18 .. 22;
25881          MMX    at 0 range 23 .. 23;
25882          FXSR   at 0 range 24 .. 24;
25883          Res_3  at 0 range 25 .. 31;
25884       end record;
25886    for Processor_Features'Size use 32;
25888    -------------------
25889    --  Subprograms  --
25890    -------------------
25892    function Has_FPU return Boolean;
25893    --  return True if a FPU is found
25894    --  use only if CPUID is not supported
25896    function Has_CPUID return Boolean;
25897    --  return True if the processor supports the CPUID instruction
25899    function CPUID_Level return Natural;
25900    --  return the CPUID support level (0, 1 or 2)
25901    --  can only be called if the CPUID instruction is supported
25903    function Vendor_ID return String;
25904    --  return the processor vendor identification string
25905    --  can only be called if the CPUID instruction is supported
25907    function Signature return Processor_Signature;
25908    --  return the processor signature
25909    --  can only be called if the CPUID instruction is supported
25911    function Features return Processor_Features;
25912    --  return the processors features
25913    --  can only be called if the CPUID instruction is supported
25915 private
25917    ------------------------
25918    --  EFLAGS bit names  --
25919    ------------------------
25921    ID_Flag : constant Num_Bits := 21;
25922    --  ID flag bit
25924 end Intel_CPU;
25925 @end smallexample
25927 @c ---------------------------------------------------------------------------
25928 @node Intel_CPU Package Body
25929 @subsection @code{Intel_CPU} Package Body
25930 @cindex Intel_CPU package body
25932 @smallexample @c adanocomment
25933 package body Intel_CPU is
25935    ---------------------------
25936    --  Detect FPU presence  --
25937    ---------------------------
25939    --  There is a FPU present if we can set values to the FPU Status
25940    --  and Control Words.
25942    function Has_FPU return Boolean is
25944       Register : Unsigned_16;
25945       --  processor register to store a word
25947    begin
25949       --  check if we can change the status word
25950       Asm (
25952            --  the assembler code
25953            "finit"              & LF & HT &    --  reset status word
25954            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
25955            "fnstsw %0"          & LF & HT &    --  save status word
25956            "movw %%ax, %0",                    --  store status word
25958            --  output stored in Register
25959            --  register must be a memory location
25960            Outputs => Unsigned_16'Asm_output ("=m", Register),
25962            --  tell compiler that we used eax
25963            Clobber => "eax");
25965       --  if the status word is zero, there is no FPU
25966       if Register = 0 then
25967          return False;   --  no status word
25968       end if;  --  check status word value
25970       --  check if we can get the control word
25971       Asm (
25973            --  the assembler code
25974            "fnstcw %0",   --  save the control word
25976            --  output into Register
25977            --  register must be a memory location
25978            Outputs => Unsigned_16'Asm_output ("=m", Register));
25980       --  check the relevant bits
25981       if (Register and 16#103F#) /= 16#003F# then
25982          return False;   --  no control word
25983       end if;  --  check control word value
25985       --  FPU found
25986       return True;
25988    end Has_FPU;
25990    --------------------------------
25991    --  Detect CPUID instruction  --
25992    --------------------------------
25994    --  The processor supports the CPUID instruction if it is possible
25995    --  to change the value of ID flag bit in the EFLAGS register.
25997    function Has_CPUID return Boolean is
25999       Original_Flags, Modified_Flags : Processor_Register;
26000       --  EFLAG contents before and after changing the ID flag
26002    begin
26004       --  try flipping the ID flag in the EFLAGS register
26005       Asm (
26007            --  the assembler code
26008            "pushfl"               & LF & HT &     --  push EFLAGS on stack
26009            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
26010            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
26011            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
26012            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
26013            "popfl"                & LF & HT &     --  load EFLAGS register
26014            "pushfl"               & LF & HT &     --  push EFLAGS on stack
26015            "pop %1",                              --  save EFLAGS content
26017            --  output values, may be anything
26018            --  Original_Flags is %0
26019            --  Modified_Flags is %1
26020            Outputs =>
26021               (Processor_Register'Asm_output ("=g", Original_Flags),
26022                Processor_Register'Asm_output ("=g", Modified_Flags)),
26024            --  tell compiler eax is destroyed
26025            Clobber => "eax");
26027       --  check if CPUID is supported
26028       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
26029          return True;   --  ID flag was modified
26030       else
26031          return False;  --  ID flag unchanged
26032       end if;  --  check for CPUID
26034    end Has_CPUID;
26036    -------------------------------
26037    --  Get CPUID support level  --
26038    -------------------------------
26040    function CPUID_Level return Natural is
26042       Level : Unsigned_32;
26043       --  returned support level
26045    begin
26047       --  execute CPUID, storing the results in the Level register
26048       Asm (
26050            --  the assembler code
26051            "cpuid",    --  execute CPUID
26053            --  zero is stored in eax
26054            --  returning the support level in eax
26055            Inputs => Unsigned_32'Asm_input ("a", 0),
26057            --  eax is stored in Level
26058            Outputs => Unsigned_32'Asm_output ("=a", Level),
26060            --  tell compiler ebx, ecx and edx registers are destroyed
26061            Clobber => "ebx, ecx, edx");
26063       --  return the support level
26064       return Natural (Level);
26066    end CPUID_Level;
26068    --------------------------------
26069    --  Get CPU Vendor ID String  --
26070    --------------------------------
26072    --  The vendor ID string is returned in the ebx, ecx and edx register
26073    --  after executing the CPUID instruction with eax set to zero.
26074    --  In case of a true Intel processor the string returned is
26075    --  "GenuineIntel"
26077    function Vendor_ID return String is
26079       Ebx, Ecx, Edx : Unsigned_Register;
26080       --  registers containing the vendor ID string
26082       Vendor_ID : String (1 .. 12);
26083       -- the vendor ID string
26085    begin
26087       --  execute CPUID, storing the results in the processor registers
26088       Asm (
26090            --  the assembler code
26091            "cpuid",    --  execute CPUID
26093            --  zero stored in eax
26094            --  vendor ID string returned in ebx, ecx and edx
26095            Inputs => Unsigned_32'Asm_input ("a", 0),
26097            --  ebx is stored in Ebx
26098            --  ecx is stored in Ecx
26099            --  edx is stored in Edx
26100            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
26101                        Unsigned_Register'Asm_output ("=c", Ecx),
26102                        Unsigned_Register'Asm_output ("=d", Edx)));
26104       --  now build the vendor ID string
26105       Vendor_ID( 1) := Character'Val (Ebx.L1);
26106       Vendor_ID( 2) := Character'Val (Ebx.H1);
26107       Vendor_ID( 3) := Character'Val (Ebx.L2);
26108       Vendor_ID( 4) := Character'Val (Ebx.H2);
26109       Vendor_ID( 5) := Character'Val (Edx.L1);
26110       Vendor_ID( 6) := Character'Val (Edx.H1);
26111       Vendor_ID( 7) := Character'Val (Edx.L2);
26112       Vendor_ID( 8) := Character'Val (Edx.H2);
26113       Vendor_ID( 9) := Character'Val (Ecx.L1);
26114       Vendor_ID(10) := Character'Val (Ecx.H1);
26115       Vendor_ID(11) := Character'Val (Ecx.L2);
26116       Vendor_ID(12) := Character'Val (Ecx.H2);
26118       --  return string
26119       return Vendor_ID;
26121    end Vendor_ID;
26123    -------------------------------
26124    --  Get processor signature  --
26125    -------------------------------
26127    function Signature return Processor_Signature is
26129       Result : Processor_Signature;
26130       --  processor signature returned
26132    begin
26134       --  execute CPUID, storing the results in the Result variable
26135       Asm (
26137            --  the assembler code
26138            "cpuid",    --  execute CPUID
26140            --  one is stored in eax
26141            --  processor signature returned in eax
26142            Inputs => Unsigned_32'Asm_input ("a", 1),
26144            --  eax is stored in Result
26145            Outputs => Processor_Signature'Asm_output ("=a", Result),
26147            --  tell compiler that ebx, ecx and edx are also destroyed
26148            Clobber => "ebx, ecx, edx");
26150       --  return processor signature
26151       return Result;
26153    end Signature;
26155    ------------------------------
26156    --  Get processor features  --
26157    ------------------------------
26159    function Features return Processor_Features is
26161       Result : Processor_Features;
26162       --  processor features returned
26164    begin
26166       --  execute CPUID, storing the results in the Result variable
26167       Asm (
26169            --  the assembler code
26170            "cpuid",    --  execute CPUID
26172            --  one stored in eax
26173            --  processor features returned in edx
26174            Inputs => Unsigned_32'Asm_input ("a", 1),
26176            --  edx is stored in Result
26177            Outputs => Processor_Features'Asm_output ("=d", Result),
26179            --  tell compiler that ebx and ecx are also destroyed
26180            Clobber => "ebx, ecx");
26182       --  return processor signature
26183       return Result;
26185    end Features;
26187 end Intel_CPU;
26188 @end smallexample
26189 @c END OF INLINE ASSEMBLER CHAPTER
26190 @c ===============================
26192 @c ***********************************
26193 @c * Compatibility and Porting Guide *
26194 @c ***********************************
26195 @node Compatibility and Porting Guide
26196 @appendix Compatibility and Porting Guide
26198 @noindent
26199 This chapter describes the compatibility issues that may arise between
26200 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
26201 can expedite porting
26202 applications developed in other Ada environments.
26204 @menu
26205 * Compatibility with Ada 83::
26206 * Implementation-dependent characteristics::
26207 * Compatibility with Other Ada 95 Systems::
26208 * Representation Clauses::
26209 * Compatibility with DEC Ada 83::
26210 @ifset vms
26211 * Transitioning from Alpha to Integrity OpenVMS::
26212 @end ifset
26213 @end menu
26215 @node Compatibility with Ada 83
26216 @section Compatibility with Ada 83
26217 @cindex Compatibility (between Ada 83 and Ada 95)
26219 @noindent
26220 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
26221 particular, the design intention is that the difficulties associated
26222 with moving from Ada 83 to Ada 95 should be no greater than those
26223 that occur when moving from one Ada 83 system to another.
26225 However, there are a number of points at which there are minor
26226 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26227 full details of these issues,
26228 and should be consulted for a complete treatment.
26229 In practice the
26230 following subsections treat the most likely issues to be encountered.
26232 @menu
26233 * Legal Ada 83 programs that are illegal in Ada 95::
26234 * More deterministic semantics::
26235 * Changed semantics::
26236 * Other language compatibility issues::
26237 @end menu
26239 @node Legal Ada 83 programs that are illegal in Ada 95
26240 @subsection Legal Ada 83 programs that are illegal in Ada 95
26242 @table @asis
26243 @item Character literals
26244 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26245 @code{Wide_Character} as a new predefined character type, some uses of
26246 character literals that were legal in Ada 83 are illegal in Ada 95.
26247 For example:
26248 @smallexample @c ada
26249    for Char in 'A' .. 'Z' loop ... end loop;
26250 @end smallexample
26251 @noindent
26252 The problem is that @code{'A'} and @code{'Z'} could be from either
26253 @code{Character} or @code{Wide_Character}.  The simplest correction
26254 is to make the type explicit; e.g.:
26255 @smallexample @c ada
26256    for Char in Character range 'A' .. 'Z' loop ... end loop;
26257 @end smallexample
26259 @item New reserved words
26260 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26261 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26262 Existing Ada 83 code using any of these identifiers must be edited to
26263 use some alternative name.
26265 @item Freezing rules
26266 The rules in Ada 95 are slightly different with regard to the point at
26267 which entities are frozen, and representation pragmas and clauses are
26268 not permitted past the freeze point.  This shows up most typically in
26269 the form of an error message complaining that a representation item
26270 appears too late, and the appropriate corrective action is to move
26271 the item nearer to the declaration of the entity to which it refers.
26273 A particular case is that representation pragmas
26274 @ifset vms
26275 (including the
26276 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
26277 @end ifset
26278 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26279 declaration must be introduced to which the pragma can be applied.
26281 @item Optional bodies for library packages
26282 In Ada 83, a package that did not require a package body was nevertheless
26283 allowed to have one.  This lead to certain surprises in compiling large
26284 systems (situations in which the body could be unexpectedly ignored by the
26285 binder).  In Ada 95, if a package does not require a body then it is not
26286 permitted to have a body.  To fix this problem, simply remove a redundant
26287 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26288 into the spec that makes the body required.  One approach is to add a private
26289 part to the package declaration (if necessary), and define a parameterless
26290 procedure called @code{Requires_Body}, which must then be given a dummy
26291 procedure body in the package body, which then becomes required.
26292 Another approach (assuming that this does not introduce elaboration
26293 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26294 since one effect of this pragma is to require the presence of a package body.
26296 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26297 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26298 @code{Constraint_Error}.
26299 This means that it is illegal to have separate exception handlers for
26300 the two exceptions.  The fix is simply to remove the handler for the
26301 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26302 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26304 @item Indefinite subtypes in generics
26305 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26306 as the actual for a generic formal private type, but then the instantiation
26307 would be illegal if there were any instances of declarations of variables
26308 of this type in the generic body.  In Ada 95, to avoid this clear violation
26309 of the methodological principle known as the ``contract model'',
26310 the generic declaration explicitly indicates whether
26311 or not such instantiations are permitted.  If a generic formal parameter
26312 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26313 type name, then it can be instantiated with indefinite types, but no
26314 stand-alone variables can be declared of this type.  Any attempt to declare
26315 such a variable will result in an illegality at the time the generic is
26316 declared.  If the @code{(<>)} notation is not used, then it is illegal
26317 to instantiate the generic with an indefinite type.
26318 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26319 It will show up as a compile time error, and
26320 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26321 @end table
26323 @node More deterministic semantics
26324 @subsection More deterministic semantics
26326 @table @asis
26327 @item Conversions
26328 Conversions from real types to integer types round away from 0.  In Ada 83
26329 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26330 implementation freedom was intended to support unbiased rounding in
26331 statistical applications, but in practice it interfered with portability.
26332 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26333 is required.  Numeric code may be affected by this change in semantics.
26334 Note, though, that this issue is no worse than already existed in Ada 83
26335 when porting code from one vendor to another.
26337 @item Tasking
26338 The Real-Time Annex introduces a set of policies that define the behavior of
26339 features that were implementation dependent in Ada 83, such as the order in
26340 which open select branches are executed.
26341 @end table
26343 @node Changed semantics
26344 @subsection Changed semantics
26346 @noindent
26347 The worst kind of incompatibility is one where a program that is legal in
26348 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26349 possible in Ada 83.  Fortunately this is extremely rare, but the one
26350 situation that you should be alert to is the change in the predefined type
26351 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26353 @table @asis
26354 @item range of @code{Character}
26355 The range of @code{Standard.Character} is now the full 256 characters
26356 of Latin-1, whereas in most Ada 83 implementations it was restricted
26357 to 128 characters. Although some of the effects of
26358 this change will be manifest in compile-time rejection of legal
26359 Ada 83 programs it is possible for a working Ada 83 program to have
26360 a different effect in Ada 95, one that was not permitted in Ada 83.
26361 As an example, the expression
26362 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26363 delivers @code{255} as its value.
26364 In general, you should look at the logic of any
26365 character-processing Ada 83 program and see whether it needs to be adapted
26366 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26367 character handling package that may be relevant if code needs to be adapted
26368 to account for the additional Latin-1 elements.
26369 The desirable fix is to
26370 modify the program to accommodate the full character set, but in some cases
26371 it may be convenient to define a subtype or derived type of Character that
26372 covers only the restricted range.
26373 @cindex Latin-1
26374 @end table
26376 @node Other language compatibility issues
26377 @subsection Other language compatibility issues
26378 @table @asis
26379 @item @option{-gnat83 switch}
26380 All implementations of GNAT provide a switch that causes GNAT to operate
26381 in Ada 83 mode.  In this mode, some but not all compatibility problems
26382 of the type described above are handled automatically.  For example, the
26383 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
26384 However,
26385 in practice, it is usually advisable to make the necessary modifications
26386 to the program to remove the need for using this switch.
26387 See @ref{Compiling Ada 83 Programs}.
26389 @item Support for removed Ada 83 pragmas and attributes
26390 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
26391 generally because they have been replaced by other mechanisms.  Ada 95
26392 compilers are allowed, but not required, to implement these missing
26393 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
26394 such pragmas and attributes, eliminating this compatibility concern.  These
26395 include @code{pragma Interface} and the floating point type attributes
26396 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26397 @end table
26399 @node Implementation-dependent characteristics
26400 @section Implementation-dependent characteristics
26401 @noindent
26402 Although the Ada language defines the semantics of each construct as
26403 precisely as practical, in some situations (for example for reasons of
26404 efficiency, or where the effect is heavily dependent on the host or target
26405 platform) the implementation is allowed some freedom.  In porting Ada 83
26406 code to GNAT, you need to be aware of whether / how the existing code
26407 exercised such implementation dependencies.  Such characteristics fall into
26408 several categories, and GNAT offers specific support in assisting the
26409 transition from certain Ada 83 compilers.
26411 @menu
26412 * Implementation-defined pragmas::
26413 * Implementation-defined attributes::
26414 * Libraries::
26415 * Elaboration order::
26416 * Target-specific aspects::
26417 @end menu
26419 @node Implementation-defined pragmas
26420 @subsection Implementation-defined pragmas
26422 @noindent
26423 Ada compilers are allowed to supplement the language-defined pragmas, and
26424 these are a potential source of non-portability.  All GNAT-defined pragmas
26425 are described in the GNAT Reference Manual, and these include several that
26426 are specifically intended to correspond to other vendors' Ada 83 pragmas.
26427 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26429 compatibility with DEC Ada 83, GNAT supplies the pragmas
26430 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26431 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26432 and @code{Volatile}.
26433 Other relevant pragmas include @code{External} and @code{Link_With}.
26434 Some vendor-specific
26435 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26436 recognized, thus
26437 avoiding compiler rejection of units that contain such pragmas; they are not
26438 relevant in a GNAT context and hence are not otherwise implemented.
26440 @node Implementation-defined attributes
26441 @subsection Implementation-defined attributes
26443 Analogous to pragmas, the set of attributes may be extended by an
26444 implementation.  All GNAT-defined attributes are described in the
26445 @cite{GNAT Reference Manual}, and these include several that are specifically
26446 intended
26447 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26448 the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
26449 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26450 @code{Type_Class}.
26452 @node Libraries
26453 @subsection Libraries
26454 @noindent
26455 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26456 code uses vendor-specific libraries then there are several ways to manage
26457 this in Ada 95:
26458 @enumerate
26459 @item
26460 If the source code for the libraries (specifications and bodies) are
26461 available, then the libraries can be migrated in the same way as the
26462 application.
26463 @item
26464 If the source code for the specifications but not the bodies are
26465 available, then you can reimplement the bodies.
26466 @item
26467 Some new Ada 95 features obviate the need for library support.  For
26468 example most Ada 83 vendors supplied a package for unsigned integers.  The
26469 Ada 95 modular type feature is the preferred way to handle this need, so
26470 instead of migrating or reimplementing the unsigned integer package it may
26471 be preferable to retrofit the application using modular types.
26472 @end enumerate
26474 @node Elaboration order
26475 @subsection Elaboration order
26476 @noindent
26477 The implementation can choose any elaboration order consistent with the unit
26478 dependency relationship.  This freedom means that some orders can result in
26479 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26480 to invoke a subprogram its body has been elaborated, or to instantiate a
26481 generic before the generic body has been elaborated.  By default GNAT
26482 attempts to choose a safe order (one that will not encounter access before
26483 elaboration problems) by implicitly inserting Elaborate_All pragmas where
26484 needed.  However, this can lead to the creation of elaboration circularities
26485 and a resulting rejection of the program by gnatbind.  This issue is
26486 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26487 In brief, there are several
26488 ways to deal with this situation:
26490 @itemize @bullet
26491 @item
26492 Modify the program to eliminate the circularities, e.g. by moving
26493 elaboration-time code into explicitly-invoked procedures
26494 @item
26495 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26496 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26497 @code{Elaborate_All}
26498 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26499 (by selectively suppressing elaboration checks via pragma
26500 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26501 @end itemize
26503 @node Target-specific aspects
26504 @subsection Target-specific aspects
26505 @noindent
26506 Low-level applications need to deal with machine addresses, data
26507 representations, interfacing with assembler code, and similar issues.  If
26508 such an Ada 83 application is being ported to different target hardware (for
26509 example where the byte endianness has changed) then you will need to
26510 carefully examine the program logic; the porting effort will heavily depend
26511 on the robustness of the original design.  Moreover, Ada 95 is sometimes
26512 incompatible with typical Ada 83 compiler practices regarding implicit
26513 packing, the meaning of the Size attribute, and the size of access values.
26514 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26516 @node Compatibility with Other Ada 95 Systems
26517 @section Compatibility with Other Ada 95 Systems
26519 @noindent
26520 Providing that programs avoid the use of implementation dependent and
26521 implementation defined features of Ada 95, as documented in the Ada 95
26522 reference manual, there should be a high degree of portability between
26523 GNAT and other Ada 95 systems.  The following are specific items which
26524 have proved troublesome in moving GNAT programs to other Ada 95
26525 compilers, but do not affect porting code to GNAT@.
26527 @table @asis
26528 @item Ada 83 Pragmas and Attributes
26529 Ada 95 compilers are allowed, but not required, to implement the missing
26530 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26531 GNAT implements all such pragmas and attributes, eliminating this as
26532 a compatibility concern, but some other Ada 95 compilers reject these
26533 pragmas and attributes.
26535 @item Special-needs Annexes
26536 GNAT implements the full set of special needs annexes.  At the
26537 current time, it is the only Ada 95 compiler to do so.  This means that
26538 programs making use of these features may not be portable to other Ada
26539 95 compilation systems.
26541 @item Representation Clauses
26542 Some other Ada 95 compilers implement only the minimal set of
26543 representation clauses required by the Ada 95 reference manual.  GNAT goes
26544 far beyond this minimal set, as described in the next section.
26545 @end table
26547 @node Representation Clauses
26548 @section Representation Clauses
26550 @noindent
26551 The Ada 83 reference manual was quite vague in describing both the minimal
26552 required implementation of representation clauses, and also their precise
26553 effects.  The Ada 95 reference manual is much more explicit, but the minimal
26554 set of capabilities required in Ada 95 is quite limited.
26556 GNAT implements the full required set of capabilities described in the
26557 Ada 95 reference manual, but also goes much beyond this, and in particular
26558 an effort has been made to be compatible with existing Ada 83 usage to the
26559 greatest extent possible.
26561 A few cases exist in which Ada 83 compiler behavior is incompatible with
26562 requirements in the Ada 95 reference manual.  These are instances of
26563 intentional or accidental dependence on specific implementation dependent
26564 characteristics of these Ada 83 compilers.  The following is a list of
26565 the cases most likely to arise in existing legacy Ada 83 code.
26567 @table @asis
26568 @item Implicit Packing
26569 Some Ada 83 compilers allowed a Size specification to cause implicit
26570 packing of an array or record.  This could cause expensive implicit
26571 conversions for change of representation in the presence of derived
26572 types, and the Ada design intends to avoid this possibility.
26573 Subsequent AI's were issued to make it clear that such implicit
26574 change of representation in response to a Size clause is inadvisable,
26575 and this recommendation is represented explicitly in the Ada 95 RM
26576 as implementation advice that is followed by GNAT@.
26577 The problem will show up as an error
26578 message rejecting the size clause.  The fix is simply to provide
26579 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26580 a Component_Size clause.
26582 @item Meaning of Size Attribute
26583 The Size attribute in Ada 95 for discrete types is defined as being the
26584 minimal number of bits required to hold values of the type.  For example,
26585 on a 32-bit machine, the size of Natural will typically be 31 and not
26586 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26587 some 32 in this situation.  This problem will usually show up as a compile
26588 time error, but not always.  It is a good idea to check all uses of the
26589 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26590 Object_Size can provide a useful way of duplicating the behavior of
26591 some Ada 83 compiler systems.
26593 @item Size of Access Types
26594 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26595 and that therefore it will be the same size as a System.Address value.  This
26596 assumption is true for GNAT in most cases with one exception.  For the case of
26597 a pointer to an unconstrained array type (where the bounds may vary from one
26598 value of the access type to another), the default is to use a ``fat pointer'',
26599 which is represented as two separate pointers, one to the bounds, and one to
26600 the array.  This representation has a number of advantages, including improved
26601 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26602 code which makes the assumption that, for example, pointers fit in 32 bits on
26603 a machine with 32-bit addressing.
26605 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26606 access types in this case (where the designated type is an unconstrained array
26607 type).  These thin pointers are indeed the same size as a System.Address value.
26608 To specify a thin pointer, use a size clause for the type, for example:
26610 @smallexample @c ada
26611 type X is access all String;
26612 for X'Size use Standard'Address_Size;
26613 @end smallexample
26615 @noindent
26616 which will cause the type X to be represented using a single pointer.
26617 When using this representation, the bounds are right behind the array.
26618 This representation is slightly less efficient, and does not allow quite
26619 such flexibility in the use of foreign pointers or in using the
26620 Unrestricted_Access attribute to create pointers to non-aliased objects.
26621 But for any standard portable use of the access type it will work in
26622 a functionally correct manner and allow porting of existing code.
26623 Note that another way of forcing a thin pointer representation
26624 is to use a component size clause for the element size in an array,
26625 or a record representation clause for an access field in a record.
26626 @end table
26628 @node Compatibility with DEC Ada 83
26629 @section Compatibility with DEC Ada 83
26631 @noindent
26632 The VMS version of GNAT fully implements all the pragmas and attributes
26633 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
26634 libraries, including Starlet.  In addition, data layouts and parameter
26635 passing conventions are highly compatible.  This means that porting
26636 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
26637 most other porting efforts.  The following are some of the most
26638 significant differences between GNAT and DEC Ada 83.
26640 @table @asis
26641 @item Default floating-point representation
26642 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
26643 it is VMS format.  GNAT does implement the necessary pragmas
26644 (Long_Float, Float_Representation) for changing this default.
26646 @item System
26647 The package System in GNAT exactly corresponds to the definition in the
26648 Ada 95 reference manual, which means that it excludes many of the
26649 DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
26650 that contains the additional definitions, and a special pragma,
26651 Extend_System allows this package to be treated transparently as an
26652 extension of package System.
26654 @item To_Address
26655 The definitions provided by Aux_DEC are exactly compatible with those
26656 in the DEC Ada 83 version of System, with one exception.
26657 DEC Ada provides the following declarations:
26659 @smallexample @c ada
26660 TO_ADDRESS (INTEGER)
26661 TO_ADDRESS (UNSIGNED_LONGWORD)
26662 TO_ADDRESS (universal_integer)
26663 @end smallexample
26665 @noindent
26666 The version of TO_ADDRESS taking a universal integer argument is in fact
26667 an extension to Ada 83 not strictly compatible with the reference manual.
26668 In GNAT, we are constrained to be exactly compatible with the standard,
26669 and this means we cannot provide this capability.  In DEC Ada 83, the
26670 point of this definition is to deal with a call like:
26672 @smallexample @c ada
26673 TO_ADDRESS (16#12777#);
26674 @end smallexample
26676 @noindent
26677 Normally, according to the Ada 83 standard, one would expect this to be
26678 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26679 of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
26680 definition using universal_integer takes precedence.
26682 In GNAT, since the version with universal_integer cannot be supplied, it is
26683 not possible to be 100% compatible.  Since there are many programs using
26684 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26685 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26686 declarations provided in the GNAT version of AUX_Dec are:
26688 @smallexample @c ada
26689 function To_Address (X : Integer) return Address;
26690 pragma Pure_Function (To_Address);
26692 function To_Address_Long (X : Unsigned_Longword)
26693  return Address;
26694 pragma Pure_Function (To_Address_Long);
26695 @end smallexample
26697 @noindent
26698 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26699 change the name to TO_ADDRESS_LONG@.
26701 @item Task_Id values
26702 The Task_Id values assigned will be different in the two systems, and GNAT
26703 does not provide a specified value for the Task_Id of the environment task,
26704 which in GNAT is treated like any other declared task.
26705 @end table
26707 For full details on these and other less significant compatibility issues,
26708 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
26709 Overview and Comparison on DIGITAL Platforms}.
26711 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
26712 attributes are recognized, although only a subset of them can sensibly
26713 be implemented.  The description of pragmas in this reference manual
26714 indicates whether or not they are applicable to non-VMS systems.
26717 @ifset vms
26718 @node Transitioning from Alpha to Integrity OpenVMS
26719 @section Transitioning from Alpha to Integrity OpenVMS
26721 @menu
26722 * Introduction to transitioning::
26723 * Migration of 32 bit code::
26724 * Taking advantage of 64 bit addressing::
26725 * Technical details::
26726 @end menu
26728 @node Introduction to transitioning
26729 @subsection Introduction to transitioning
26731 @noindent
26732 This guide is meant to assist users of GNAT Pro
26733 for Alpha OpenVMS who are planning to transition to the IA64 architecture.
26734 GNAT Pro for Open VMS Integrity has been designed to meet
26735 three main goals:
26737 @enumerate
26738 @item
26739 Providing a full conforming implementation of the Ada 95 language
26741 @item
26742 Allowing maximum backward compatibility, thus easing migration of existing
26743 Ada source code
26745 @item
26746 Supplying a path for exploiting the full IA64 address range
26747 @end enumerate
26749 @noindent
26750 Ada's strong typing semantics has made it
26751 impractical to have different 32-bit and 64-bit modes. As soon as
26752 one object could possibly be outside the 32-bit address space, this
26753 would make it necessary for the @code{System.Address} type to be 64 bits.
26754 In particular, this would cause inconsistencies if 32-bit code is
26755 called from 64-bit code that raises an exception.
26757 This issue has been resolved by always using 64-bit addressing
26758 at the system level, but allowing for automatic conversions between
26759 32-bit and 64-bit addresses where required. Thus users who
26760 do not currently require 64-bit addressing capabilities, can
26761 recompile their code with only minimal changes (and indeed
26762 if the code is written in portable Ada, with no assumptions about
26763 the size of the @code{Address} type, then no changes at all are necessary).
26764 At the same time,
26765 this approach provides a simple, gradual upgrade path to future
26766 use of larger memories than available for 32-bit systems.
26767 Also, newly written applications or libraries will by default
26768 be fully compatible with future systems exploiting 64-bit
26769 addressing capabilities present in IA64.
26771 @ref{Migration of 32 bit code}, will focus on porting applications
26772 that do not require more than 2 GB of
26773 addressable memory. This code will be referred to as
26774 @emph{32-bit code}.
26775 For applications intending to exploit the full ia64 address space,
26776 @ref{Taking advantage of 64 bit addressing},
26777 will consider further changes that may be required.
26778 Such code is called @emph{64-bit code} in the
26779 remainder of this guide.
26782 @node Migration of 32 bit code
26783 @subsection Migration of 32-bit code
26785 @menu
26786 * Address types::
26787 * Access types::
26788 * Unchecked conversions::
26789 * Predefined constants::
26790 * Single source compatibility::
26791 * Experience with source compatibility::
26792 @end menu
26794 @node Address types
26795 @subsubsection Address types
26797 @noindent
26798 To solve the problem of mixing 64-bit and 32-bit addressing,
26799 while maintaining maximum backward compatibility, the following
26800 approach has been taken:
26802 @itemize @bullet
26803 @item
26804 @code{System.Address} always has a size of 64 bits
26806 @item
26807 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26808 @end itemize
26811 @noindent
26812 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26813 a @code{Short_Address}
26814 may be used where an @code{Address} is required, and vice versa, without
26815 needing explicit type conversions.
26816 By virtue of the Open VMS Integrity parameter passing conventions,
26817 even imported
26818 and exported subprograms that have 32-bit address parameters are
26819 compatible with those that have 64-bit address parameters.
26820 (See @ref{Making code 64 bit clean}, for details.)
26822 The areas that may need attention are those where record types have
26823 been defined that contain components of the type @code{System.Address}, and
26824 where objects of this type are passed to code expecting a record layout with
26825 32-bit addresses.
26827 Different compilers on different platforms cannot be
26828 expected to represent the same type in the same way,
26829 since alignment constraints
26830 and other system-dependent properties affect the compiler's decision.
26831 For that reason, Ada code
26832 generally uses representation clauses to specify the expected
26833 layout where required.
26835 If such a representation clause uses 32 bits for a component having
26836 the type @code{System.Address}, GNAT Pro for OpenVMS Integrity will detect
26837 that error and produce a specific diagnostic message.
26838 The developer should then determine whether the representation
26839 should be 64 bits or not and make either of two changes:
26840 change the size to 64 bits and leave the type as @code{System.Address}, or
26841 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26842 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26843 required in any code setting or accessing the field; the compiler will
26844 automatically perform any needed conversions between address
26845 formats.
26847 @node Access types
26848 @subsubsection Access types
26850 @noindent
26851 By default, objects designated by access values are always
26852 allocated in the 32-bit
26853 address space. Thus legacy code will never contain
26854 any objects that are not addressable with 32-bit addresses, and
26855 the compiler will never raise exceptions as result of mixing
26856 32-bit and 64-bit addresses.
26858 However, the access values themselves are represented in 64 bits, for optimum
26859 performance and future compatibility with 64-bit code. As was
26860 the case with @code{System.Address}, the compiler will give an error message
26861 if an object or record component has a representation clause that
26862 requires the access value to fit in 32 bits. In such a situation,
26863 an explicit size clause for the access type, specifying 32 bits,
26864 will have the desired effect.
26866 General access types (declared with @code{access all}) can never be
26867 32 bits, as values of such types must be able to refer to any object
26868 of the  designated type,
26869 including objects residing outside the 32-bit address range.
26870 Existing Ada 83 code will not contain such type definitions,
26871 however, since general access types were introduced in Ada 95.
26873 @node Unchecked conversions
26874 @subsubsection Unchecked conversions
26876 @noindent
26877 In the case of an @code{Unchecked_Conversion} where the source type is a
26878 64-bit access type or the type @code{System.Address}, and the target
26879 type is a 32-bit type, the compiler will generate a warning.
26880 Even though the generated code will still perform the required
26881 conversions, it is highly recommended in these cases to use
26882 respectively a 32-bit access type or @code{System.Short_Address}
26883 as the source type.
26885 @node Predefined constants
26886 @subsubsection Predefined constants
26888 @noindent
26889 The following predefined constants have changed:
26891 @multitable {@code{System.Address_Size}} {2**32} {2**64}
26892 @item   @b{Constant}               @tab @b{Old} @tab @b{New}
26893 @item   @code{System.Word_Size}    @tab 32      @tab 64
26894 @item   @code{System.Memory_Size}  @tab 2**32   @tab 2**64
26895 @item   @code{System.Address_Size} @tab 32      @tab 64
26896 @end multitable
26898 @noindent
26899 If you need to refer to the specific
26900 memory size of a 32-bit implementation, instead of the
26901 actual memory size, use @code{System.Short_Memory_Size}
26902 rather than @code{System.Memory_Size}.
26903 Similarly, references to @code{System.Address_Size} may need
26904 to be replaced by @code{System.Short_Address'Size}.
26905 The program @command{gnatfind} may be useful for locating
26906 references to the above constants, so that you can verify that they
26907 are still correct.
26909 @node Single source compatibility
26910 @subsubsection Single source compatibility
26912 @noindent
26913 In order to allow the same source code to be compiled on
26914 both Alpha and IA64 platforms, GNAT Pro for Alpha/OpenVMS
26915 defines @code{System.Short_Address} and System.Short_Memory_Size
26916 as aliases of respectively @code{System.Address} and
26917 @code{System.Memory_Size}.
26918 (These aliases also leave the door open for a possible
26919 future ``upgrade'' of OpenVMS Alpha to a 64-bit address space.)
26921 @node Experience with source compatibility
26922 @subsubsection Experience with source compatibility
26924 @noindent
26925 The Security Server and STARLET provide an interesting ``test case''
26926 for source compatibility issues, since it is in such system code
26927 where assumptions about @code{Address} size might be expected to occur.
26928 Indeed, there were a small number of occasions in the Security Server
26929 file @file{jibdef.ads}
26930 where a representation clause for a record type specified
26931 32 bits for a component of type @code{Address}.
26932 All of these errors were detected by the compiler.
26933 The repair was obvious and immediate; to simply replace @code{Address} by
26934 @code{Short_Address}.
26936 In the case of STARLET, there were several record types that should
26937 have had representation clauses but did not.  In these record types
26938 there was an implicit assumption that an @code{Address} value occupied
26939 32 bits.
26940 These compiled without error, but their usage resulted in run-time error
26941 returns from STARLET system calls.
26942 To assist in the compile-time detection of such situations, we
26943 plan to include a switch to generate a warning message when a
26944 record component is of type @code{Address}.
26947 @c ****************************************
26948 @node Taking advantage of 64 bit addressing
26949 @subsection Taking advantage of 64-bit addressing
26951 @menu
26952 * Making code 64 bit clean::
26953 * Allocating memory from the 64 bit storage pool::
26954 * Restrictions on use of 64 bit objects::
26955 * Using 64 bit storage pools by default::
26956 * General access types::
26957 * STARLET and other predefined libraries::
26958 @end menu
26960 @node Making code 64 bit clean
26961 @subsubsection Making code 64-bit clean
26963 @noindent
26964 In order to prevent problems that may occur when (parts of) a
26965 system start using memory outside the 32-bit address range,
26966 we recommend some additional guidelines:
26968 @itemize @bullet
26969 @item
26970 For imported subprograms that take parameters of the
26971 type @code{System.Address}, ensure that these subprograms can
26972 indeed handle 64-bit addresses. If not, or when in doubt,
26973 change the subprogram declaration to specify
26974 @code{System.Short_Address} instead.
26976 @item
26977 Resolve all warnings related to size mismatches in
26978 unchecked conversions. Failing to do so causes
26979 erroneous execution if the source object is outside
26980 the 32-bit address space.
26982 @item
26983 (optional) Explicitly use the 32-bit storage pool
26984 for access types used in a 32-bit context, or use
26985 generic access types where possible
26986 (see @ref{Restrictions on use of 64 bit objects}).
26987 @end itemize
26989 @noindent
26990 If these rules are followed, the compiler will automatically insert
26991 any necessary checks to ensure that no addresses or access values
26992 passed to 32-bit code ever refer to objects outside the 32-bit
26993 address range.
26994 Any attempt to do this will raise @code{Constraint_Error}.
26996 @node Allocating memory from the 64 bit storage pool
26997 @subsubsection Allocating memory from the 64-bit storage pool
26999 @noindent
27000 For any access type @code{T} that potentially requires memory allocations
27001 beyond the 32-bit address space,
27002 use the following representation clause:
27004 @smallexample @c ada
27005    for T'Storage_Pool use System.Pool_64;
27006 @end smallexample
27009 @node Restrictions on use of 64 bit objects
27010 @subsubsection Restrictions on use of 64-bit objects
27012 @noindent
27013 Taking the address of an object allocated from a 64-bit storage pool,
27014 and then passing this address to a subprogram expecting
27015 @code{System.Short_Address},
27016 or assigning it to a variable of type @code{Short_Address}, will cause
27017 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
27018 (see @ref{Making code 64 bit clean}), or checks are suppressed,
27019 no exception is raised and execution
27020 will become erroneous.
27022 @node Using 64 bit storage pools by default
27023 @subsubsection Using 64-bit storage pools by default
27025 @noindent
27026 In some cases it may be desirable to have the compiler allocate
27027 from 64-bit storage pools by default. This may be the case for
27028 libraries that are 64-bit clean, but may be used in both 32-bit
27029 and 64-bit contexts. For these cases the following configuration
27030 pragma may be specified:
27032 @smallexample @c ada
27033   pragma Pool_64_Default;
27034 @end smallexample
27036 @noindent
27037 Any code compiled in the context of this pragma will by default
27038 use the @code{System.Pool_64} storage pool. This default may be overridden
27039 for a specific access type @code{T} by the representation clause:
27041 @smallexample @c ada
27042    for T'Storage_Pool use System.Pool_32;
27043 @end smallexample
27045 @noindent
27046 Any object whose address may be passed to a subprogram with a
27047 @code{Short_Address} argument, or assigned to a variable of type
27048 @code{Short_Address}, needs to be allocated from this pool.
27050 @node General access types
27051 @subsubsection General access types
27053 @noindent
27054 Objects designated by access values from a
27055 general access type (declared with @code{access all}) are never allocated
27056 from a 64-bit storage pool. Code that uses general access types will
27057 accept objects allocated in either 32-bit or 64-bit address spaces,
27058 but never allocate objects outside the 32-bit address space.
27059 Using general access types ensures maximum compatibility with both
27060 32-bit and 64-bit code.
27063 @node STARLET and other predefined libraries
27064 @subsubsection STARLET and other predefined libraries
27066 @noindent
27067 All code that comes as part of GNAT is 64-bit clean, but the
27068 restrictions given in @ref{Restrictions on use of 64 bit objects},
27069 still apply. Look at the package
27070 specifications to see in which contexts objects allocated
27071 in 64-bit address space are acceptable.
27073 @node Technical details
27074 @subsection Technical details
27076 @noindent
27077 GNAT Pro for Open VMS Integrity takes advantage of the freedom given in the Ada
27078 standard with respect to the type of @code{System.Address}. Previous versions
27079 of GNAT Pro have defined this type as private and implemented it as
27080 a modular type.
27082 In order to allow defining @code{System.Short_Address} as a proper subtype,
27083 and to match the implicit sign extension in parameter passing,
27084 in GNAT Pro for Open VMS Integrity, @code{System.Address} is defined as a
27085 visible (i.e., non-private) integer type.
27086 Standard operations on the type, such as the binary operators ``+'', ``-'',
27087 etc., that take @code{Address} operands and return an @code{Address} result,
27088 have been hidden by declaring these
27089 @code{abstract}, an Ada 95 feature that helps avoid the potential ambiguities
27090 that would otherwise result from overloading.
27091 (Note that, although @code{Address} is a visible integer type,
27092 good programming practice dictates against exploiting the type's
27093 integer properties such as literals, since this will compromise
27094 code portability.)
27096 Defining @code{Address} as a visible integer type helps achieve
27097 maximum compatibility for existing Ada code,
27098 without sacrificing the capabilities of the IA64 architecture.
27099 @end ifset
27102 @c ************************************************
27103 @ifset unw
27104 @node Microsoft Windows Topics
27105 @appendix Microsoft Windows Topics
27106 @cindex Windows NT
27107 @cindex Windows 95
27108 @cindex Windows 98
27110 @noindent
27111 This chapter describes topics that are specific to the Microsoft Windows
27112 platforms (NT, 2000, and XP Professional).
27114 @menu
27115 * Using GNAT on Windows::
27116 * Using a network installation of GNAT::
27117 * CONSOLE and WINDOWS subsystems::
27118 * Temporary Files::
27119 * Mixed-Language Programming on Windows::
27120 * Windows Calling Conventions::
27121 * Introduction to Dynamic Link Libraries (DLLs)::
27122 * Using DLLs with GNAT::
27123 * Building DLLs with GNAT::
27124 * Building DLLs with GNAT Project files::
27125 * Building DLLs with gnatdll::
27126 * GNAT and Windows Resources::
27127 * Debugging a DLL::
27128 * GNAT and COM/DCOM Objects::
27129 @end menu
27131 @node Using GNAT on Windows
27132 @section Using GNAT on Windows
27134 @noindent
27135 One of the strengths of the GNAT technology is that its tool set
27136 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
27137 @code{gdb} debugger, etc.) is used in the same way regardless of the
27138 platform.
27140 On Windows this tool set is complemented by a number of Microsoft-specific
27141 tools that have been provided to facilitate interoperability with Windows
27142 when this is required. With these tools:
27144 @itemize @bullet
27146 @item
27147 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27148 subsystems.
27150 @item
27151 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27152 relocatable and non-relocatable DLLs are supported).
27154 @item
27155 You can build Ada DLLs for use in other applications. These applications
27156 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27157 relocatable and non-relocatable Ada DLLs are supported.
27159 @item
27160 You can include Windows resources in your Ada application.
27162 @item
27163 You can use or create COM/DCOM objects.
27164 @end itemize
27166 @noindent
27167 Immediately below are listed all known general GNAT-for-Windows restrictions.
27168 Other restrictions about specific features like Windows Resources and DLLs
27169 are listed in separate sections below.
27171 @itemize @bullet
27173 @item
27174 It is not possible to use @code{GetLastError} and @code{SetLastError}
27175 when tasking, protected records, or exceptions are used. In these
27176 cases, in order to implement Ada semantics, the GNAT run-time system
27177 calls certain Win32 routines that set the last error variable to 0 upon
27178 success. It should be possible to use @code{GetLastError} and
27179 @code{SetLastError} when tasking, protected record, and exception
27180 features are not used, but it is not guaranteed to work.
27182 @item
27183 It is not possible to link against Microsoft libraries except for
27184 import libraries. The library must be built to be compatible with
27185 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
27186 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
27187 not be compatible with the GNAT runtime. Even if the library is
27188 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
27190 @item
27191 When the compilation environment is located on FAT32 drives, users may
27192 experience recompilations of the source files that have not changed if
27193 Daylight Saving Time (DST) state has changed since the last time files
27194 were compiled. NTFS drives do not have this problem.
27196 @item
27197 No components of the GNAT toolset use any entries in the Windows
27198 registry. The only entries that can be created are file associations and
27199 PATH settings, provided the user has chosen to create them at installation
27200 time, as well as some minimal book-keeping information needed to correctly
27201 uninstall or integrate different GNAT products.
27202 @end itemize
27204 @node Using a network installation of GNAT
27205 @section Using a network installation of GNAT
27207 @noindent
27208 Make sure the system on which GNAT is installed is accessible from the
27209 current machine, i.e. the install location is shared over the network.
27210 Shared resources are accessed on Windows by means of UNC paths, which
27211 have the format @code{\\server\sharename\path}
27213 In order to use such a network installation, simply add the UNC path of the
27214 @file{bin} directory of your GNAT installation in front of your PATH. For
27215 example, if GNAT is installed in @file{\GNAT} directory of a share location
27216 called @file{c-drive} on a machine @file{LOKI}, the following command will
27217 make it available:
27219 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27221 Be aware that every compilation using the network installation results in the
27222 transfer of large amounts of data across the network and will likely cause
27223 serious performance penalty.
27225 @node CONSOLE and WINDOWS subsystems
27226 @section CONSOLE and WINDOWS subsystems
27227 @cindex CONSOLE Subsystem
27228 @cindex WINDOWS Subsystem
27229 @cindex -mwindows
27231 @noindent
27232 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27233 (which is the default subsystem) will always create a console when
27234 launching the application. This is not something desirable when the
27235 application has a Windows GUI. To get rid of this console the
27236 application must be using the @code{WINDOWS} subsystem. To do so
27237 the @option{-mwindows} linker option must be specified.
27239 @smallexample
27240 $ gnatmake winprog -largs -mwindows
27241 @end smallexample
27243 @node Temporary Files
27244 @section Temporary Files
27245 @cindex Temporary files
27247 @noindent
27248 It is possible to control where temporary files gets created by setting
27249 the TMP environment variable. The file will be created:
27251 @itemize
27252 @item Under the directory pointed to by the TMP environment variable if
27253 this directory exists.
27255 @item Under c:\temp, if the TMP environment variable is not set (or not
27256 pointing to a directory) and if this directory exists.
27258 @item Under the current working directory otherwise.
27259 @end itemize
27261 @noindent
27262 This allows you to determine exactly where the temporary
27263 file will be created. This is particularly useful in networked
27264 environments where you may not have write access to some
27265 directories.
27267 @node Mixed-Language Programming on Windows
27268 @section Mixed-Language Programming on Windows
27270 @noindent
27271 Developing pure Ada applications on Windows is no different than on
27272 other GNAT-supported platforms. However, when developing or porting an
27273 application that contains a mix of Ada and C/C++, the choice of your
27274 Windows C/C++ development environment conditions your overall
27275 interoperability strategy.
27277 If you use @code{gcc} to compile the non-Ada part of your application,
27278 there are no Windows-specific restrictions that affect the overall
27279 interoperability with your Ada code. If you plan to use
27280 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
27281 the following limitations:
27283 @itemize @bullet
27284 @item
27285 You cannot link your Ada code with an object or library generated with
27286 Microsoft tools if these use the @code{.tls} section (Thread Local
27287 Storage section) since the GNAT linker does not yet support this section.
27289 @item
27290 You cannot link your Ada code with an object or library generated with
27291 Microsoft tools if these use I/O routines other than those provided in
27292 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
27293 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
27294 libraries can cause a conflict with @code{msvcrt.dll} services. For
27295 instance Visual C++ I/O stream routines conflict with those in
27296 @code{msvcrt.dll}.
27297 @end itemize
27299 @noindent
27300 If you do want to use the Microsoft tools for your non-Ada code and hit one
27301 of the above limitations, you have two choices:
27303 @enumerate
27304 @item
27305 Encapsulate your non Ada code in a DLL to be linked with your Ada
27306 application. In this case, use the Microsoft or whatever environment to
27307 build the DLL and use GNAT to build your executable
27308 (@pxref{Using DLLs with GNAT}).
27310 @item
27311 Or you can encapsulate your Ada code in a DLL to be linked with the
27312 other part of your application. In this case, use GNAT to build the DLL
27313 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
27314 environment to build your executable.
27315 @end enumerate
27317 @node Windows Calling Conventions
27318 @section Windows Calling Conventions
27319 @findex Stdcall
27320 @findex APIENTRY
27322 @menu
27323 * C Calling Convention::
27324 * Stdcall Calling Convention::
27325 * DLL Calling Convention::
27326 @end menu
27328 @noindent
27329 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27330 (callee), there are several ways to push @code{G}'s parameters on the
27331 stack and there are several possible scenarios to clean up the stack
27332 upon @code{G}'s return. A calling convention is an agreed upon software
27333 protocol whereby the responsibilities between the caller (@code{F}) and
27334 the callee (@code{G}) are clearly defined. Several calling conventions
27335 are available for Windows:
27337 @itemize @bullet
27338 @item
27339 @code{C} (Microsoft defined)
27341 @item
27342 @code{Stdcall} (Microsoft defined)
27344 @item
27345 @code{DLL} (GNAT specific)
27346 @end itemize
27348 @node C Calling Convention
27349 @subsection @code{C} Calling Convention
27351 @noindent
27352 This is the default calling convention used when interfacing to C/C++
27353 routines compiled with either @code{gcc} or Microsoft Visual C++.
27355 In the @code{C} calling convention subprogram parameters are pushed on the
27356 stack by the caller from right to left. The caller itself is in charge of
27357 cleaning up the stack after the call. In addition, the name of a routine
27358 with @code{C} calling convention is mangled by adding a leading underscore.
27360 The name to use on the Ada side when importing (or exporting) a routine
27361 with @code{C} calling convention is the name of the routine. For
27362 instance the C function:
27364 @smallexample
27365 int get_val (long);
27366 @end smallexample
27368 @noindent
27369 should be imported from Ada as follows:
27371 @smallexample @c ada
27372 @group
27373 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27374 pragma Import (C, Get_Val, External_Name => "get_val");
27375 @end group
27376 @end smallexample
27378 @noindent
27379 Note that in this particular case the @code{External_Name} parameter could
27380 have been omitted since, when missing, this parameter is taken to be the
27381 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27382 is missing, as in the above example, this parameter is set to be the
27383 @code{External_Name} with a leading underscore.
27385 When importing a variable defined in C, you should always use the @code{C}
27386 calling convention unless the object containing the variable is part of a
27387 DLL (in which case you should use the @code{DLL} calling convention,
27388 @pxref{DLL Calling Convention}).
27390 @node Stdcall Calling Convention
27391 @subsection @code{Stdcall} Calling Convention
27393 @noindent
27394 This convention, which was the calling convention used for Pascal
27395 programs, is used by Microsoft for all the routines in the Win32 API for
27396 efficiency reasons. It must be used to import any routine for which this
27397 convention was specified.
27399 In the @code{Stdcall} calling convention subprogram parameters are pushed
27400 on the stack by the caller from right to left. The callee (and not the
27401 caller) is in charge of cleaning the stack on routine exit. In addition,
27402 the name of a routine with @code{Stdcall} calling convention is mangled by
27403 adding a leading underscore (as for the @code{C} calling convention) and a
27404 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
27405 bytes) of the parameters passed to the routine.
27407 The name to use on the Ada side when importing a C routine with a
27408 @code{Stdcall} calling convention is the name of the C routine. The leading
27409 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
27410 the compiler. For instance the Win32 function:
27412 @smallexample
27413 @b{APIENTRY} int get_val (long);
27414 @end smallexample
27416 @noindent
27417 should be imported from Ada as follows:
27419 @smallexample @c ada
27420 @group
27421 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27422 pragma Import (Stdcall, Get_Val);
27423 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27424 @end group
27425 @end smallexample
27427 @noindent
27428 As for the @code{C} calling convention, when the @code{External_Name}
27429 parameter is missing, it is taken to be the name of the Ada entity in lower
27430 case. If instead of writing the above import pragma you write:
27432 @smallexample @c ada
27433 @group
27434 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27435 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27436 @end group
27437 @end smallexample
27439 @noindent
27440 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27441 of specifying the @code{External_Name} parameter you specify the
27442 @code{Link_Name} as in the following example:
27444 @smallexample @c ada
27445 @group
27446 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27447 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27448 @end group
27449 @end smallexample
27451 @noindent
27452 then the imported routine is @code{retrieve_val@@4}, that is, there is no
27453 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
27454 added at the end of the @code{Link_Name} by the compiler.
27456 @noindent
27457 Note, that in some special cases a DLL's entry point name lacks a trailing
27458 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
27459 The @code{gnatdll} tool, which creates the import library for the DLL, is able
27460 to handle those cases (see the description of the switches in
27461 @pxref{Using gnatdll} section).
27463 @node DLL Calling Convention
27464 @subsection @code{DLL} Calling Convention
27466 @noindent
27467 This convention, which is GNAT-specific, must be used when you want to
27468 import in Ada a variables defined in a DLL. For functions and procedures
27469 this convention is equivalent to the @code{Stdcall} convention. As an
27470 example, if a DLL contains a variable defined as:
27472 @smallexample
27473 int my_var;
27474 @end smallexample
27476 @noindent
27477 then, to access this variable from Ada you should write:
27479 @smallexample @c ada
27480 @group
27481 My_Var : Interfaces.C.int;
27482 pragma Import (DLL, My_Var);
27483 @end group
27484 @end smallexample
27486 The remarks concerning the @code{External_Name} and @code{Link_Name}
27487 parameters given in the previous sections equally apply to the @code{DLL}
27488 calling convention.
27490 @node Introduction to Dynamic Link Libraries (DLLs)
27491 @section Introduction to Dynamic Link Libraries (DLLs)
27492 @findex DLL
27494 @noindent
27495 A Dynamically Linked Library (DLL) is a library that can be shared by
27496 several applications running under Windows. A DLL can contain any number of
27497 routines and variables.
27499 One advantage of DLLs is that you can change and enhance them without
27500 forcing all the applications that depend on them to be relinked or
27501 recompiled. However, you should be aware than all calls to DLL routines are
27502 slower since, as you will understand below, such calls are indirect.
27504 To illustrate the remainder of this section, suppose that an application
27505 wants to use the services of a DLL @file{API.dll}. To use the services
27506 provided by @file{API.dll} you must statically link against the DLL or
27507 an import library which contains a jump table with an entry for each
27508 routine and variable exported by the DLL. In the Microsoft world this
27509 import library is called @file{API.lib}. When using GNAT this import
27510 library is called either @file{libAPI.a} or @file{libapi.a} (names are
27511 case insensitive).
27513 After you have linked your application with the DLL or the import library
27514 and you run your application, here is what happens:
27516 @enumerate
27517 @item
27518 Your application is loaded into memory.
27520 @item
27521 The DLL @file{API.dll} is mapped into the address space of your
27522 application. This means that:
27524 @itemize @bullet
27525 @item
27526 The DLL will use the stack of the calling thread.
27528 @item
27529 The DLL will use the virtual address space of the calling process.
27531 @item
27532 The DLL will allocate memory from the virtual address space of the calling
27533 process.
27535 @item
27536 Handles (pointers) can be safely exchanged between routines in the DLL
27537 routines and routines in the application using the DLL.
27538 @end itemize
27540 @item
27541 The entries in the jump table (from the import library @file{libAPI.a}
27542 or @file{API.lib} or automatically created when linking against a DLL)
27543 which is part of your application are initialized with the addresses
27544 of the routines and variables in @file{API.dll}.
27546 @item
27547 If present in @file{API.dll}, routines @code{DllMain} or
27548 @code{DllMainCRTStartup} are invoked. These routines typically contain
27549 the initialization code needed for the well-being of the routines and
27550 variables exported by the DLL.
27551 @end enumerate
27553 @noindent
27554 There is an additional point which is worth mentioning. In the Windows
27555 world there are two kind of DLLs: relocatable and non-relocatable
27556 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27557 in the target application address space. If the addresses of two
27558 non-relocatable DLLs overlap and these happen to be used by the same
27559 application, a conflict will occur and the application will run
27560 incorrectly. Hence, when possible, it is always preferable to use and
27561 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27562 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27563 User's Guide) removes the debugging symbols from the DLL but the DLL can
27564 still be relocated.
27566 As a side note, an interesting difference between Microsoft DLLs and
27567 Unix shared libraries, is the fact that on most Unix systems all public
27568 routines are exported by default in a Unix shared library, while under
27569 Windows it is possible (but not required) to list exported routines in
27570 a definition file (@pxref{The Definition File}).
27572 @node Using DLLs with GNAT
27573 @section Using DLLs with GNAT
27575 @menu
27576 * Creating an Ada Spec for the DLL Services::
27577 * Creating an Import Library::
27578 @end menu
27580 @noindent
27581 To use the services of a DLL, say @file{API.dll}, in your Ada application
27582 you must have:
27584 @enumerate
27585 @item
27586 The Ada spec for the routines and/or variables you want to access in
27587 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27588 header files provided with the DLL.
27590 @item
27591 The import library (@file{libAPI.a} or @file{API.lib}). As previously
27592 mentioned an import library is a statically linked library containing the
27593 import table which will be filled at load time to point to the actual
27594 @file{API.dll} routines. Sometimes you don't have an import library for the
27595 DLL you want to use. The following sections will explain how to build
27596 one. Note that this is optional.
27598 @item
27599 The actual DLL, @file{API.dll}.
27600 @end enumerate
27602 @noindent
27603 Once you have all the above, to compile an Ada application that uses the
27604 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27605 you simply issue the command
27607 @smallexample
27608 $ gnatmake my_ada_app -largs -lAPI
27609 @end smallexample
27611 @noindent
27612 The argument @option{-largs -lAPI} at the end of the @code{gnatmake} command
27613 tells the GNAT linker to look first for a library named @file{API.lib}
27614 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
27615 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
27616 contains the following pragma
27618 @smallexample @c ada
27619 pragma Linker_Options ("-lAPI");
27620 @end smallexample
27622 @noindent
27623 you do not have to add @option{-largs -lAPI} at the end of the @code{gnatmake}
27624 command.
27626 If any one of the items above is missing you will have to create it
27627 yourself. The following sections explain how to do so using as an
27628 example a fictitious DLL called @file{API.dll}.
27630 @node Creating an Ada Spec for the DLL Services
27631 @subsection Creating an Ada Spec for the DLL Services
27633 @noindent
27634 A DLL typically comes with a C/C++ header file which provides the
27635 definitions of the routines and variables exported by the DLL. The Ada
27636 equivalent of this header file is a package spec that contains definitions
27637 for the imported entities. If the DLL you intend to use does not come with
27638 an Ada spec you have to generate one such spec yourself. For example if
27639 the header file of @file{API.dll} is a file @file{api.h} containing the
27640 following two definitions:
27642 @smallexample
27643 @group
27644 @cartouche
27645 int some_var;
27646 int get (char *);
27647 @end cartouche
27648 @end group
27649 @end smallexample
27651 @noindent
27652 then the equivalent Ada spec could be:
27654 @smallexample @c ada
27655 @group
27656 @cartouche
27657 with Interfaces.C.Strings;
27658 package API is
27659    use Interfaces;
27661    Some_Var : C.int;
27662    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27664 private
27665    pragma Import (C, Get);
27666    pragma Import (DLL, Some_Var);
27667 end API;
27668 @end cartouche
27669 @end group
27670 @end smallexample
27672 @noindent
27673 Note that a variable is @strong{always imported with a DLL convention}. A
27674 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
27675 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
27676 (@pxref{Windows Calling Conventions}).
27678 @node Creating an Import Library
27679 @subsection Creating an Import Library
27680 @cindex Import library
27682 @menu
27683 * The Definition File::
27684 * GNAT-Style Import Library::
27685 * Microsoft-Style Import Library::
27686 @end menu
27688 @noindent
27689 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27690 import library @file{libAPI.a} is available with @file{API.dll} you
27691 can skip this section. You can also skip this section if
27692 @file{API.dll} is built with GNU tools as in this case it is possible
27693 to link directly against the DLL. Otherwise read on.
27695 @node The Definition File
27696 @subsubsection The Definition File
27697 @cindex Definition file
27698 @findex .def
27700 @noindent
27701 As previously mentioned, and unlike Unix systems, the list of symbols
27702 that are exported from a DLL must be provided explicitly in Windows.
27703 The main goal of a definition file is precisely that: list the symbols
27704 exported by a DLL. A definition file (usually a file with a @code{.def}
27705 suffix) has the following structure:
27707 @smallexample
27708 @group
27709 @cartouche
27710 [LIBRARY @i{name}]
27711 [DESCRIPTION @i{string}]
27712 EXPORTS
27713    @i{symbol1}
27714    @i{symbol2}
27715    ...
27716 @end cartouche
27717 @end group
27718 @end smallexample
27720 @table @code
27721 @item LIBRARY @i{name}
27722 This section, which is optional, gives the name of the DLL.
27724 @item DESCRIPTION @i{string}
27725 This section, which is optional, gives a description string that will be
27726 embedded in the import library.
27728 @item EXPORTS
27729 This section gives the list of exported symbols (procedures, functions or
27730 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27731 section of @file{API.def} looks like:
27733 @smallexample
27734 @group
27735 @cartouche
27736 EXPORTS
27737    some_var
27738    get
27739 @end cartouche
27740 @end group
27741 @end smallexample
27742 @end table
27744 @noindent
27745 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
27746 (@pxref{Windows Calling Conventions}) for a Stdcall
27747 calling convention function in the exported symbols list.
27749 @noindent
27750 There can actually be other sections in a definition file, but these
27751 sections are not relevant to the discussion at hand.
27753 @node GNAT-Style Import Library
27754 @subsubsection GNAT-Style Import Library
27756 @noindent
27757 To create a static import library from @file{API.dll} with the GNAT tools
27758 you should proceed as follows:
27760 @enumerate
27761 @item
27762 Create the definition file @file{API.def} (@pxref{The Definition File}).
27763 For that use the @code{dll2def} tool as follows:
27765 @smallexample
27766 $ dll2def API.dll > API.def
27767 @end smallexample
27769 @noindent
27770 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27771 to standard output the list of entry points in the DLL. Note that if
27772 some routines in the DLL have the @code{Stdcall} convention
27773 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
27774 suffix then you'll have to edit @file{api.def} to add it, and specify
27775 @code{-k} to @code{gnatdll} when creating the import library.
27777 @noindent
27778 Here are some hints to find the right @code{@@}@i{nn} suffix.
27780 @enumerate
27781 @item
27782 If you have the Microsoft import library (.lib), it is possible to get
27783 the right symbols by using Microsoft @code{dumpbin} tool (see the
27784 corresponding Microsoft documentation for further details).
27786 @smallexample
27787 $ dumpbin /exports api.lib
27788 @end smallexample
27790 @item
27791 If you have a message about a missing symbol at link time the compiler
27792 tells you what symbol is expected. You just have to go back to the
27793 definition file and add the right suffix.
27794 @end enumerate
27796 @item
27797 Build the import library @code{libAPI.a}, using @code{gnatdll}
27798 (@pxref{Using gnatdll}) as follows:
27800 @smallexample
27801 $ gnatdll -e API.def -d API.dll
27802 @end smallexample
27804 @noindent
27805 @code{gnatdll} takes as input a definition file @file{API.def} and the
27806 name of the DLL containing the services listed in the definition file
27807 @file{API.dll}. The name of the static import library generated is
27808 computed from the name of the definition file as follows: if the
27809 definition file name is @i{xyz}@code{.def}, the import library name will
27810 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
27811 @option{-e} could have been removed because the name of the definition
27812 file (before the ``@code{.def}'' suffix) is the same as the name of the
27813 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27814 @end enumerate
27816 @node Microsoft-Style Import Library
27817 @subsubsection Microsoft-Style Import Library
27819 @noindent
27820 With GNAT you can either use a GNAT-style or Microsoft-style import
27821 library. A Microsoft import library is needed only if you plan to make an
27822 Ada DLL available to applications developed with Microsoft
27823 tools (@pxref{Mixed-Language Programming on Windows}).
27825 To create a Microsoft-style import library for @file{API.dll} you
27826 should proceed as follows:
27828 @enumerate
27829 @item
27830 Create the definition file @file{API.def} from the DLL. For this use either
27831 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27832 tool (see the corresponding Microsoft documentation for further details).
27834 @item
27835 Build the actual import library using Microsoft's @code{lib} utility:
27837 @smallexample
27838 $ lib -machine:IX86 -def:API.def -out:API.lib
27839 @end smallexample
27841 @noindent
27842 If you use the above command the definition file @file{API.def} must
27843 contain a line giving the name of the DLL:
27845 @smallexample
27846 LIBRARY      "API"
27847 @end smallexample
27849 @noindent
27850 See the Microsoft documentation for further details about the usage of
27851 @code{lib}.
27852 @end enumerate
27854 @node Building DLLs with GNAT
27855 @section Building DLLs with GNAT
27856 @cindex DLLs, building
27858 @noindent
27859 This section explain how to build DLLs using the GNAT built-in DLL
27860 support. With the following procedure it is straight forward to build
27861 and use DLLs with GNAT.
27863 @enumerate
27865 @item building object files
27867 The first step is to build all objects files that are to be included
27868 into the DLL. This is done by using the standard @code{gnatmake} tool.
27870 @item building the DLL
27872 To build the DLL you must use @code{gcc}'s @code{-shared}
27873 option. It is quite simple to use this method:
27875 @smallexample
27876 $ gcc -shared -o api.dll obj1.o obj2.o ...
27877 @end smallexample
27879 It is important to note that in this case all symbols found in the
27880 object files are automatically exported. It is possible to restrict
27881 the set of symbols to export by passing to @code{gcc} a definition
27882 file, @pxref{The Definition File}. For example:
27884 @smallexample
27885 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
27886 @end smallexample
27888 If you use a definition file you must export the elaboration procedures
27889 for every package that required one. Elaboration procedures are named
27890 using the package name followed by "_E".
27892 @item preparing DLL to be used
27894 For the DLL to be used by client programs the bodies must be hidden
27895 from it and the .ali set with read-only attribute. This is very important
27896 otherwise GNAT will recompile all packages and will not actually use
27897 the code in the DLL. For example:
27899 @smallexample
27900 $ mkdir apilib
27901 $ copy *.ads *.ali api.dll apilib
27902 $ attrib +R apilib\*.ali
27903 @end smallexample
27905 @end enumerate
27907 At this point it is possible to use the DLL by directly linking
27908 against it. Note that you must use the GNAT shared runtime when using
27909 GNAT shared libraries. This is achieved by using @code{-shared} binder's
27910 option.
27912 @smallexample
27913 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27914 @end smallexample
27916 @node Building DLLs with GNAT Project files
27917 @section Building DLLs with GNAT Project files
27918 @cindex DLLs, building
27920 @noindent
27921 There is nothing specific to Windows in this area. @pxref{Library Projects}.
27923 @node Building DLLs with gnatdll
27924 @section Building DLLs with gnatdll
27925 @cindex DLLs, building
27927 @menu
27928 * Limitations When Using Ada DLLs from Ada::
27929 * Exporting Ada Entities::
27930 * Ada DLLs and Elaboration::
27931 * Ada DLLs and Finalization::
27932 * Creating a Spec for Ada DLLs::
27933 * Creating the Definition File::
27934 * Using gnatdll::
27935 @end menu
27937 @noindent
27938 Note that it is prefered to use the built-in GNAT DLL support
27939 (@pxref{Building DLLs with GNAT}) or GNAT Project files
27940 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
27942 This section explains how to build DLLs containing Ada code using
27943 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27944 remainder of this section.
27946 The steps required to build an Ada DLL that is to be used by Ada as well as
27947 non-Ada applications are as follows:
27949 @enumerate
27950 @item
27951 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27952 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27953 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27954 skip this step if you plan to use the Ada DLL only from Ada applications.
27956 @item
27957 Your Ada code must export an initialization routine which calls the routine
27958 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
27959 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27960 routine exported by the Ada DLL must be invoked by the clients of the DLL
27961 to initialize the DLL.
27963 @item
27964 When useful, the DLL should also export a finalization routine which calls
27965 routine @code{adafinal} generated by @code{gnatbind} to perform the
27966 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27967 The finalization routine exported by the Ada DLL must be invoked by the
27968 clients of the DLL when the DLL services are no further needed.
27970 @item
27971 You must provide a spec for the services exported by the Ada DLL in each
27972 of the programming languages to which you plan to make the DLL available.
27974 @item
27975 You must provide a definition file listing the exported entities
27976 (@pxref{The Definition File}).
27978 @item
27979 Finally you must use @code{gnatdll} to produce the DLL and the import
27980 library (@pxref{Using gnatdll}).
27981 @end enumerate
27983 @noindent
27984 Note that a relocatable DLL stripped using the @code{strip} binutils
27985 tool will not be relocatable anymore. To build a DLL without debug
27986 information pass @code{-largs -s} to @code{gnatdll}.
27988 @node Limitations When Using Ada DLLs from Ada
27989 @subsection Limitations When Using Ada DLLs from Ada
27991 @noindent
27992 When using Ada DLLs from Ada applications there is a limitation users
27993 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27994 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27995 each Ada DLL includes the services of the GNAT run time that are necessary
27996 to the Ada code inside the DLL. As a result, when an Ada program uses an
27997 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27998 one in the main program.
28000 It is therefore not possible to exchange GNAT run-time objects between the
28001 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
28002 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
28003 types, etc.
28005 It is completely safe to exchange plain elementary, array or record types,
28006 Windows object handles, etc.
28008 @node Exporting Ada Entities
28009 @subsection Exporting Ada Entities
28010 @cindex Export table
28012 @noindent
28013 Building a DLL is a way to encapsulate a set of services usable from any
28014 application. As a result, the Ada entities exported by a DLL should be
28015 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
28016 any Ada name mangling. Please note that the @code{Stdcall} convention
28017 should only be used for subprograms, not for variables. As an example here
28018 is an Ada package @code{API}, spec and body, exporting two procedures, a
28019 function, and a variable:
28021 @smallexample @c ada
28022 @group
28023 @cartouche
28024 with Interfaces.C; use Interfaces;
28025 package API is
28026    Count : C.int := 0;
28027    function Factorial (Val : C.int) return C.int;
28029    procedure Initialize_API;
28030    procedure Finalize_API;
28031    --  Initialization & Finalization routines. More in the next section.
28032 private
28033    pragma Export (C, Initialize_API);
28034    pragma Export (C, Finalize_API);
28035    pragma Export (C, Count);
28036    pragma Export (C, Factorial);
28037 end API;
28038 @end cartouche
28039 @end group
28040 @end smallexample
28042 @smallexample @c ada
28043 @group
28044 @cartouche
28045 package body API is
28046    function Factorial (Val : C.int) return C.int is
28047       Fact : C.int := 1;
28048    begin
28049       Count := Count + 1;
28050       for K in 1 .. Val loop
28051          Fact := Fact * K;
28052       end loop;
28053       return Fact;
28054    end Factorial;
28056    procedure Initialize_API is
28057       procedure Adainit;
28058       pragma Import (C, Adainit);
28059    begin
28060       Adainit;
28061    end Initialize_API;
28063    procedure Finalize_API is
28064       procedure Adafinal;
28065       pragma Import (C, Adafinal);
28066    begin
28067       Adafinal;
28068    end Finalize_API;
28069 end API;
28070 @end cartouche
28071 @end group
28072 @end smallexample
28074 @noindent
28075 If the Ada DLL you are building will only be used by Ada applications
28076 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28077 convention. As an example, the previous package could be written as
28078 follows:
28080 @smallexample @c ada
28081 @group
28082 @cartouche
28083 package API is
28084    Count : Integer := 0;
28085    function Factorial (Val : Integer) return Integer;
28087    procedure Initialize_API;
28088    procedure Finalize_API;
28089    --  Initialization and Finalization routines.
28090 end API;
28091 @end cartouche
28092 @end group
28093 @end smallexample
28095 @smallexample @c ada
28096 @group
28097 @cartouche
28098 package body API is
28099    function Factorial (Val : Integer) return Integer is
28100       Fact : Integer := 1;
28101    begin
28102       Count := Count + 1;
28103       for K in 1 .. Val loop
28104          Fact := Fact * K;
28105       end loop;
28106       return Fact;
28107    end Factorial;
28109    ...
28110    --  The remainder of this package body is unchanged.
28111 end API;
28112 @end cartouche
28113 @end group
28114 @end smallexample
28116 @noindent
28117 Note that if you do not export the Ada entities with a @code{C} or
28118 @code{Stdcall} convention you will have to provide the mangled Ada names
28119 in the definition file of the Ada DLL
28120 (@pxref{Creating the Definition File}).
28122 @node Ada DLLs and Elaboration
28123 @subsection Ada DLLs and Elaboration
28124 @cindex DLLs and elaboration
28126 @noindent
28127 The DLL that you are building contains your Ada code as well as all the
28128 routines in the Ada library that are needed by it. The first thing a
28129 user of your DLL must do is elaborate the Ada code
28130 (@pxref{Elaboration Order Handling in GNAT}).
28132 To achieve this you must export an initialization routine
28133 (@code{Initialize_API} in the previous example), which must be invoked
28134 before using any of the DLL services. This elaboration routine must call
28135 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28136 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28137 @code{Initialize_Api} for an example. Note that the GNAT binder is
28138 automatically invoked during the DLL build process by the @code{gnatdll}
28139 tool (@pxref{Using gnatdll}).
28141 When a DLL is loaded, Windows systematically invokes a routine called
28142 @code{DllMain}. It would therefore be possible to call @code{adainit}
28143 directly from @code{DllMain} without having to provide an explicit
28144 initialization routine. Unfortunately, it is not possible to call
28145 @code{adainit} from the @code{DllMain} if your program has library level
28146 tasks because access to the @code{DllMain} entry point is serialized by
28147 the system (that is, only a single thread can execute ``through'' it at a
28148 time), which means that the GNAT run time will deadlock waiting for the
28149 newly created task to complete its initialization.
28151 @node Ada DLLs and Finalization
28152 @subsection Ada DLLs and Finalization
28153 @cindex DLLs and finalization
28155 @noindent
28156 When the services of an Ada DLL are no longer needed, the client code should
28157 invoke the DLL finalization routine, if available. The DLL finalization
28158 routine is in charge of releasing all resources acquired by the DLL. In the
28159 case of the Ada code contained in the DLL, this is achieved by calling
28160 routine @code{adafinal} generated by the GNAT binder
28161 (@pxref{Binding with Non-Ada Main Programs}).
28162 See the body of @code{Finalize_Api} for an
28163 example. As already pointed out the GNAT binder is automatically invoked
28164 during the DLL build process by the @code{gnatdll} tool
28165 (@pxref{Using gnatdll}).
28167 @node Creating a Spec for Ada DLLs
28168 @subsection Creating a Spec for Ada DLLs
28170 @noindent
28171 To use the services exported by the Ada DLL from another programming
28172 language (e.g. C), you have to translate the specs of the exported Ada
28173 entities in that language. For instance in the case of @code{API.dll},
28174 the corresponding C header file could look like:
28176 @smallexample
28177 @group
28178 @cartouche
28179 extern int *_imp__count;
28180 #define count (*_imp__count)
28181 int factorial (int);
28182 @end cartouche
28183 @end group
28184 @end smallexample
28186 @noindent
28187 It is important to understand that when building an Ada DLL to be used by
28188 other Ada applications, you need two different specs for the packages
28189 contained in the DLL: one for building the DLL and the other for using
28190 the DLL. This is because the @code{DLL} calling convention is needed to
28191 use a variable defined in a DLL, but when building the DLL, the variable
28192 must have either the @code{Ada} or @code{C} calling convention. As an
28193 example consider a DLL comprising the following package @code{API}:
28195 @smallexample @c ada
28196 @group
28197 @cartouche
28198 package API is
28199    Count : Integer := 0;
28200    ...
28201    --  Remainder of the package omitted.
28202 end API;
28203 @end cartouche
28204 @end group
28205 @end smallexample
28207 @noindent
28208 After producing a DLL containing package @code{API}, the spec that
28209 must be used to import @code{API.Count} from Ada code outside of the
28210 DLL is:
28212 @smallexample @c ada
28213 @group
28214 @cartouche
28215 package API is
28216    Count : Integer;
28217    pragma Import (DLL, Count);
28218 end API;
28219 @end cartouche
28220 @end group
28221 @end smallexample
28223 @node Creating the Definition File
28224 @subsection Creating the Definition File
28226 @noindent
28227 The definition file is the last file needed to build the DLL. It lists
28228 the exported symbols. As an example, the definition file for a DLL
28229 containing only package @code{API} (where all the entities are exported
28230 with a @code{C} calling convention) is:
28232 @smallexample
28233 @group
28234 @cartouche
28235 EXPORTS
28236     count
28237     factorial
28238     finalize_api
28239     initialize_api
28240 @end cartouche
28241 @end group
28242 @end smallexample
28244 @noindent
28245 If the @code{C} calling convention is missing from package @code{API},
28246 then the definition file contains the mangled Ada names of the above
28247 entities, which in this case are:
28249 @smallexample
28250 @group
28251 @cartouche
28252 EXPORTS
28253     api__count
28254     api__factorial
28255     api__finalize_api
28256     api__initialize_api
28257 @end cartouche
28258 @end group
28259 @end smallexample
28261 @node Using gnatdll
28262 @subsection Using @code{gnatdll}
28263 @findex gnatdll
28265 @menu
28266 * gnatdll Example::
28267 * gnatdll behind the Scenes::
28268 * Using dlltool::
28269 @end menu
28271 @noindent
28272 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28273 and non-Ada sources that make up your DLL have been compiled.
28274 @code{gnatdll} is actually in charge of two distinct tasks: build the
28275 static import library for the DLL and the actual DLL. The form of the
28276 @code{gnatdll} command is
28278 @smallexample
28279 @cartouche
28280 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
28281 @end cartouche
28282 @end smallexample
28284 @noindent
28285 where @i{list-of-files} is a list of ALI and object files. The object
28286 file list must be the exact list of objects corresponding to the non-Ada
28287 sources whose services are to be included in the DLL. The ALI file list
28288 must be the exact list of ALI files for the corresponding Ada sources
28289 whose services are to be included in the DLL. If @i{list-of-files} is
28290 missing, only the static import library is generated.
28292 @noindent
28293 You may specify any of the following switches to @code{gnatdll}:
28295 @table @code
28296 @item -a[@var{address}]
28297 @cindex @option{-a} (@code{gnatdll})
28298 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28299 specified the default address @var{0x11000000} will be used. By default,
28300 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28301 advise the reader to build relocatable DLL.
28303 @item -b @var{address}
28304 @cindex @option{-b} (@code{gnatdll})
28305 Set the relocatable DLL base address. By default the address is
28306 @var{0x11000000}.
28308 @item -bargs @var{opts}
28309 @cindex @option{-bargs} (@code{gnatdll})
28310 Binder options. Pass @var{opts} to the binder.
28312 @item -d @var{dllfile}
28313 @cindex @option{-d} (@code{gnatdll})
28314 @var{dllfile} is the name of the DLL. This switch must be present for
28315 @code{gnatdll} to do anything. The name of the generated import library is
28316 obtained algorithmically from @var{dllfile} as shown in the following
28317 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28318 @code{libxyz.a}. The name of the definition file to use (if not specified
28319 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28320 as shown in the following example:
28321 if @var{dllfile} is @code{xyz.dll}, the definition
28322 file used is @code{xyz.def}.
28324 @item -e @var{deffile}
28325 @cindex @option{-e} (@code{gnatdll})
28326 @var{deffile} is the name of the definition file.
28328 @item -g
28329 @cindex @option{-g} (@code{gnatdll})
28330 Generate debugging information. This information is stored in the object
28331 file and copied from there to the final DLL file by the linker,
28332 where it can be read by the debugger. You must use the
28333 @option{-g} switch if you plan on using the debugger or the symbolic
28334 stack traceback.
28336 @item -h
28337 @cindex @option{-h} (@code{gnatdll})
28338 Help mode. Displays @code{gnatdll} switch usage information.
28340 @item -Idir
28341 @cindex @option{-I} (@code{gnatdll})
28342 Direct @code{gnatdll} to search the @var{dir} directory for source and
28343 object files needed to build the DLL.
28344 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28346 @item -k
28347 @cindex @option{-k} (@code{gnatdll})
28348 Removes the @code{@@}@i{nn} suffix from the import library's exported
28349 names, but keeps them for the link names. You must specify this
28350 option if you want to use a @code{Stdcall} function in a DLL for which
28351 the @code{@@}@i{nn} suffix has been removed. This is the case for most
28352 of the Windows NT DLL for example. This option has no effect when
28353 @option{-n} option is specified.
28355 @item -l @var{file}
28356 @cindex @option{-l} (@code{gnatdll})
28357 The list of ALI and object files used to build the DLL are listed in
28358 @var{file}, instead of being given in the command line. Each line in
28359 @var{file} contains the name of an ALI or object file.
28361 @item -n
28362 @cindex @option{-n} (@code{gnatdll})
28363 No Import. Do not create the import library.
28365 @item -q
28366 @cindex @option{-q} (@code{gnatdll})
28367 Quiet mode. Do not display unnecessary messages.
28369 @item -v
28370 @cindex @option{-v} (@code{gnatdll})
28371 Verbose mode. Display extra information.
28373 @item -largs @var{opts}
28374 @cindex @option{-largs} (@code{gnatdll})
28375 Linker options. Pass @var{opts} to the linker.
28376 @end table
28378 @node gnatdll Example
28379 @subsubsection @code{gnatdll} Example
28381 @noindent
28382 As an example the command to build a relocatable DLL from @file{api.adb}
28383 once @file{api.adb} has been compiled and @file{api.def} created is
28385 @smallexample
28386 $ gnatdll -d api.dll api.ali
28387 @end smallexample
28389 @noindent
28390 The above command creates two files: @file{libapi.a} (the import
28391 library) and @file{api.dll} (the actual DLL). If you want to create
28392 only the DLL, just type:
28394 @smallexample
28395 $ gnatdll -d api.dll -n api.ali
28396 @end smallexample
28398 @noindent
28399 Alternatively if you want to create just the import library, type:
28401 @smallexample
28402 $ gnatdll -d api.dll
28403 @end smallexample
28405 @node gnatdll behind the Scenes
28406 @subsubsection @code{gnatdll} behind the Scenes
28408 @noindent
28409 This section details the steps involved in creating a DLL. @code{gnatdll}
28410 does these steps for you. Unless you are interested in understanding what
28411 goes on behind the scenes, you should skip this section.
28413 We use the previous example of a DLL containing the Ada package @code{API},
28414 to illustrate the steps necessary to build a DLL. The starting point is a
28415 set of objects that will make up the DLL and the corresponding ALI
28416 files. In the case of this example this means that @file{api.o} and
28417 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28418 the following:
28420 @enumerate
28421 @item
28422 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28423 the information necessary to generate relocation information for the
28424 DLL.
28426 @smallexample
28427 @group
28428 $ gnatbind -n api
28429 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28430 @end group
28431 @end smallexample
28433 @noindent
28434 In addition to the base file, the @code{gnatlink} command generates an
28435 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28436 asks @code{gnatlink} to generate the routines @code{DllMain} and
28437 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28438 is loaded into memory.
28440 @item
28441 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28442 export table (@file{api.exp}). The export table contains the relocation
28443 information in a form which can be used during the final link to ensure
28444 that the Windows loader is able to place the DLL anywhere in memory.
28446 @smallexample
28447 @group
28448 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28449           --output-exp api.exp
28450 @end group
28451 @end smallexample
28453 @item
28454 @code{gnatdll} builds the base file using the new export table. Note that
28455 @code{gnatbind} must be called once again since the binder generated file
28456 has been deleted during the previous call to @code{gnatlink}.
28458 @smallexample
28459 @group
28460 $ gnatbind -n api
28461 $ gnatlink api -o api.jnk api.exp -mdll
28462       -Wl,--base-file,api.base
28463 @end group
28464 @end smallexample
28466 @item
28467 @code{gnatdll} builds the new export table using the new base file and
28468 generates the DLL import library @file{libAPI.a}.
28470 @smallexample
28471 @group
28472 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28473           --output-exp api.exp --output-lib libAPI.a
28474 @end group
28475 @end smallexample
28477 @item
28478 Finally @code{gnatdll} builds the relocatable DLL using the final export
28479 table.
28481 @smallexample
28482 @group
28483 $ gnatbind -n api
28484 $ gnatlink api api.exp -o api.dll -mdll
28485 @end group
28486 @end smallexample
28487 @end enumerate
28489 @node Using dlltool
28490 @subsubsection Using @code{dlltool}
28492 @noindent
28493 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28494 DLLs and static import libraries. This section summarizes the most
28495 common @code{dlltool} switches. The form of the @code{dlltool} command
28498 @smallexample
28499 $ dlltool [@var{switches}]
28500 @end smallexample
28502 @noindent
28503 @code{dlltool} switches include:
28505 @table @option
28506 @item --base-file @var{basefile}
28507 @cindex @option{--base-file} (@command{dlltool})
28508 Read the base file @var{basefile} generated by the linker. This switch
28509 is used to create a relocatable DLL.
28511 @item --def @var{deffile}
28512 @cindex @option{--def} (@command{dlltool})
28513 Read the definition file.
28515 @item --dllname @var{name}
28516 @cindex @option{--dllname} (@command{dlltool})
28517 Gives the name of the DLL. This switch is used to embed the name of the
28518 DLL in the static import library generated by @code{dlltool} with switch
28519 @option{--output-lib}.
28521 @item -k
28522 @cindex @option{-k} (@command{dlltool})
28523 Kill @code{@@}@i{nn} from exported names
28524 (@pxref{Windows Calling Conventions}
28525 for a discussion about @code{Stdcall}-style symbols.
28527 @item --help
28528 @cindex @option{--help} (@command{dlltool})
28529 Prints the @code{dlltool} switches with a concise description.
28531 @item --output-exp @var{exportfile}
28532 @cindex @option{--output-exp} (@command{dlltool})
28533 Generate an export file @var{exportfile}. The export file contains the
28534 export table (list of symbols in the DLL) and is used to create the DLL.
28536 @item --output-lib @i{libfile}
28537 @cindex @option{--output-lib} (@command{dlltool})
28538 Generate a static import library @var{libfile}.
28540 @item -v
28541 @cindex @option{-v} (@command{dlltool})
28542 Verbose mode.
28544 @item --as @i{assembler-name}
28545 @cindex @option{--as} (@command{dlltool})
28546 Use @i{assembler-name} as the assembler. The default is @code{as}.
28547 @end table
28549 @node GNAT and Windows Resources
28550 @section GNAT and Windows Resources
28551 @cindex Resources, windows
28553 @menu
28554 * Building Resources::
28555 * Compiling Resources::
28556 * Using Resources::
28557 @end menu
28559 @noindent
28560 Resources are an easy way to add Windows specific objects to your
28561 application. The objects that can be added as resources include:
28563 @itemize @bullet
28564 @item
28565 menus
28567 @item
28568 accelerators
28570 @item
28571 dialog boxes
28573 @item
28574 string tables
28576 @item
28577 bitmaps
28579 @item
28580 cursors
28582 @item
28583 icons
28585 @item
28586 fonts
28587 @end itemize
28589 @noindent
28590 This section explains how to build, compile and use resources.
28592 @node Building Resources
28593 @subsection Building Resources
28594 @cindex Resources, building
28596 @noindent
28597 A resource file is an ASCII file. By convention resource files have an
28598 @file{.rc} extension.
28599 The easiest way to build a resource file is to use Microsoft tools
28600 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28601 @code{dlgedit.exe} to build dialogs.
28602 It is always possible to build an @file{.rc} file yourself by writing a
28603 resource script.
28605 It is not our objective to explain how to write a resource file. A
28606 complete description of the resource script language can be found in the
28607 Microsoft documentation.
28609 @node Compiling Resources
28610 @subsection Compiling Resources
28611 @findex rc
28612 @findex windres
28613 @cindex Resources, compiling
28615 @noindent
28616 This section describes how to build a GNAT-compatible (COFF) object file
28617 containing the resources. This is done using the Resource Compiler
28618 @code{windres} as follows:
28620 @smallexample
28621 $ windres -i myres.rc -o myres.o
28622 @end smallexample
28624 @noindent
28625 By default @code{windres} will run @code{gcc} to preprocess the @file{.rc}
28626 file. You can specify an alternate preprocessor (usually named
28627 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28628 parameter. A list of all possible options may be obtained by entering
28629 the command @code{windres} @option{--help}.
28631 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28632 to produce a @file{.res} file (binary resource file). See the
28633 corresponding Microsoft documentation for further details. In this case
28634 you need to use @code{windres} to translate the @file{.res} file to a
28635 GNAT-compatible object file as follows:
28637 @smallexample
28638 $ windres -i myres.res -o myres.o
28639 @end smallexample
28641 @node Using Resources
28642 @subsection Using Resources
28643 @cindex Resources, using
28645 @noindent
28646 To include the resource file in your program just add the
28647 GNAT-compatible object file for the resource(s) to the linker
28648 arguments. With @code{gnatmake} this is done by using the @option{-largs}
28649 option:
28651 @smallexample
28652 $ gnatmake myprog -largs myres.o
28653 @end smallexample
28655 @node Debugging a DLL
28656 @section Debugging a DLL
28657 @cindex DLL debugging
28659 @menu
28660 * Program and DLL Both Built with GCC/GNAT::
28661 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28662 @end menu
28664 @noindent
28665 Debugging a DLL is similar to debugging a standard program. But
28666 we have to deal with two different executable parts: the DLL and the
28667 program that uses it. We have the following four possibilities:
28669 @enumerate 1
28670 @item
28671 The program and the DLL are built with @code{GCC/GNAT}.
28672 @item
28673 The program is built with foreign tools and the DLL is built with
28674 @code{GCC/GNAT}.
28675 @item
28676 The program is built with @code{GCC/GNAT} and the DLL is built with
28677 foreign tools.
28678 @item
28679 @end enumerate
28681 @noindent
28682 In this section we address only cases one and two above.
28683 There is no point in trying to debug
28684 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28685 information in it. To do so you must use a debugger compatible with the
28686 tools suite used to build the DLL.
28688 @node Program and DLL Both Built with GCC/GNAT
28689 @subsection Program and DLL Both Built with GCC/GNAT
28691 @noindent
28692 This is the simplest case. Both the DLL and the program have @code{GDB}
28693 compatible debugging information. It is then possible to break anywhere in
28694 the process. Let's suppose here that the main procedure is named
28695 @code{ada_main} and that in the DLL there is an entry point named
28696 @code{ada_dll}.
28698 @noindent
28699 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28700 program must have been built with the debugging information (see GNAT -g
28701 switch). Here are the step-by-step instructions for debugging it:
28703 @enumerate 1
28704 @item Launch @code{GDB} on the main program.
28706 @smallexample
28707 $ gdb -nw ada_main
28708 @end smallexample
28710 @item Break on the main procedure and run the program.
28712 @smallexample
28713 (gdb) break ada_main
28714 (gdb) run
28715 @end smallexample
28717 @noindent
28718 This step is required to be able to set a breakpoint inside the DLL. As long
28719 as the program is not run, the DLL is not loaded. This has the
28720 consequence that the DLL debugging information is also not loaded, so it is not
28721 possible to set a breakpoint in the DLL.
28723 @item Set a breakpoint inside the DLL
28725 @smallexample
28726 (gdb) break ada_dll
28727 (gdb) run
28728 @end smallexample
28730 @end enumerate
28732 @noindent
28733 At this stage a breakpoint is set inside the DLL. From there on
28734 you can use the standard approach to debug the whole program
28735 (@pxref{Running and Debugging Ada Programs}).
28737 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28738 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28740 @menu
28741 * Debugging the DLL Directly::
28742 * Attaching to a Running Process::
28743 @end menu
28745 @noindent
28746 In this case things are slightly more complex because it is not possible to
28747 start the main program and then break at the beginning to load the DLL and the
28748 associated DLL debugging information. It is not possible to break at the
28749 beginning of the program because there is no @code{GDB} debugging information,
28750 and therefore there is no direct way of getting initial control. This
28751 section addresses this issue by describing some methods that can be used
28752 to break somewhere in the DLL to debug it.
28754 @noindent
28755 First suppose that the main procedure is named @code{main} (this is for
28756 example some C code built with Microsoft Visual C) and that there is a
28757 DLL named @code{test.dll} containing an Ada entry point named
28758 @code{ada_dll}.
28760 @noindent
28761 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28762 been built with debugging information (see GNAT -g option).
28764 @node Debugging the DLL Directly
28765 @subsubsection Debugging the DLL Directly
28767 @enumerate 1
28768 @item
28769 Launch the debugger on the DLL.
28771 @smallexample
28772 $ gdb -nw test.dll
28773 @end smallexample
28775 @item Set a breakpoint on a DLL subroutine.
28777 @smallexample
28778 (gdb) break ada_dll
28779 @end smallexample
28781 @item
28782 Specify the executable file to @code{GDB}.
28784 @smallexample
28785 (gdb) exec-file main.exe
28786 @end smallexample
28788 @item
28789 Run the program.
28791 @smallexample
28792 (gdb) run
28793 @end smallexample
28795 @noindent
28796 This will run the program until it reaches the breakpoint that has been
28797 set. From that point you can use the standard way to debug a program
28798 as described in (@pxref{Running and Debugging Ada Programs}).
28800 @end enumerate
28802 @noindent
28803 It is also possible to debug the DLL by attaching to a running process.
28805 @node Attaching to a Running Process
28806 @subsubsection Attaching to a Running Process
28807 @cindex DLL debugging, attach to process
28809 @noindent
28810 With @code{GDB} it is always possible to debug a running process by
28811 attaching to it. It is possible to debug a DLL this way. The limitation
28812 of this approach is that the DLL must run long enough to perform the
28813 attach operation. It may be useful for instance to insert a time wasting
28814 loop in the code of the DLL to meet this criterion.
28816 @enumerate 1
28818 @item Launch the main program @file{main.exe}.
28820 @smallexample
28821 $ main
28822 @end smallexample
28824 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28825 that the process PID for @file{main.exe} is 208.
28827 @item Launch gdb.
28829 @smallexample
28830 $ gdb -nw
28831 @end smallexample
28833 @item Attach to the running process to be debugged.
28835 @smallexample
28836 (gdb) attach 208
28837 @end smallexample
28839 @item Load the process debugging information.
28841 @smallexample
28842 (gdb) symbol-file main.exe
28843 @end smallexample
28845 @item Break somewhere in the DLL.
28847 @smallexample
28848 (gdb) break ada_dll
28849 @end smallexample
28851 @item Continue process execution.
28853 @smallexample
28854 (gdb) continue
28855 @end smallexample
28857 @end enumerate
28859 @noindent
28860 This last step will resume the process execution, and stop at
28861 the breakpoint we have set. From there you can use the standard
28862 approach to debug a program as described in
28863 (@pxref{Running and Debugging Ada Programs}).
28865 @node GNAT and COM/DCOM Objects
28866 @section GNAT and COM/DCOM Objects
28867 @findex COM
28868 @findex DCOM
28870 @noindent
28871 This section is temporarily left blank.
28873 @end ifset
28875 @c **********************************
28876 @c * GNU Free Documentation License *
28877 @c **********************************
28878 @include fdl.texi
28879 @c GNU Free Documentation License
28881 @node Index,,GNU Free Documentation License, Top
28882 @unnumbered Index
28884 @printindex cp
28886 @contents
28887 @c Put table of contents at end, otherwise it precedes the "title page" in
28888 @c the .txt version
28889 @c Edit the pdf file to move the contents to the beginning, after the title
28890 @c page
28892 @bye