Merge from the pain train
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blobf112f4dd79cbdd89edf533486b00c42b11a1ece7
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 the Scheduling Policy::
571 * Solaris-Specific Considerations::
572 * IRIX-Specific Considerations::
573 * Linux-Specific Considerations::
574 * AIX-Specific Considerations::
576 Example of Binder Output File
578 Elaboration Order Handling in GNAT
580 * Elaboration Code in Ada 95::
581 * Checking the Elaboration Order in Ada 95::
582 * Controlling the Elaboration Order in Ada 95::
583 * Controlling Elaboration in GNAT - Internal Calls::
584 * Controlling Elaboration in GNAT - External Calls::
585 * Default Behavior in GNAT - Ensuring Safety::
586 * Treatment of Pragma Elaborate::
587 * Elaboration Issues for Library Tasks::
588 * Mixing Elaboration Models::
589 * What to Do If the Default Elaboration Behavior Fails::
590 * Elaboration for Access-to-Subprogram Values::
591 * Summary of Procedures for Elaboration Control::
592 * Other Elaboration Order Considerations::
594 Inline Assembler
596 * Basic Assembler Syntax::
597 * A Simple Example of Inline Assembler::
598 * Output Variables in Inline Assembler::
599 * Input Variables in Inline Assembler::
600 * Inlining Inline Assembler Code::
601 * Other Asm Functionality::
602 * A Complete Example::
604 Compatibility and Porting Guide
606 * Compatibility with Ada 83::
607 * Implementation-dependent characteristics::
608 * Compatibility with DEC Ada 83::
609 * Compatibility with Other Ada 95 Systems::
610 * Representation Clauses::
611 @ifset vms
612 * Transitioning from Alpha to Integrity OpenVMS::
613 @end ifset
615 @ifset unw
616 Microsoft Windows Topics
618 * Using GNAT on Windows::
619 * CONSOLE and WINDOWS subsystems::
620 * Temporary Files::
621 * Mixed-Language Programming on Windows::
622 * Windows Calling Conventions::
623 * Introduction to Dynamic Link Libraries (DLLs)::
624 * Using DLLs with GNAT::
625 * Building DLLs with GNAT::
626 * GNAT and Windows Resources::
627 * Debugging a DLL::
628 * GNAT and COM/DCOM Objects::
629 @end ifset
631 * Index::
632 @end menu
633 @end ifnottex
635 @node About This Guide
636 @unnumbered About This Guide
638 @noindent
639 @ifset vms
640 This guide describes the use of @value{EDITION},
641 a full language compiler for the Ada
642 95 programming language, implemented on HP's Alpha and
643 Integrity (ia64) OpenVMS platforms.
644 @end ifset
645 @ifclear vms
646 This guide describes the use of @value{EDITION},
647 a compiler and software development
648 toolset for the full Ada 95 programming language.
649 @end ifclear
650 It describes the features of the compiler and tools, and details
651 how to use them to build Ada 95 applications.
653 @ifset PROEDITION
654 For ease of exposition, ``GNAT Pro'' will be referred to simply as
655 ``GNAT'' in the remainder of this document.
656 @end ifset
658 @menu
659 * What This Guide Contains::
660 * What You Should Know before Reading This Guide::
661 * Related Information::
662 * Conventions::
663 @end menu
665 @node What This Guide Contains
666 @unnumberedsec What This Guide Contains
668 @noindent
669 This guide contains the following chapters:
670 @itemize @bullet
672 @item
673 @ref{Getting Started with GNAT}, describes how to get started compiling
674 and running Ada programs with the GNAT Ada programming environment.
675 @item
676 @ref{The GNAT Compilation Model}, describes the compilation model used
677 by GNAT.
679 @item
680 @ref{Compiling Using gcc}, describes how to compile
681 Ada programs with @command{gcc}, the Ada compiler.
683 @item
684 @ref{Binding Using gnatbind}, describes how to
685 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
686 utility.
688 @item
689 @ref{Linking Using gnatlink},
690 describes @command{gnatlink}, a
691 program that provides for linking using the GNAT run-time library to
692 construct a program. @command{gnatlink} can also incorporate foreign language
693 object units into the executable.
695 @item
696 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
697 utility that automatically determines the set of sources
698 needed by an Ada compilation unit, and executes the necessary compilations
699 binding and link.
701 @item
702 @ref{Improving Performance}, shows various techniques for making your
703 Ada program run faster or take less space.
704 It discusses the effect of the compiler's optimization switch and
705 also describes the @command{gnatelim} tool.
707 @item
708 @ref{Renaming Files Using gnatchop}, describes
709 @code{gnatchop}, a utility that allows you to preprocess a file that
710 contains Ada source code, and split it into one or more new files, one
711 for each compilation unit.
713 @item
714 @ref{Configuration Pragmas}, describes the configuration pragmas
715 handled by GNAT.
717 @item
718 @ref{Handling Arbitrary File Naming Conventions Using gnatname},
719 shows how to override the default GNAT file naming conventions,
720 either for an individual unit or globally.
722 @item
723 @ref{GNAT Project Manager}, describes how to use project files
724 to organize large projects.
726 @item
727 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
728 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
729 way to navigate through sources.
731 @item
732 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
733 version of an Ada source file with control over casing, indentation,
734 comment placement, and other elements of program presentation style.
736 @item
737 @ref{The GNAT Metric Tool gnatmetric}, shows how to compute various
738 metrics for an Ada source file, such as the number of types and subprograms,
739 and assorted complexity measures.
741 @item
742 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
743 file name krunching utility, used to handle shortened
744 file names on operating systems with a limit on the length of names.
746 @item
747 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
748 preprocessor utility that allows a single source file to be used to
749 generate multiple or parameterized source files, by means of macro
750 substitution.
752 @ifset vms
753 @item
754 @ref{The GNAT Run-Time Library Builder gnatlbr}, describes @command{gnatlbr},
755 a tool for rebuilding the GNAT run time with user-supplied
756 configuration pragmas.
757 @end ifset
759 @item
760 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
761 utility that displays information about compiled units, including dependences
762 on the corresponding sources files, and consistency of compilations.
764 @item
765 @ref{Cleaning Up Using gnatclean}, describes @code{gnatclean}, a utility
766 to delete files that are produced by the compiler, binder and linker.
768 @ifclear vms
769 @item
770 @ref{GNAT and Libraries}, describes the process of creating and using
771 Libraries with GNAT. It also describes how to recompile the GNAT run-time
772 library.
774 @item
775 @ref{Using the GNU make Utility}, describes some techniques for using
776 the GNAT toolset in Makefiles.
777 @end ifclear
779 @item
780 @ref{Memory Management Issues}, describes some useful predefined storage pools
781 and in particular the GNAT Debug Pool facility, which helps detect incorrect
782 memory references.
783 @ifclear vms
784 It also describes @command{gnatmem}, a utility that monitors dynamic
785 allocation and deallocation and helps detect ``memory leaks''.
786 @end ifclear
788 @item
789 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
790 a utility that generates empty but compilable bodies for library units.
792 @item
793 @ref{Other Utility Programs}, discusses several other GNAT utilities,
794 including @code{gnathtml}.
796 @item
797 @ref{Running and Debugging Ada Programs}, describes how to run and debug
798 Ada programs.
800 @ifset vms
801 @item
802 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
803 DEC Ada 83 @footnote{``DEC Ada'' refers to the legacy product originally
804 developed by Digital Equipment Corporation and currently supported by HP.}
805 for OpenVMS Alpha.
806 @end ifset
808 @item
809 @ref{Platform-Specific Information for the Run-Time Libraries},
810 describes the various run-time
811 libraries supported by GNAT on various platforms and explains how to
812 choose a particular library.
814 @item
815 @ref{Example of Binder Output File}, shows the source code for the binder
816 output file for a sample program.
818 @item
819 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
820 you deal with elaboration order issues.
822 @item
823 @ref{Inline Assembler}, shows how to use the inline assembly facility
824 in an Ada program.
826 @item
827 @ref{Compatibility and Porting Guide}, includes sections on compatibility
828 of GNAT with other Ada 83 and Ada 95 compilation systems, to assist
829 in porting code from other environments.
831 @ifset unw
832 @item
833 @ref{Microsoft Windows Topics}, presents information relevant to the
834 Microsoft Windows platform.
835 @end ifset
836 @end itemize
838 @c *************************************************
839 @node What You Should Know before Reading This Guide
840 @c *************************************************
841 @unnumberedsec What You Should Know before Reading This Guide
843 @cindex Ada 95 Language Reference Manual
844 @noindent
845 This user's guide assumes that you are familiar with Ada 95 language, as
846 described in the International Standard ANSI/ISO/IEC-8652:1995, January
847 1995.
849 @node Related Information
850 @unnumberedsec Related Information
852 @noindent
853 For further information about related tools, refer to the following
854 documents:
856 @itemize @bullet
857 @item
858 @cite{GNAT Reference Manual}, which contains all reference
859 material for the GNAT implementation of Ada 95.
861 @ifset unw
862 @item
863 @cite{Using the GNAT Programming System}, which describes the GPS
864 integrated development environment.
866 @item
867 @cite{GNAT Programming System Tutorial}, which introduces the
868 main GPS features through examples.
869 @end ifset
871 @item
872 @cite{Ada 95 Language Reference Manual}, which contains all reference
873 material for the Ada 95 programming language.
875 @item
876 @cite{Debugging with GDB}
877 @ifset vms
878 , located in the GNU:[DOCS] directory,
879 @end ifset
880 contains all details on the use of the GNU source-level debugger.
882 @item
883 @cite{GNU Emacs Manual}
884 @ifset vms
885 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
886 @end ifset
887 contains full information on the extensible editor and programming
888 environment Emacs.
890 @end itemize
892 @c **************
893 @node Conventions
894 @unnumberedsec Conventions
895 @cindex Conventions
896 @cindex Typographical conventions
898 @noindent
899 Following are examples of the typographical and graphic conventions used
900 in this guide:
902 @itemize @bullet
903 @item
904 @code{Functions}, @code{utility program names}, @code{standard names},
905 and @code{classes}.
907 @item
908 @samp{Option flags}
910 @item
911 @file{File Names}, @file{button names}, and @file{field names}.
913 @item
914 @var{Variables}.
916 @item
917 @emph{Emphasis}.
919 @item
920 [optional information or parameters]
922 @item
923 Examples are described by text
924 @smallexample
925 and then shown this way.
926 @end smallexample
927 @end itemize
929 @noindent
930 Commands that are entered by the user are preceded in this manual by the
931 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
932 uses this sequence as a prompt, then the commands will appear exactly as
933 you see them in the manual. If your system uses some other prompt, then
934 the command will appear with the @code{$} replaced by whatever prompt
935 character you are using.
937 @ifset unw
938 Full file names are shown with the ``@code{/}'' character
939 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
940 If you are using GNAT on a Windows platform, please note that
941 the ``@code{\}'' character should be used instead.
942 @end ifset
944 @c ****************************
945 @node Getting Started with GNAT
946 @chapter Getting Started with GNAT
948 @noindent
949 This chapter describes some simple ways of using GNAT to build
950 executable Ada programs.
951 @ifset unw
952 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
953 show how to use the command line environment.
954 @ref{Introduction to Glide and GVD}, provides a brief
955 introduction to the visually-oriented IDE for GNAT.
956 Supplementing Glide on some platforms is GPS, the
957 GNAT Programming System, which offers a richer graphical
958 ``look and feel'', enhanced configurability, support for
959 development in other programming language, comprehensive
960 browsing features, and many other capabilities.
961 For information on GPS please refer to
962 @cite{Using the GNAT Programming System}.
963 @end ifset
965 @menu
966 * Running GNAT::
967 * Running a Simple Ada Program::
968 * Running a Program with Multiple Units::
969 * Using the gnatmake Utility::
970 @ifset vms
971 * Editing with Emacs::
972 @end ifset
973 @ifclear vms
974 * Introduction to GPS::
975 * Introduction to Glide and GVD::
976 @end ifclear
977 @end menu
979 @node Running GNAT
980 @section Running GNAT
982 @noindent
983 Three steps are needed to create an executable file from an Ada source
984 file:
986 @enumerate
987 @item
988 The source file(s) must be compiled.
989 @item
990 The file(s) must be bound using the GNAT binder.
991 @item
992 All appropriate object files must be linked to produce an executable.
993 @end enumerate
995 @noindent
996 All three steps are most commonly handled by using the @command{gnatmake}
997 utility program that, given the name of the main program, automatically
998 performs the necessary compilation, binding and linking steps.
1000 @node Running a Simple Ada Program
1001 @section Running a Simple Ada Program
1003 @noindent
1004 Any text editor may be used to prepare an Ada program.
1005 @ifclear vms
1006 If @code{Glide} is
1007 used, the optional Ada mode may be helpful in laying out the program.
1008 @end ifclear
1010 program text is a normal text file. We will suppose in our initial
1011 example that you have used your editor to prepare the following
1012 standard format text file:
1014 @smallexample @c ada
1015 @cartouche
1016 with Ada.Text_IO; use Ada.Text_IO;
1017 procedure Hello is
1018 begin
1019    Put_Line ("Hello WORLD!");
1020 end Hello;
1021 @end cartouche
1022 @end smallexample
1024 @noindent
1025 This file should be named @file{hello.adb}.
1026 With the normal default file naming conventions, GNAT requires
1027 that each file
1028 contain a single compilation unit whose file name is the
1029 unit name,
1030 with periods replaced by hyphens; the
1031 extension is @file{ads} for a
1032 spec and @file{adb} for a body.
1033 You can override this default file naming convention by use of the
1034 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
1035 Alternatively, if you want to rename your files according to this default
1036 convention, which is probably more convenient if you will be using GNAT
1037 for all your compilations, then the @code{gnatchop} utility
1038 can be used to generate correctly-named source files
1039 (@pxref{Renaming Files Using gnatchop}).
1041 You can compile the program using the following command (@code{$} is used
1042 as the command prompt in the examples in this document):
1044 @smallexample
1045 $ gcc -c hello.adb
1046 @end smallexample
1048 @noindent
1049 @command{gcc} is the command used to run the compiler. This compiler is
1050 capable of compiling programs in several languages, including Ada 95 and
1051 C. It assumes that you have given it an Ada program if the file extension is
1052 either @file{.ads} or @file{.adb}, and it will then call
1053 the GNAT compiler to compile the specified file.
1055 @ifclear vms
1056 The @option{-c} switch is required. It tells @command{gcc} to only do a
1057 compilation. (For C programs, @command{gcc} can also do linking, but this
1058 capability is not used directly for Ada programs, so the @option{-c}
1059 switch must always be present.)
1060 @end ifclear
1062 This compile command generates a file
1063 @file{hello.o}, which is the object
1064 file corresponding to your Ada program. It also generates
1065 an ``Ada Library Information'' file @file{hello.ali},
1066 which contains additional information used to check
1067 that an Ada program is consistent.
1068 To build an executable file,
1069 use @code{gnatbind} to bind the program
1070 and @command{gnatlink} to link it. The
1071 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
1072 @file{ALI} file, but the default extension of @file{.ali} can
1073 be omitted. This means that in the most common case, the argument
1074 is simply the name of the main program:
1076 @smallexample
1077 $ gnatbind hello
1078 $ gnatlink hello
1079 @end smallexample
1081 @noindent
1082 A simpler method of carrying out these steps is to use
1083 @command{gnatmake},
1084 a master program that invokes all the required
1085 compilation, binding and linking tools in the correct order. In particular,
1086 @command{gnatmake} automatically recompiles any sources that have been
1087 modified since they were last compiled, or sources that depend
1088 on such modified sources, so that ``version skew'' is avoided.
1089 @cindex Version skew (avoided by @command{gnatmake})
1091 @smallexample
1092 $ gnatmake hello.adb
1093 @end smallexample
1095 @noindent
1096 The result is an executable program called @file{hello}, which can be
1097 run by entering:
1099 @c The following should be removed (BMB 2001-01-23)
1100 @c @smallexample
1101 @c $ ^./hello^$ RUN HELLO^
1102 @c @end smallexample
1104 @smallexample
1105 $ hello
1106 @end smallexample
1108 @noindent
1109 assuming that the current directory is on the search path
1110 for executable programs.
1112 @noindent
1113 and, if all has gone well, you will see
1115 @smallexample
1116 Hello WORLD!
1117 @end smallexample
1119 @noindent
1120 appear in response to this command.
1122 @c ****************************************
1123 @node Running a Program with Multiple Units
1124 @section Running a Program with Multiple Units
1126 @noindent
1127 Consider a slightly more complicated example that has three files: a
1128 main program, and the spec and body of a package:
1130 @smallexample @c ada
1131 @cartouche
1132 @group
1133 package Greetings is
1134    procedure Hello;
1135    procedure Goodbye;
1136 end Greetings;
1138 with Ada.Text_IO; use Ada.Text_IO;
1139 package body Greetings is
1140    procedure Hello is
1141    begin
1142       Put_Line ("Hello WORLD!");
1143    end Hello;
1145    procedure Goodbye is
1146    begin
1147       Put_Line ("Goodbye WORLD!");
1148    end Goodbye;
1149 end Greetings;
1150 @end group
1152 @group
1153 with Greetings;
1154 procedure Gmain is
1155 begin
1156    Greetings.Hello;
1157    Greetings.Goodbye;
1158 end Gmain;
1159 @end group
1160 @end cartouche
1161 @end smallexample
1163 @noindent
1164 Following the one-unit-per-file rule, place this program in the
1165 following three separate files:
1167 @table @file
1168 @item greetings.ads
1169 spec of package @code{Greetings}
1171 @item greetings.adb
1172 body of package @code{Greetings}
1174 @item gmain.adb
1175 body of main program
1176 @end table
1178 @noindent
1179 To build an executable version of
1180 this program, we could use four separate steps to compile, bind, and link
1181 the program, as follows:
1183 @smallexample
1184 $ gcc -c gmain.adb
1185 $ gcc -c greetings.adb
1186 $ gnatbind gmain
1187 $ gnatlink gmain
1188 @end smallexample
1190 @noindent
1191 Note that there is no required order of compilation when using GNAT.
1192 In particular it is perfectly fine to compile the main program first.
1193 Also, it is not necessary to compile package specs in the case where
1194 there is an accompanying body; you only need to compile the body. If you want
1195 to submit these files to the compiler for semantic checking and not code
1196 generation, then use the
1197 @option{-gnatc} switch:
1199 @smallexample
1200 $ gcc -c greetings.ads -gnatc
1201 @end smallexample
1203 @noindent
1204 Although the compilation can be done in separate steps as in the
1205 above example, in practice it is almost always more convenient
1206 to use the @command{gnatmake} tool. All you need to know in this case
1207 is the name of the main program's source file. The effect of the above four
1208 commands can be achieved with a single one:
1210 @smallexample
1211 $ gnatmake gmain.adb
1212 @end smallexample
1214 @noindent
1215 In the next section we discuss the advantages of using @command{gnatmake} in
1216 more detail.
1218 @c *****************************
1219 @node Using the gnatmake Utility
1220 @section Using the @command{gnatmake} Utility
1222 @noindent
1223 If you work on a program by compiling single components at a time using
1224 @command{gcc}, you typically keep track of the units you modify. In order to
1225 build a consistent system, you compile not only these units, but also any
1226 units that depend on the units you have modified.
1227 For example, in the preceding case,
1228 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1229 you edit @file{greetings.ads}, you must recompile both
1230 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1231 units that depend on @file{greetings.ads}.
1233 @code{gnatbind} will warn you if you forget one of these compilation
1234 steps, so that it is impossible to generate an inconsistent program as a
1235 result of forgetting to do a compilation. Nevertheless it is tedious and
1236 error-prone to keep track of dependencies among units.
1237 One approach to handle the dependency-bookkeeping is to use a
1238 makefile. However, makefiles present maintenance problems of their own:
1239 if the dependencies change as you change the program, you must make
1240 sure that the makefile is kept up-to-date manually, which is also an
1241 error-prone process.
1243 The @command{gnatmake} utility takes care of these details automatically.
1244 Invoke it using either one of the following forms:
1246 @smallexample
1247 $ gnatmake gmain.adb
1248 $ gnatmake ^gmain^GMAIN^
1249 @end smallexample
1251 @noindent
1252 The argument is the name of the file containing the main program;
1253 you may omit the extension. @command{gnatmake}
1254 examines the environment, automatically recompiles any files that need
1255 recompiling, and binds and links the resulting set of object files,
1256 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1257 In a large program, it
1258 can be extremely helpful to use @command{gnatmake}, because working out by hand
1259 what needs to be recompiled can be difficult.
1261 Note that @command{gnatmake}
1262 takes into account all the Ada 95 rules that
1263 establish dependencies among units. These include dependencies that result
1264 from inlining subprogram bodies, and from
1265 generic instantiation. Unlike some other
1266 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
1267 found by the compiler on a previous compilation, which may possibly
1268 be wrong when sources change. @command{gnatmake} determines the exact set of
1269 dependencies from scratch each time it is run.
1271 @ifset vms
1272 @node Editing with Emacs
1273 @section Editing with Emacs
1274 @cindex Emacs
1276 @noindent
1277 Emacs is an extensible self-documenting text editor that is available in a
1278 separate VMSINSTAL kit.
1280 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
1281 click on the Emacs Help menu and run the Emacs Tutorial.
1282 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
1283 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
1285 Documentation on Emacs and other tools is available in Emacs under the
1286 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
1287 use the middle mouse button to select a topic (e.g. Emacs).
1289 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
1290 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
1291 get to the Emacs manual.
1292 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
1293 prompt.
1295 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1296 which is sufficiently extensible to provide for a complete programming
1297 environment and shell for the sophisticated user.
1298 @end ifset
1300 @ifclear vms
1301 @node Introduction to GPS
1302 @section Introduction to GPS
1303 @cindex GPS (GNAT Programming System)
1304 @cindex GNAT Programming System (GPS)
1305 @noindent
1306 Although the command line interface (@command{gnatmake}, etc.) alone
1307 is sufficient, a graphical Interactive Development
1308 Environment can make it easier for you to compose, navigate, and debug
1309 programs.  This section describes the main features of GPS
1310 (``GNAT Programming System''), the GNAT graphical IDE.
1311 You will see how to use GPS to build and debug an executable, and
1312 you will also learn some of the basics of the GNAT ``project'' facility.
1314 GPS enables you to do much more than is presented here;
1315 e.g., you can produce a call graph, interface to a third-party
1316 Version Control System, and inspect the generated assembly language
1317 for a program.
1318 Indeed, GPS also supports languages other than Ada.
1319 Such additional information, and an explanation of all of the GPS menu
1320 items. may be found in the on-line help, which includes
1321 a user's guide and a tutorial (these are also accessible from the GNAT
1322 startup menu).
1324 @menu
1325 * Building a New Program with GPS::
1326 * Simple Debugging with GPS::
1327 @end menu
1329 @node Building a New Program with GPS
1330 @subsection Building a New Program with GPS
1331 @noindent
1332 GPS invokes the GNAT compilation tools using information
1333 contained in a @emph{project} (also known as a @emph{project file}):
1334 a collection of properties such
1335 as source directories, identities of main subprograms, tool switches, etc.,
1336 and their associated values.
1337 See @ref{GNAT Project Manager} for details.
1338 In order to run GPS, you will need to either create a new project
1339 or else open an existing one.
1341 This section will explain how you can use GPS to create a project,
1342 to associate Ada source files with a project, and to build and run
1343 programs.
1345 @enumerate
1346 @item @emph{Creating a project}
1348 Invoke GPS, either from the command line or the platform's IDE.
1349 After it starts, GPS will display a ``Welcome'' screen with three
1350 radio buttons:
1352 @itemize @bullet
1353 @item
1354 @code{Start with default project in directory}
1356 @item
1357 @code{Create new project with wizard}
1359 @item
1360 @code{Open existing project}
1361 @end itemize
1363 @noindent
1364 Select @code{Create new project with wizard} and press @code{OK}.
1365 A new window will appear.  In the text box labeled with
1366 @code{Enter the name of the project to create}, type @file{sample}
1367 as the project name.
1368 In the next box, browse to choose the directory in which you
1369 would like to create the project file.
1370 After selecting an appropriate directory, press @code{Forward}.
1372 A window will appear with the title
1373 @code{Version Control System Configuration}.
1374 Simply press @code{Forward}.
1376 A window will appear with the title
1377 @code{Please select the source directories for this project}.
1378 The directory that you specified for the project file will be selected
1379 by default as the one to use for sources; simply press @code{Forward}.
1381 A window will appear with the title
1382 @code{Please select the build directory for this project}.
1383 The directory that you specified for the project file will be selected
1384 by default for object files and executables;
1385 simply press @code{Forward}.
1387 A window will appear with the title
1388 @code{Please select the main units for this project}.
1389 You will supply this information later, after creating the source file.
1390 Simply press @code{Forward} for now.
1392 A window will appear with the title
1393 @code{Please select the switches to build the project}.
1394 Press @code{Apply}.  This will create a project file named
1395 @file{sample.prj} in the directory that you had specified.
1397 @item @emph{Creating and saving the source file}
1399 After you create the new project, a GPS window will appear, which is
1400 partitioned into two main sections:
1402 @itemize @bullet
1403 @item
1404 A @emph{Workspace area}, initially greyed out, which you will use for
1405 creating and editing source files
1407 @item
1408 Directly below, a @emph{Messages area}, which initially displays a
1409 ``Welcome'' message.
1410 (If the Messages area is not visible, drag its border upward to expand it.)
1411 @end itemize
1413 @noindent
1414 Select @code{File} on the menu bar, and then the @code{New} command.
1415 The Workspace area will become white, and you can now
1416 enter the source program explicitly.
1417 Type the following text
1419 @smallexample @c ada
1420 @group
1421 with Ada.Text_IO; use Ada.Text_IO;
1422 procedure Hello is
1423 begin
1424   Put_Line("Hello from GPS!");
1425 end Hello;
1426 @end group
1427 @end smallexample
1429 @noindent
1430 Select @code{File}, then @code{Save As}, and enter the source file name
1431 @file{hello.adb}.
1432 The file will be saved in the same directory you specified as the
1433 location of the default project file.
1435 @item @emph{Updating the project file}
1437 You need to add the new source file to the project.
1438 To do this, select
1439 the @code{Project} menu and then @code{Edit project properties}.
1440 Click the @code{Main files} tab on the left, and then the
1441 @code{Add} button.
1442 Choose @file{hello.adb} from the list, and press @code{Open}.
1443 The project settings window will reflect this action.
1444 Click @code{OK}.
1446 @item @emph{Building and running the program}
1448 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1449 and select @file{hello.adb}.
1450 The Messages window will display the resulting invocations of @command{gcc},
1451 @command{gnatbind}, and @command{gnatlink}
1452 (reflecting the default switch settings from the
1453 project file that you created) and then a ``successful compilation/build''
1454 message.
1456 To run the program, choose the @code{Build} menu, then @code{Run}, and
1457 select @command{hello}.
1458 An @emph{Arguments Selection} window will appear.
1459 There are no command line arguments, so just click @code{OK}.
1461 The Messages window will now display the program's output (the string
1462 @code{Hello from GPS}), and at the bottom of the GPS window a status
1463 update is displayed (@code{Run: hello}).
1464 Close the GPS window (or select @code{File}, then @code{Exit}) to
1465 terminate this GPS session.
1466 @end enumerate
1468 @node Simple Debugging with GPS
1469 @subsection Simple Debugging with GPS
1470 @noindent
1471 This section illustrates basic debugging techniques (setting breakpoints,
1472 examining/modifying variables, single stepping).
1474 @enumerate
1475 @item @emph{Opening a project}
1477 Start GPS and select @code{Open existing project}; browse to
1478 specify the project file @file{sample.prj} that you had created in the
1479 earlier example.
1481 @item @emph{Creating a source file}
1483 Select @code{File}, then @code{New}, and type in the following program:
1485 @smallexample @c ada
1486 @group
1487 with Ada.Text_IO; use Ada.Text_IO;
1488 procedure Example is
1489    Line : String (1..80);
1490    N    : Natural;
1491 begin
1492    Put_Line("Type a line of text at each prompt; an empty line to exit");
1493    loop
1494       Put(": ");
1495       Get_Line (Line, N);
1496       Put_Line (Line (1..N) );
1497       exit when N=0;
1498    end loop;
1499 end Example;
1500 @end group
1501 @end smallexample
1503 @noindent
1504 Select @code{File}, then @code{Save as}, and enter the file name
1505 @file{example.adb}.
1507 @item @emph{Updating the project file}
1509 Add @code{Example} as a new main unit for the project:
1510 @enumerate a
1511 @item
1512 Select @code{Project}, then @code{Edit Project Properties}.
1514 @item
1515 Select the @code{Main files} tab, click @code{Add}, then
1516 select the file @file{example.adb} from the list, and
1517 click @code{Open}.
1518 You will see the file name appear in the list of main units
1520 @item
1521 Click @code{OK}
1522 @end enumerate
1524 @item @emph{Building/running the executable}
1526 To build the executable
1527 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1529 Run the program to see its effect (in the Messages area).
1530 Each line that you enter is displayed; an empty line will
1531 cause the loop to exit and the program to terminate.
1533 @item @emph{Debugging the program}
1535 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1536 which are required for debugging, are on by default when you create
1537 a new project.
1538 Thus unless you intentionally remove these settings, you will be able
1539 to debug any program that you develop using GPS.
1541 @enumerate a
1542 @item @emph{Initializing}
1544 Select @code{Debug}, then @code{Initialize}, then @file{example}
1546 @item @emph{Setting a breakpoint}
1548 After performing the initialization step, you will observe a small
1549 icon to the right of each line number.
1550 This serves as a toggle for breakpoints; clicking the icon will
1551 set a breakpoint at the corresponding line (the icon will change to
1552 a red circle with an ``x''), and clicking it again
1553 will remove the breakpoint / reset the icon.
1555 For purposes of this example, set a breakpoint at line 10 (the
1556 statement @code{Put_Line@ (Line@ (1..N));}
1558 @item @emph{Starting program execution}
1560 Select @code{Debug}, then @code{Run}.  When the
1561 @code{Program Arguments} window appears, click @code{OK}.
1562 A console window will appear; enter some line of text,
1563 e.g. @code{abcde}, at the prompt.
1564 The program will pause execution when it gets to the
1565 breakpoint, and the corresponding line is highlighted.
1567 @item @emph{Examining a variable}
1569 Move the mouse over one of the occurrences of the variable @code{N}.
1570 You will see the value (5) displayed, in ``tool tip'' fashion.
1571 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1572 You will see information about @code{N} appear in the @code{Debugger Data}
1573 pane, showing the value as 5.
1575 @item @emph{Assigning a new value to a variable}
1577 Right click on the @code{N} in the @code{Debugger Data} pane, and
1578 select @code{Set value of N}.
1579 When the input window appears, enter the value @code{4} and click
1580 @code{OK}.
1581 This value does not automatically appear in the @code{Debugger Data}
1582 pane; to see it, right click again on the @code{N} in the
1583 @code{Debugger Data} pane and select @code{Update value}.
1584 The new value, 4, will appear in red.
1586 @item @emph{Single stepping}
1588 Select @code{Debug}, then @code{Next}.
1589 This will cause the next statement to be executed, in this case the
1590 call of @code{Put_Line} with the string slice.
1591 Notice in the console window that the displayed string is simply
1592 @code{abcd} and not @code{abcde} which you had entered.
1593 This is because the upper bound of the slice is now 4 rather than 5.
1595 @item @emph{Removing a breakpoint}
1597 Toggle the breakpoint icon at line 10.
1599 @item @emph{Resuming execution from a breakpoint}
1601 Select @code{Debug}, then @code{Continue}.
1602 The program will reach the next iteration of the loop, and
1603 wait for input after displaying the prompt.
1604 This time, just hit the @kbd{Enter} key.
1605 The value of @code{N} will be 0, and the program will terminate.
1606 The console window will disappear.
1607 @end enumerate
1608 @end enumerate
1610 @node Introduction to Glide and GVD
1611 @section Introduction to Glide and GVD
1612 @cindex Glide
1613 @cindex GVD
1614 @noindent
1615 This section describes the main features of Glide,
1616 a GNAT graphical IDE, and also shows how to use the basic commands in GVD,
1617 the GNU Visual Debugger.
1618 These tools may be present in addition to, or in place of, GPS on some
1619 platforms.
1620 Additional information on Glide and GVD may be found
1621 in the on-line help for these tools.
1623 @menu
1624 * Building a New Program with Glide::
1625 * Simple Debugging with GVD::
1626 * Other Glide Features::
1627 @end menu
1629 @node Building a New Program with Glide
1630 @subsection Building a New Program with Glide
1631 @noindent
1632 The simplest way to invoke Glide is to enter @command{glide}
1633 at the command prompt.  It will generally be useful to issue this
1634 as a background command, thus allowing you to continue using
1635 your command window for other purposes while Glide is running:
1637 @smallexample
1638 $ glide&
1639 @end smallexample
1641 @noindent
1642 Glide will start up with an initial screen displaying the top-level menu items
1643 as well as some other information.  The menu selections are as follows
1644 @itemize @bullet
1645 @item @code{Buffers}
1646 @item @code{Files}
1647 @item @code{Tools}
1648 @item @code{Edit}
1649 @item @code{Search}
1650 @item @code{Mule}
1651 @item @code{Glide}
1652 @item @code{Help}
1653 @end itemize
1655 @noindent
1656 For this introductory example, you will need to create a new Ada source file.
1657 First, select the @code{Files} menu.  This will pop open a menu with around
1658 a dozen or so items.  To create a file, select the @code{Open file...} choice.
1659 Depending on the platform, you may see a pop-up window where you can browse
1660 to an appropriate directory and then enter the file name, or else simply
1661 see a line at the bottom of the Glide window where you can likewise enter
1662 the file name.  Note that in Glide, when you attempt to open a non-existent
1663 file, the effect is to create a file with that name.  For this example enter
1664 @file{hello.adb} as the name of the file.
1666 A new buffer will now appear, occupying the entire Glide window,
1667 with the file name at the top.  The menu selections are slightly different
1668 from the ones you saw on the opening screen; there is an @code{Entities} item,
1669 and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses
1670 the file extension to identify the source language, so @file{adb} indicates
1671 an Ada source file.
1673 You will enter some of the source program lines explicitly,
1674 and use the syntax-oriented template mechanism to enter other lines.
1675 First, type the following text:
1676 @smallexample
1677 with Ada.Text_IO; use Ada.Text_IO;
1678 procedure Hello is
1679 begin
1680 @end smallexample
1682 @noindent
1683 Observe that Glide uses different colors to distinguish reserved words from
1684 identifiers.  Also, after the @code{procedure Hello is} line, the cursor is
1685 automatically indented in anticipation of declarations.  When you enter
1686 @code{begin}, Glide recognizes that there are no declarations and thus places
1687 @code{begin} flush left.  But after the @code{begin} line the cursor is again
1688 indented, where the statement(s) will be placed.
1690 The main part of the program will be a @code{for} loop.  Instead of entering
1691 the text explicitly, however, use a statement template.  Select the @code{Ada}
1692 item on the top menu bar, move the mouse to the @code{Statements} item,
1693 and you will see a large selection of alternatives.  Choose @code{for loop}.
1694 You will be prompted (at the bottom of the buffer) for a loop name;
1695 simply press the @key{Enter} key since a loop name is not needed.
1696 You should see the beginning of a @code{for} loop appear in the source
1697 program window.  You will now be prompted for the name of the loop variable;
1698 enter a line with the identifier @code{ind} (lower case).  Note that,
1699 by default, Glide capitalizes the name (you can override such behavior
1700 if you wish, although this is outside the scope of this introduction).
1701 Next, Glide prompts you for the loop range; enter a line containing
1702 @code{1..5} and you will see this also appear in the source program,
1703 together with the remaining elements of the @code{for} loop syntax.
1705 Next enter the statement (with an intentional error, a missing semicolon)
1706 that will form the body of the loop:
1707 @smallexample
1708 Put_Line("Hello, World" & Integer'Image(I))
1709 @end smallexample
1711 @noindent
1712 Finally, type @code{end Hello;} as the last line in the program.
1713 Now save the file: choose the @code{File} menu item, and then the
1714 @code{Save buffer} selection.  You will see a message at the bottom
1715 of the buffer confirming that the file has been saved.
1717 You are now ready to attempt to build the program.  Select the @code{Ada}
1718 item from the top menu bar.  Although we could choose simply to compile
1719 the file, we will instead attempt to do a build (which invokes
1720 @command{gnatmake}) since, if the compile is successful, we want to build
1721 an executable.  Thus select @code{Ada build}.  This will fail because of the
1722 compilation error, and you will notice that the Glide window has been split:
1723 the top window contains the source file, and the bottom window contains the
1724 output from the GNAT tools. Glide allows you to navigate from a compilation
1725 error to the source file position corresponding to the error: click the
1726 middle mouse button (or simultaneously press the left and right buttons,
1727 on a two-button mouse) on the diagnostic line in the tool window.  The
1728 focus will shift to the source window, and the cursor will be positioned
1729 on the character at which the error was detected.
1731 Correct the error: type in a semicolon to terminate the statement.
1732 Although you can again save the file explicitly, you can also simply invoke
1733 @code{Ada} @result{} @code{Build} and you will be prompted to save the file.
1734 This time the build will succeed; the tool output window shows you the
1735 options that are supplied by default.  The GNAT tools' output (e.g.
1736 object and ALI files, executable) will go in the directory from which
1737 Glide was launched.
1739 To execute the program, choose @code{Ada} and then @code{Run}.
1740 You should see the program's output displayed in the bottom window:
1742 @smallexample
1743 Hello, world 1
1744 Hello, world 2
1745 Hello, world 3
1746 Hello, world 4
1747 Hello, world 5
1748 @end smallexample
1750 @node Simple Debugging with GVD
1751 @subsection Simple Debugging with GVD
1753 @noindent
1754 This section describes how to set breakpoints, examine/modify variables,
1755 and step through execution.
1757 In order to enable debugging, you need to pass the @option{-g} switch
1758 to both the compiler and to @command{gnatlink}.  If you are using
1759 the command line, passing @option{-g} to @command{gnatmake} will have
1760 this effect.  You can then launch GVD, e.g. on the @code{hello} program,
1761 by issuing the command:
1763 @smallexample
1764 $ gvd hello
1765 @end smallexample
1767 @noindent
1768 If you are using Glide, then @option{-g} is passed to the relevant tools
1769 by default when you do a build.  Start the debugger by selecting the
1770 @code{Ada} menu item, and then @code{Debug}.
1772 GVD comes up in a multi-part window.  One pane shows the names of files
1773 comprising your executable; another pane shows the source code of the current
1774 unit (initially your main subprogram), another pane shows the debugger output
1775 and user interactions, and the fourth pane (the data canvas at the top
1776 of the window) displays data objects that you have selected.
1778 To the left of the source file pane, you will notice green dots adjacent
1779 to some lines.  These are lines for which object code exists and where
1780 breakpoints can thus be set.  You set/reset a breakpoint by clicking
1781 the green dot.  When a breakpoint is set, the dot is replaced by an @code{X}
1782 in a red circle.  Clicking the circle toggles the breakpoint off,
1783 and the red circle is replaced by the green dot.
1785 For this example, set a breakpoint at the statement where @code{Put_Line}
1786 is invoked.
1788 Start program execution by selecting the @code{Run} button on the top menu bar.
1789 (The @code{Start} button will also start your program, but it will
1790 cause program execution to break at the entry to your main subprogram.)
1791 Evidence of reaching the breakpoint will appear: the source file line will be
1792 highlighted, and the debugger interactions pane will display
1793 a relevant message.
1795 You can examine the values of variables in several ways.  Move the mouse
1796 over an occurrence of @code{Ind} in the @code{for} loop, and you will see
1797 the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind}
1798 and select @code{Display Ind}; a box showing the variable's name and value
1799 will appear in the data canvas.
1801 Although a loop index is a constant with respect to Ada semantics,
1802 you can change its value in the debugger.  Right-click in the box
1803 for @code{Ind}, and select the @code{Set Value of Ind} item.
1804 Enter @code{2} as the new value, and press @command{OK}.
1805 The box for @code{Ind} shows the update.
1807 Press the @code{Step} button on the top menu bar; this will step through
1808 one line of program text (the invocation of @code{Put_Line}), and you can
1809 observe the effect of having modified @code{Ind} since the value displayed
1810 is @code{2}.
1812 Remove the breakpoint, and resume execution by selecting the @code{Cont}
1813 button.  You will see the remaining output lines displayed in the debugger
1814 interaction window, along with a message confirming normal program
1815 termination.
1817 @node Other Glide Features
1818 @subsection Other Glide Features
1820 @noindent
1821 You may have observed that some of the menu selections contain abbreviations;
1822 e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.
1823 These are @emph{shortcut keys} that you can use instead of selecting
1824 menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means
1825 @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead
1826 of selecting @code{Files} and then @code{Open file...}.
1828 To abort a Glide command, type @key{Ctrl-g}.
1830 If you want Glide to start with an existing source file, you can either
1831 launch Glide as above and then open the file via @code{Files} @result{}
1832 @code{Open file...}, or else simply pass the name of the source file
1833 on the command line:
1835 @smallexample
1836 $ glide hello.adb&
1837 @end smallexample
1839 @noindent
1840 While you are using Glide, a number of @emph{buffers} exist.
1841 You create some explicitly; e.g., when you open/create a file.
1842 Others arise as an effect of the commands that you issue; e.g., the buffer
1843 containing the output of the tools invoked during a build.  If a buffer
1844 is hidden, you can bring it into a visible window by first opening
1845 the @code{Buffers} menu and then selecting the desired entry.
1847 If a buffer occupies only part of the Glide screen and you want to expand it
1848 to fill the entire screen, then click in the buffer and then select
1849 @code{Files} @result{} @code{One Window}.
1851 If a window is occupied by one buffer and you want to split the window
1852 to bring up a second buffer, perform the following steps:
1853 @itemize @bullet
1854 @item Select @code{Files} @result{} @code{Split Window};
1855 this will produce two windows each of which holds the original buffer
1856 (these are not copies, but rather different views of the same buffer contents)
1858 @item With the focus in one of the windows,
1859 select the desired buffer from the @code{Buffers} menu
1860 @end itemize
1862 @noindent
1863 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1864 @end ifclear
1866 @node The GNAT Compilation Model
1867 @chapter The GNAT Compilation Model
1868 @cindex GNAT compilation model
1869 @cindex Compilation model
1871 @menu
1872 * Source Representation::
1873 * Foreign Language Representation::
1874 * File Naming Rules::
1875 * Using Other File Names::
1876 * Alternative File Naming Schemes::
1877 * Generating Object Files::
1878 * Source Dependencies::
1879 * The Ada Library Information Files::
1880 * Binding an Ada Program::
1881 * Mixed Language Programming::
1882 * Building Mixed Ada & C++ Programs::
1883 * Comparison between GNAT and C/C++ Compilation Models::
1884 * Comparison between GNAT and Conventional Ada Library Models::
1885 @ifset vms
1886 * Placement of temporary files::
1887 @end ifset
1888 @end menu
1890 @noindent
1891 This chapter describes the compilation model used by GNAT. Although
1892 similar to that used by other languages, such as C and C++, this model
1893 is substantially different from the traditional Ada compilation models,
1894 which are based on a library. The model is initially described without
1895 reference to the library-based model. If you have not previously used an
1896 Ada compiler, you need only read the first part of this chapter. The
1897 last section describes and discusses the differences between the GNAT
1898 model and the traditional Ada compiler models. If you have used other
1899 Ada compilers, this section will help you to understand those
1900 differences, and the advantages of the GNAT model.
1902 @node Source Representation
1903 @section Source Representation
1904 @cindex Latin-1
1906 @noindent
1907 Ada source programs are represented in standard text files, using
1908 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1909 7-bit ASCII set, plus additional characters used for
1910 representing foreign languages (@pxref{Foreign Language Representation}
1911 for support of non-USA character sets). The format effector characters
1912 are represented using their standard ASCII encodings, as follows:
1914 @table @code
1915 @item VT
1916 @findex VT
1917 Vertical tab, @code{16#0B#}
1919 @item HT
1920 @findex HT
1921 Horizontal tab, @code{16#09#}
1923 @item CR
1924 @findex CR
1925 Carriage return, @code{16#0D#}
1927 @item LF
1928 @findex LF
1929 Line feed, @code{16#0A#}
1931 @item FF
1932 @findex FF
1933 Form feed, @code{16#0C#}
1934 @end table
1936 @noindent
1937 Source files are in standard text file format. In addition, GNAT will
1938 recognize a wide variety of stream formats, in which the end of
1939 physical lines is marked by any of the following sequences:
1940 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1941 in accommodating files that are imported from other operating systems.
1943 @cindex End of source file
1944 @cindex Source file, end
1945 @findex SUB
1946 The end of a source file is normally represented by the physical end of
1947 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1948 recognized as signalling the end of the source file. Again, this is
1949 provided for compatibility with other operating systems where this
1950 code is used to represent the end of file.
1952 Each file contains a single Ada compilation unit, including any pragmas
1953 associated with the unit. For example, this means you must place a
1954 package declaration (a package @dfn{spec}) and the corresponding body in
1955 separate files. An Ada @dfn{compilation} (which is a sequence of
1956 compilation units) is represented using a sequence of files. Similarly,
1957 you will place each subunit or child unit in a separate file.
1959 @node Foreign Language Representation
1960 @section Foreign Language Representation
1962 @noindent
1963 GNAT supports the standard character sets defined in Ada 95 as well as
1964 several other non-standard character sets for use in localized versions
1965 of the compiler (@pxref{Character Set Control}).
1966 @menu
1967 * Latin-1::
1968 * Other 8-Bit Codes::
1969 * Wide Character Encodings::
1970 @end menu
1972 @node Latin-1
1973 @subsection Latin-1
1974 @cindex Latin-1
1976 @noindent
1977 The basic character set is Latin-1. This character set is defined by ISO
1978 standard 8859, part 1. The lower half (character codes @code{16#00#}
1979 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half
1980 is used to represent additional characters. These include extended letters
1981 used by European languages, such as French accents, the vowels with umlauts
1982 used in German, and the extra letter A-ring used in Swedish.
1984 @findex Ada.Characters.Latin_1
1985 For a complete list of Latin-1 codes and their encodings, see the source
1986 file of library unit @code{Ada.Characters.Latin_1} in file
1987 @file{a-chlat1.ads}.
1988 You may use any of these extended characters freely in character or
1989 string literals. In addition, the extended characters that represent
1990 letters can be used in identifiers.
1992 @node Other 8-Bit Codes
1993 @subsection Other 8-Bit Codes
1995 @noindent
1996 GNAT also supports several other 8-bit coding schemes:
1998 @table @asis
1999 @item ISO 8859-2 (Latin-2)
2000 @cindex Latin-2
2001 @cindex ISO 8859-2
2002 Latin-2 letters allowed in identifiers, with uppercase and lowercase
2003 equivalence.
2005 @item ISO 8859-3 (Latin-3)
2006 @cindex Latin-3
2007 @cindex ISO 8859-3
2008 Latin-3 letters allowed in identifiers, with uppercase and lowercase
2009 equivalence.
2011 @item ISO 8859-4 (Latin-4)
2012 @cindex Latin-4
2013 @cindex ISO 8859-4
2014 Latin-4 letters allowed in identifiers, with uppercase and lowercase
2015 equivalence.
2017 @item ISO 8859-5 (Cyrillic)
2018 @cindex ISO 8859-5
2019 @cindex Cyrillic
2020 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
2021 lowercase equivalence.
2023 @item ISO 8859-15 (Latin-9)
2024 @cindex ISO 8859-15
2025 @cindex Latin-9
2026 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
2027 lowercase equivalence
2029 @item IBM PC (code page 437)
2030 @cindex code page 437
2031 This code page is the normal default for PCs in the U.S. It corresponds
2032 to the original IBM PC character set. This set has some, but not all, of
2033 the extended Latin-1 letters, but these letters do not have the same
2034 encoding as Latin-1. In this mode, these letters are allowed in
2035 identifiers with uppercase and lowercase equivalence.
2037 @item IBM PC (code page 850)
2038 @cindex code page 850
2039 This code page is a modification of 437 extended to include all the
2040 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
2041 mode, all these letters are allowed in identifiers with uppercase and
2042 lowercase equivalence.
2044 @item Full Upper 8-bit
2045 Any character in the range 80-FF allowed in identifiers, and all are
2046 considered distinct. In other words, there are no uppercase and lowercase
2047 equivalences in this range. This is useful in conjunction with
2048 certain encoding schemes used for some foreign character sets (e.g.
2049 the typical method of representing Chinese characters on the PC).
2051 @item No Upper-Half
2052 No upper-half characters in the range 80-FF are allowed in identifiers.
2053 This gives Ada 83 compatibility for identifier names.
2054 @end table
2056 @noindent
2057 For precise data on the encodings permitted, and the uppercase and lowercase
2058 equivalences that are recognized, see the file @file{csets.adb} in
2059 the GNAT compiler sources. You will need to obtain a full source release
2060 of GNAT to obtain this file.
2062 @node Wide Character Encodings
2063 @subsection Wide Character Encodings
2065 @noindent
2066 GNAT allows wide character codes to appear in character and string
2067 literals, and also optionally in identifiers, by means of the following
2068 possible encoding schemes:
2070 @table @asis
2072 @item Hex Coding
2073 In this encoding, a wide character is represented by the following five
2074 character sequence:
2076 @smallexample
2077 ESC a b c d
2078 @end smallexample
2080 @noindent
2081 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2082 characters (using uppercase letters) of the wide character code. For
2083 example, ESC A345 is used to represent the wide character with code
2084 @code{16#A345#}.
2085 This scheme is compatible with use of the full Wide_Character set.
2087 @item Upper-Half Coding
2088 @cindex Upper-Half Coding
2089 The wide character with encoding @code{16#abcd#} where the upper bit is on
2090 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
2091 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
2092 character, but is not required to be in the upper half. This method can
2093 be also used for shift-JIS or EUC, where the internal coding matches the
2094 external coding.
2096 @item Shift JIS Coding
2097 @cindex Shift JIS Coding
2098 A wide character is represented by a two-character sequence,
2099 @code{16#ab#} and
2100 @code{16#cd#}, with the restrictions described for upper-half encoding as
2101 described above. The internal character code is the corresponding JIS
2102 character according to the standard algorithm for Shift-JIS
2103 conversion. Only characters defined in the JIS code set table can be
2104 used with this encoding method.
2106 @item EUC Coding
2107 @cindex EUC Coding
2108 A wide character is represented by a two-character sequence
2109 @code{16#ab#} and
2110 @code{16#cd#}, with both characters being in the upper half. The internal
2111 character code is the corresponding JIS character according to the EUC
2112 encoding algorithm. Only characters defined in the JIS code set table
2113 can be used with this encoding method.
2115 @item UTF-8 Coding
2116 A wide character is represented using
2117 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
2118 10646-1/Am.2. Depending on the character value, the representation
2119 is a one, two, or three byte sequence:
2120 @smallexample
2121 @iftex
2122 @leftskip=.7cm
2123 @end iftex
2124 16#0000#-16#007f#: 2#0xxxxxxx#
2125 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
2126 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
2128 @end smallexample
2130 @noindent
2131 where the xxx bits correspond to the left-padded bits of the
2132 16-bit character value. Note that all lower half ASCII characters
2133 are represented as ASCII bytes and all upper half characters and
2134 other wide characters are represented as sequences of upper-half
2135 (The full UTF-8 scheme allows for encoding 31-bit characters as
2136 6-byte sequences, but in this implementation, all UTF-8 sequences
2137 of four or more bytes length will be treated as illegal).
2138 @item Brackets Coding
2139 In this encoding, a wide character is represented by the following eight
2140 character sequence:
2142 @smallexample
2143 [ " a b c d " ]
2144 @end smallexample
2146 @noindent
2147 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
2148 characters (using uppercase letters) of the wide character code. For
2149 example, [``A345''] is used to represent the wide character with code
2150 @code{16#A345#}. It is also possible (though not required) to use the
2151 Brackets coding for upper half characters. For example, the code
2152 @code{16#A3#} can be represented as @code{[``A3'']}.
2154 This scheme is compatible with use of the full Wide_Character set,
2155 and is also the method used for wide character encoding in the standard
2156 ACVC (Ada Compiler Validation Capability) test suite distributions.
2158 @end table
2160 @noindent
2161 Note: Some of these coding schemes do not permit the full use of the
2162 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
2163 use of the upper half of the Latin-1 set.
2165 @node File Naming Rules
2166 @section File Naming Rules
2168 @noindent
2169 The default file name is determined by the name of the unit that the
2170 file contains. The name is formed by taking the full expanded name of
2171 the unit and replacing the separating dots with hyphens and using
2172 ^lowercase^uppercase^ for all letters.
2174 An exception arises if the file name generated by the above rules starts
2175 with one of the characters
2176 @ifset vms
2177 A,G,I, or S,
2178 @end ifset
2179 @ifclear vms
2180 a,g,i, or s,
2181 @end ifclear
2182 and the second character is a
2183 minus. In this case, the character ^tilde^dollar sign^ is used in place
2184 of the minus. The reason for this special rule is to avoid clashes with
2185 the standard names for child units of the packages System, Ada,
2186 Interfaces, and GNAT, which use the prefixes
2187 @ifset vms
2188 S- A- I- and G-
2189 @end ifset
2190 @ifclear vms
2191 s- a- i- and g-
2192 @end ifclear
2193 respectively.
2195 The file extension is @file{.ads} for a spec and
2196 @file{.adb} for a body. The following list shows some
2197 examples of these rules.
2199 @table @file
2200 @item main.ads
2201 Main (spec)
2202 @item main.adb
2203 Main (body)
2204 @item arith_functions.ads
2205 Arith_Functions (package spec)
2206 @item arith_functions.adb
2207 Arith_Functions (package body)
2208 @item func-spec.ads
2209 Func.Spec (child package spec)
2210 @item func-spec.adb
2211 Func.Spec (child package body)
2212 @item main-sub.adb
2213 Sub (subunit of Main)
2214 @item ^a~bad.adb^A$BAD.ADB^
2215 A.Bad (child package body)
2216 @end table
2218 @noindent
2219 Following these rules can result in excessively long
2220 file names if corresponding
2221 unit names are long (for example, if child units or subunits are
2222 heavily nested). An option is available to shorten such long file names
2223 (called file name ``krunching''). This may be particularly useful when
2224 programs being developed with GNAT are to be used on operating systems
2225 with limited file name lengths. @xref{Using gnatkr}.
2227 Of course, no file shortening algorithm can guarantee uniqueness over
2228 all possible unit names; if file name krunching is used, it is your
2229 responsibility to ensure no name clashes occur. Alternatively you
2230 can specify the exact file names that you want used, as described
2231 in the next section. Finally, if your Ada programs are migrating from a
2232 compiler with a different naming convention, you can use the gnatchop
2233 utility to produce source files that follow the GNAT naming conventions.
2234 (For details @pxref{Renaming Files Using gnatchop}.)
2236 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
2237 systems, case is not significant. So for example on @code{Windows XP}
2238 if the canonical name is @code{main-sub.adb}, you can use the file name
2239 @code{Main-Sub.adb} instead. However, case is significant for other
2240 operating systems, so for example, if you want to use other than
2241 canonically cased file names on a Unix system, you need to follow
2242 the procedures described in the next section.
2244 @node Using Other File Names
2245 @section Using Other File Names
2246 @cindex File names
2248 @noindent
2249 In the previous section, we have described the default rules used by
2250 GNAT to determine the file name in which a given unit resides. It is
2251 often convenient to follow these default rules, and if you follow them,
2252 the compiler knows without being explicitly told where to find all
2253 the files it needs.
2255 However, in some cases, particularly when a program is imported from
2256 another Ada compiler environment, it may be more convenient for the
2257 programmer to specify which file names contain which units. GNAT allows
2258 arbitrary file names to be used by means of the Source_File_Name pragma.
2259 The form of this pragma is as shown in the following examples:
2260 @cindex Source_File_Name pragma
2262 @smallexample @c ada
2263 @cartouche
2264 pragma Source_File_Name (My_Utilities.Stacks,
2265   Spec_File_Name => "myutilst_a.ada");
2266 pragma Source_File_name (My_Utilities.Stacks,
2267   Body_File_Name => "myutilst.ada");
2268 @end cartouche
2269 @end smallexample
2271 @noindent
2272 As shown in this example, the first argument for the pragma is the unit
2273 name (in this example a child unit). The second argument has the form
2274 of a named association. The identifier
2275 indicates whether the file name is for a spec or a body;
2276 the file name itself is given by a string literal.
2278 The source file name pragma is a configuration pragma, which means that
2279 normally it will be placed in the @file{gnat.adc}
2280 file used to hold configuration
2281 pragmas that apply to a complete compilation environment.
2282 For more details on how the @file{gnat.adc} file is created and used
2283 see @ref{Handling of Configuration Pragmas}.
2284 @cindex @file{gnat.adc}
2286 @ifclear vms
2287 GNAT allows completely arbitrary file names to be specified using the
2288 source file name pragma. However, if the file name specified has an
2289 extension other than @file{.ads} or @file{.adb} it is necessary to use
2290 a special syntax when compiling the file. The name in this case must be
2291 preceded by the special sequence @code{-x} followed by a space and the name
2292 of the language, here @code{ada}, as in:
2294 @smallexample
2295 $ gcc -c -x ada peculiar_file_name.sim
2296 @end smallexample
2297 @end ifclear
2299 @noindent
2300 @command{gnatmake} handles non-standard file names in the usual manner (the
2301 non-standard file name for the main program is simply used as the
2302 argument to gnatmake). Note that if the extension is also non-standard,
2303 then it must be included in the gnatmake command, it may not be omitted.
2305 @node Alternative File Naming Schemes
2306 @section Alternative File Naming Schemes
2307 @cindex File naming schemes, alternative
2308 @cindex File names
2310 In the previous section, we described the use of the @code{Source_File_Name}
2311 pragma to allow arbitrary names to be assigned to individual source files.
2312 However, this approach requires one pragma for each file, and especially in
2313 large systems can result in very long @file{gnat.adc} files, and also create
2314 a maintenance problem.
2316 GNAT also provides a facility for specifying systematic file naming schemes
2317 other than the standard default naming scheme previously described. An
2318 alternative scheme for naming is specified by the use of
2319 @code{Source_File_Name} pragmas having the following format:
2320 @cindex Source_File_Name pragma
2322 @smallexample @c ada
2323 pragma Source_File_Name (
2324    Spec_File_Name  => FILE_NAME_PATTERN
2325  [,Casing          => CASING_SPEC]
2326  [,Dot_Replacement => STRING_LITERAL]);
2328 pragma Source_File_Name (
2329    Body_File_Name  => FILE_NAME_PATTERN
2330  [,Casing          => CASING_SPEC]
2331  [,Dot_Replacement => STRING_LITERAL]);
2333 pragma Source_File_Name (
2334    Subunit_File_Name  => FILE_NAME_PATTERN
2335  [,Casing             => CASING_SPEC]
2336  [,Dot_Replacement    => STRING_LITERAL]);
2338 FILE_NAME_PATTERN ::= STRING_LITERAL
2339 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2340 @end smallexample
2342 @noindent
2343 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2344 It contains a single asterisk character, and the unit name is substituted
2345 systematically for this asterisk. The optional parameter
2346 @code{Casing} indicates
2347 whether the unit name is to be all upper-case letters, all lower-case letters,
2348 or mixed-case. If no
2349 @code{Casing} parameter is used, then the default is all
2350 ^lower-case^upper-case^.
2352 The optional @code{Dot_Replacement} string is used to replace any periods
2353 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2354 argument is used then separating dots appear unchanged in the resulting
2355 file name.
2356 Although the above syntax indicates that the
2357 @code{Casing} argument must appear
2358 before the @code{Dot_Replacement} argument, but it
2359 is also permissible to write these arguments in the opposite order.
2361 As indicated, it is possible to specify different naming schemes for
2362 bodies, specs, and subunits. Quite often the rule for subunits is the
2363 same as the rule for bodies, in which case, there is no need to give
2364 a separate @code{Subunit_File_Name} rule, and in this case the
2365 @code{Body_File_name} rule is used for subunits as well.
2367 The separate rule for subunits can also be used to implement the rather
2368 unusual case of a compilation environment (e.g. a single directory) which
2369 contains a subunit and a child unit with the same unit name. Although
2370 both units cannot appear in the same partition, the Ada Reference Manual
2371 allows (but does not require) the possibility of the two units coexisting
2372 in the same environment.
2374 The file name translation works in the following steps:
2376 @itemize @bullet
2378 @item
2379 If there is a specific @code{Source_File_Name} pragma for the given unit,
2380 then this is always used, and any general pattern rules are ignored.
2382 @item
2383 If there is a pattern type @code{Source_File_Name} pragma that applies to
2384 the unit, then the resulting file name will be used if the file exists. If
2385 more than one pattern matches, the latest one will be tried first, and the
2386 first attempt resulting in a reference to a file that exists will be used.
2388 @item
2389 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2390 for which the corresponding file exists, then the standard GNAT default
2391 naming rules are used.
2393 @end itemize
2395 @noindent
2396 As an example of the use of this mechanism, consider a commonly used scheme
2397 in which file names are all lower case, with separating periods copied
2398 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
2399 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
2400 two pragmas appear:
2402 @smallexample @c ada
2403 pragma Source_File_Name
2404   (Spec_File_Name => "*.1.ada");
2405 pragma Source_File_Name
2406   (Body_File_Name => "*.2.ada");
2407 @end smallexample
2409 @noindent
2410 The default GNAT scheme is actually implemented by providing the following
2411 default pragmas internally:
2413 @smallexample @c ada
2414 pragma Source_File_Name
2415   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2416 pragma Source_File_Name
2417   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2418 @end smallexample
2420 @noindent
2421 Our final example implements a scheme typically used with one of the
2422 Ada 83 compilers, where the separator character for subunits was ``__''
2423 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2424 by adding @file{.ADA}, and subunits by
2425 adding @file{.SEP}. All file names were
2426 upper case. Child units were not present of course since this was an
2427 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2428 the same double underscore separator for child units.
2430 @smallexample @c ada
2431 pragma Source_File_Name
2432   (Spec_File_Name => "*_.ADA",
2433    Dot_Replacement => "__",
2434    Casing = Uppercase);
2435 pragma Source_File_Name
2436   (Body_File_Name => "*.ADA",
2437    Dot_Replacement => "__",
2438    Casing = Uppercase);
2439 pragma Source_File_Name
2440   (Subunit_File_Name => "*.SEP",
2441    Dot_Replacement => "__",
2442    Casing = Uppercase);
2443 @end smallexample
2445 @node Generating Object Files
2446 @section Generating Object Files
2448 @noindent
2449 An Ada program consists of a set of source files, and the first step in
2450 compiling the program is to generate the corresponding object files.
2451 These are generated by compiling a subset of these source files.
2452 The files you need to compile are the following:
2454 @itemize @bullet
2455 @item
2456 If a package spec has no body, compile the package spec to produce the
2457 object file for the package.
2459 @item
2460 If a package has both a spec and a body, compile the body to produce the
2461 object file for the package. The source file for the package spec need
2462 not be compiled in this case because there is only one object file, which
2463 contains the code for both the spec and body of the package.
2465 @item
2466 For a subprogram, compile the subprogram body to produce the object file
2467 for the subprogram. The spec, if one is present, is as usual in a
2468 separate file, and need not be compiled.
2470 @item
2471 @cindex Subunits
2472 In the case of subunits, only compile the parent unit. A single object
2473 file is generated for the entire subunit tree, which includes all the
2474 subunits.
2476 @item
2477 Compile child units independently of their parent units
2478 (though, of course, the spec of all the ancestor unit must be present in order
2479 to compile a child unit).
2481 @item
2482 @cindex Generics
2483 Compile generic units in the same manner as any other units. The object
2484 files in this case are small dummy files that contain at most the
2485 flag used for elaboration checking. This is because GNAT always handles generic
2486 instantiation by means of macro expansion. However, it is still necessary to
2487 compile generic units, for dependency checking and elaboration purposes.
2488 @end itemize
2490 @noindent
2491 The preceding rules describe the set of files that must be compiled to
2492 generate the object files for a program. Each object file has the same
2493 name as the corresponding source file, except that the extension is
2494 @file{.o} as usual.
2496 You may wish to compile other files for the purpose of checking their
2497 syntactic and semantic correctness. For example, in the case where a
2498 package has a separate spec and body, you would not normally compile the
2499 spec. However, it is convenient in practice to compile the spec to make
2500 sure it is error-free before compiling clients of this spec, because such
2501 compilations will fail if there is an error in the spec.
2503 GNAT provides an option for compiling such files purely for the
2504 purposes of checking correctness; such compilations are not required as
2505 part of the process of building a program. To compile a file in this
2506 checking mode, use the @option{-gnatc} switch.
2508 @node Source Dependencies
2509 @section Source Dependencies
2511 @noindent
2512 A given object file clearly depends on the source file which is compiled
2513 to produce it. Here we are using @dfn{depends} in the sense of a typical
2514 @code{make} utility; in other words, an object file depends on a source
2515 file if changes to the source file require the object file to be
2516 recompiled.
2517 In addition to this basic dependency, a given object may depend on
2518 additional source files as follows:
2520 @itemize @bullet
2521 @item
2522 If a file being compiled @code{with}'s a unit @var{X}, the object file
2523 depends on the file containing the spec of unit @var{X}. This includes
2524 files that are @code{with}'ed implicitly either because they are parents
2525 of @code{with}'ed child units or they are run-time units required by the
2526 language constructs used in a particular unit.
2528 @item
2529 If a file being compiled instantiates a library level generic unit, the
2530 object file depends on both the spec and body files for this generic
2531 unit.
2533 @item
2534 If a file being compiled instantiates a generic unit defined within a
2535 package, the object file depends on the body file for the package as
2536 well as the spec file.
2538 @item
2539 @findex Inline
2540 @cindex @option{-gnatn} switch
2541 If a file being compiled contains a call to a subprogram for which
2542 pragma @code{Inline} applies and inlining is activated with the
2543 @option{-gnatn} switch, the object file depends on the file containing the
2544 body of this subprogram as well as on the file containing the spec. Note
2545 that for inlining to actually occur as a result of the use of this switch,
2546 it is necessary to compile in optimizing mode.
2548 @cindex @option{-gnatN} switch
2549 The use of @option{-gnatN} activates a more extensive inlining optimization
2550 that is performed by the front end of the compiler. This inlining does
2551 not require that the code generation be optimized. Like @option{-gnatn},
2552 the use of this switch generates additional dependencies.
2553 Note that
2554 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
2555 to specify both options.
2557 @item
2558 If an object file O  depends on the proper body of a subunit through inlining
2559 or instantiation, it depends on the parent unit of the subunit. This means that
2560 any modification of the parent unit or one of its subunits affects the
2561 compilation of O.
2563 @item
2564 The object file for a parent unit depends on all its subunit body files.
2566 @item
2567 The previous two rules meant that for purposes of computing dependencies and
2568 recompilation, a body and all its subunits are treated as an indivisible whole.
2570 @noindent
2571 These rules are applied transitively: if unit @code{A} @code{with}'s
2572 unit @code{B}, whose elaboration calls an inlined procedure in package
2573 @code{C}, the object file for unit @code{A} will depend on the body of
2574 @code{C}, in file @file{c.adb}.
2576 The set of dependent files described by these rules includes all the
2577 files on which the unit is semantically dependent, as described in the
2578 Ada 95 Language Reference Manual. However, it is a superset of what the
2579 ARM describes, because it includes generic, inline, and subunit dependencies.
2581 An object file must be recreated by recompiling the corresponding source
2582 file if any of the source files on which it depends are modified. For
2583 example, if the @code{make} utility is used to control compilation,
2584 the rule for an Ada object file must mention all the source files on
2585 which the object file depends, according to the above definition.
2586 The determination of the necessary
2587 recompilations is done automatically when one uses @command{gnatmake}.
2588 @end itemize
2590 @node The Ada Library Information Files
2591 @section The Ada Library Information Files
2592 @cindex Ada Library Information files
2593 @cindex @file{ALI} files
2595 @noindent
2596 Each compilation actually generates two output files. The first of these
2597 is the normal object file that has a @file{.o} extension. The second is a
2598 text file containing full dependency information. It has the same
2599 name as the source file, but an @file{.ali} extension.
2600 This file is known as the Ada Library Information (@file{ALI}) file.
2601 The following information is contained in the @file{ALI} file.
2603 @itemize @bullet
2604 @item
2605 Version information (indicates which version of GNAT was used to compile
2606 the unit(s) in question)
2608 @item
2609 Main program information (including priority and time slice settings,
2610 as well as the wide character encoding used during compilation).
2612 @item
2613 List of arguments used in the @command{gcc} command for the compilation
2615 @item
2616 Attributes of the unit, including configuration pragmas used, an indication
2617 of whether the compilation was successful, exception model used etc.
2619 @item
2620 A list of relevant restrictions applying to the unit (used for consistency)
2621 checking.
2623 @item
2624 Categorization information (e.g. use of pragma @code{Pure}).
2626 @item
2627 Information on all @code{with}'ed units, including presence of
2628 @code{Elaborate} or @code{Elaborate_All} pragmas.
2630 @item
2631 Information from any @code{Linker_Options} pragmas used in the unit
2633 @item
2634 Information on the use of @code{Body_Version} or @code{Version}
2635 attributes in the unit.
2637 @item
2638 Dependency information. This is a list of files, together with
2639 time stamp and checksum information. These are files on which
2640 the unit depends in the sense that recompilation is required
2641 if any of these units are modified.
2643 @item
2644 Cross-reference data. Contains information on all entities referenced
2645 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2646 provide cross-reference information.
2648 @end itemize
2650 @noindent
2651 For a full detailed description of the format of the @file{ALI} file,
2652 see the source of the body of unit @code{Lib.Writ}, contained in file
2653 @file{lib-writ.adb} in the GNAT compiler sources.
2655 @node Binding an Ada Program
2656 @section Binding an Ada Program
2658 @noindent
2659 When using languages such as C and C++, once the source files have been
2660 compiled the only remaining step in building an executable program
2661 is linking the object modules together. This means that it is possible to
2662 link an inconsistent version of a program, in which two units have
2663 included different versions of the same header.
2665 The rules of Ada do not permit such an inconsistent program to be built.
2666 For example, if two clients have different versions of the same package,
2667 it is illegal to build a program containing these two clients.
2668 These rules are enforced by the GNAT binder, which also determines an
2669 elaboration order consistent with the Ada rules.
2671 The GNAT binder is run after all the object files for a program have
2672 been created. It is given the name of the main program unit, and from
2673 this it determines the set of units required by the program, by reading the
2674 corresponding ALI files. It generates error messages if the program is
2675 inconsistent or if no valid order of elaboration exists.
2677 If no errors are detected, the binder produces a main program, in Ada by
2678 default, that contains calls to the elaboration procedures of those
2679 compilation unit that require them, followed by
2680 a call to the main program. This Ada program is compiled to generate the
2681 object file for the main program. The name of
2682 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2683 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2684 main program unit.
2686 Finally, the linker is used to build the resulting executable program,
2687 using the object from the main program from the bind step as well as the
2688 object files for the Ada units of the program.
2690 @node Mixed Language Programming
2691 @section Mixed Language Programming
2692 @cindex Mixed Language Programming
2694 @noindent
2695 This section describes how to develop a mixed-language program,
2696 specifically one that comprises units in both Ada and C.
2698 @menu
2699 * Interfacing to C::
2700 * Calling Conventions::
2701 @end menu
2703 @node Interfacing to C
2704 @subsection Interfacing to C
2705 @noindent
2706 Interfacing Ada with a foreign language such as C involves using
2707 compiler directives to import and/or export entity definitions in each
2708 language---using @code{extern} statements in C, for instance, and the
2709 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.  For
2710 a full treatment of these topics, read Appendix B, section 1 of the Ada
2711 95 Language Reference Manual.
2713 There are two ways to build a program using GNAT that contains some Ada
2714 sources and some foreign language sources, depending on whether or not
2715 the main subprogram is written in Ada.  Here is a source example with
2716 the main subprogram in Ada:
2718 @smallexample
2719 /* file1.c */
2720 #include <stdio.h>
2722 void print_num (int num)
2724   printf ("num is %d.\n", num);
2725   return;
2728 /* file2.c */
2730 /* num_from_Ada is declared in my_main.adb */
2731 extern int num_from_Ada;
2733 int get_num (void)
2735   return num_from_Ada;
2737 @end smallexample
2739 @smallexample @c ada
2740 --  my_main.adb
2741 procedure My_Main is
2743    --  Declare then export an Integer entity called num_from_Ada
2744    My_Num : Integer := 10;
2745    pragma Export (C, My_Num, "num_from_Ada");
2747    --  Declare an Ada function spec for Get_Num, then use
2748    --  C function get_num for the implementation.
2749    function Get_Num return Integer;
2750    pragma Import (C, Get_Num, "get_num");
2752    --  Declare an Ada procedure spec for Print_Num, then use
2753    --  C function print_num for the implementation.
2754    procedure Print_Num (Num : Integer);
2755    pragma Import (C, Print_Num, "print_num");
2757 begin
2758    Print_Num (Get_Num);
2759 end My_Main;
2760 @end smallexample
2762 @enumerate
2763 @item
2764 To build this example, first compile the foreign language files to
2765 generate object files:
2766 @smallexample
2767 gcc -c file1.c
2768 gcc -c file2.c
2769 @end smallexample
2771 @item
2772 Then, compile the Ada units to produce a set of object files and ALI
2773 files:
2774 @smallexample
2775 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2776 @end smallexample
2778 @item
2779 Run the Ada binder on the Ada main program:
2780 @smallexample
2781 gnatbind my_main.ali
2782 @end smallexample
2784 @item
2785 Link the Ada main program, the Ada objects and the other language
2786 objects:
2787 @smallexample
2788 gnatlink my_main.ali file1.o file2.o
2789 @end smallexample
2790 @end enumerate
2792 The last three steps can be grouped in a single command:
2793 @smallexample
2794 gnatmake my_main.adb -largs file1.o file2.o
2795 @end smallexample
2797 @cindex Binder output file
2798 @noindent
2799 If the main program is in a language other than Ada, then you may have
2800 more than one entry point into the Ada subsystem. You must use a special
2801 binder option to generate callable routines that initialize and
2802 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2803 Calls to the initialization and finalization routines must be inserted
2804 in the main program, or some other appropriate point in the code. The
2805 call to initialize the Ada units must occur before the first Ada
2806 subprogram is called, and the call to finalize the Ada units must occur
2807 after the last Ada subprogram returns. The binder will place the
2808 initialization and finalization subprograms into the
2809 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2810 sources.  To illustrate, we have the following example:
2812 @smallexample
2813 /* main.c */
2814 extern void adainit (void);
2815 extern void adafinal (void);
2816 extern int add (int, int);
2817 extern int sub (int, int);
2819 int main (int argc, char *argv[])
2821   int a = 21, b = 7;
2823   adainit();
2825   /* Should print "21 + 7 = 28" */
2826   printf ("%d + %d = %d\n", a, b, add (a, b));
2827   /* Should print "21 - 7 = 14" */
2828   printf ("%d - %d = %d\n", a, b, sub (a, b));
2830   adafinal();
2832 @end smallexample
2834 @smallexample @c ada
2835 --  unit1.ads
2836 package Unit1 is
2837    function Add (A, B : Integer) return Integer;
2838    pragma Export (C, Add, "add");
2839 end Unit1;
2841 --  unit1.adb
2842 package body Unit1 is
2843    function Add (A, B : Integer) return Integer is
2844    begin
2845       return A + B;
2846    end Add;
2847 end Unit1;
2849 --  unit2.ads
2850 package Unit2 is
2851    function Sub (A, B : Integer) return Integer;
2852    pragma Export (C, Sub, "sub");
2853 end Unit2;
2855 --  unit2.adb
2856 package body Unit2 is
2857    function Sub (A, B : Integer) return Integer is
2858    begin
2859       return A - B;
2860    end Sub;
2861 end Unit2;
2862 @end smallexample
2864 @enumerate
2865 @item
2866 The build procedure for this application is similar to the last
2867 example's.  First, compile the foreign language files to generate object
2868 files:
2869 @smallexample
2870 gcc -c main.c
2871 @end smallexample
2873 @item
2874 Next, compile the Ada units to produce a set of object files and ALI
2875 files:
2876 @smallexample
2877 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2878 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2879 @end smallexample
2881 @item
2882 Run the Ada binder on every generated ALI file.  Make sure to use the
2883 @option{-n} option to specify a foreign main program:
2884 @smallexample
2885 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2886 @end smallexample
2888 @item
2889 Link the Ada main program, the Ada objects and the foreign language
2890 objects. You need only list the last ALI file here:
2891 @smallexample
2892 gnatlink unit2.ali main.o -o exec_file
2893 @end smallexample
2895 This procedure yields a binary executable called @file{exec_file}.
2896 @end enumerate
2898 @node Calling Conventions
2899 @subsection Calling Conventions
2900 @cindex Foreign Languages
2901 @cindex Calling Conventions
2902 GNAT follows standard calling sequence conventions and will thus interface
2903 to any other language that also follows these conventions. The following
2904 Convention identifiers are recognized by GNAT:
2906 @table @code
2907 @cindex Interfacing to Ada
2908 @cindex Other Ada compilers
2909 @cindex Convention Ada
2910 @item Ada
2911 This indicates that the standard Ada calling sequence will be
2912 used and all Ada data items may be passed without any limitations in the
2913 case where GNAT is used to generate both the caller and callee. It is also
2914 possible to mix GNAT generated code and code generated by another Ada
2915 compiler. In this case, the data types should be restricted to simple
2916 cases, including primitive types. Whether complex data types can be passed
2917 depends on the situation. Probably it is safe to pass simple arrays, such
2918 as arrays of integers or floats. Records may or may not work, depending
2919 on whether both compilers lay them out identically. Complex structures
2920 involving variant records, access parameters, tasks, or protected types,
2921 are unlikely to be able to be passed.
2923 Note that in the case of GNAT running
2924 on a platform that supports DEC Ada 83, a higher degree of compatibility
2925 can be guaranteed, and in particular records are layed out in an identical
2926 manner in the two compilers. Note also that if output from two different
2927 compilers is mixed, the program is responsible for dealing with elaboration
2928 issues. Probably the safest approach is to write the main program in the
2929 version of Ada other than GNAT, so that it takes care of its own elaboration
2930 requirements, and then call the GNAT-generated adainit procedure to ensure
2931 elaboration of the GNAT components. Consult the documentation of the other
2932 Ada compiler for further details on elaboration.
2934 However, it is not possible to mix the tasking run time of GNAT and
2935 DEC Ada 83, All the tasking operations must either be entirely within
2936 GNAT compiled sections of the program, or entirely within DEC Ada 83
2937 compiled sections of the program.
2939 @cindex Interfacing to Assembly
2940 @cindex Convention Assembler
2941 @item Assembler
2942 Specifies assembler as the convention. In practice this has the
2943 same effect as convention Ada (but is not equivalent in the sense of being
2944 considered the same convention).
2946 @cindex Convention Asm
2947 @findex Asm
2948 @item Asm
2949 Equivalent to Assembler.
2951 @cindex Interfacing to COBOL
2952 @cindex Convention COBOL
2953 @findex COBOL
2954 @item COBOL
2955 Data will be passed according to the conventions described
2956 in section B.4 of the Ada 95 Reference Manual.
2958 @findex C
2959 @cindex Interfacing to C
2960 @cindex Convention C
2961 @item C
2962 Data will be passed according to the conventions described
2963 in section B.3 of the Ada 95 Reference Manual.
2965 @findex C varargs function
2966 @cindex Intefacing to C varargs function
2967 @cindex varargs function intefacs
2968 @item C varargs function
2969 In C, @code{varargs} allows a function to take a variable number of
2970 arguments. There is no direct equivalent in this to Ada. One
2971 approach that can be used is to create a C wrapper for each
2972 different profile and then interface to this C wrapper. For
2973 example, to print an @code{int} value using @code{printf},
2974 create a C function @code{printfi} that takes two arguments, a
2975 pointer to a string and an int, and calls @code{printf}.
2976 Then in the Ada program, use pragma @code{Import} to
2977 interface to printfi.
2979 It may work on some platforms to directly interface to
2980 a @code{varargs} function by providing a specific Ada profile
2981 for a a particular call. However, this does not work on
2982 all platforms, since there is no guarantee that the
2983 calling sequence for a two argument normal C function
2984 is the same as for calling a @code{varargs} C function with
2985 the same two arguments.
2987 @cindex Convention Default
2988 @findex Default
2989 @item Default
2990 Equivalent to C.
2992 @cindex Convention External
2993 @findex External
2994 @item External
2995 Equivalent to C.
2997 @findex C++
2998 @cindex Interfacing to C++
2999 @cindex Convention C++
3000 @item CPP
3001 This stands for C++. For most purposes this is identical to C.
3002 See the separate description of the specialized GNAT pragmas relating to
3003 C++ interfacing for further details.
3005 @findex Fortran
3006 @cindex Interfacing to Fortran
3007 @cindex Convention Fortran
3008 @item Fortran
3009 Data will be passed according to the conventions described
3010 in section B.5 of the Ada 95 Reference Manual.
3012 @item Intrinsic
3013 This applies to an intrinsic operation, as defined in the Ada 95
3014 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
3015 this means that the body of the subprogram is provided by the compiler itself,
3016 usually by means of an efficient code sequence, and that the user does not
3017 supply an explicit body for it. In an application program, the pragma can
3018 only be applied to the following two sets of names, which the GNAT compiler
3019 recognizes.
3021 @itemize @bullet
3022 @item
3023 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
3024 Arithmetic.  The corresponding subprogram declaration must have
3025 two formal parameters. The
3026 first one must be a signed integer type or a modular type with a binary
3027 modulus, and the second parameter must be of type Natural.
3028 The return type must be the same as the type of the first argument. The size
3029 of this type can only be 8, 16, 32, or 64.
3030 @item binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
3031 The corresponding operator declaration must have parameters and result type
3032 that have the same root numeric type (for example, all three are long_float
3033 types). This simplifies the definition of operations that use type checking
3034 to perform dimensional checks:
3036 @smallexample @c ada
3037 type Distance is new Long_Float;
3038 type Time     is new Long_Float;
3039 type Velocity is new Long_Float;
3040 function "/" (D : Distance; T : Time)
3041   return Velocity;
3042 pragma Import (Intrinsic, "/");
3043 @end smallexample
3045 @noindent
3046 This common idiom is often programmed with a generic definition and an
3047 explicit body. The pragma makes it simpler to introduce such declarations.
3048 It incurs no overhead in compilation time or code size, because it is
3049 implemented as a single machine instruction.
3050 @end itemize
3051 @noindent
3053 @ifset unw
3054 @findex Stdcall
3055 @cindex Convention Stdcall
3056 @item Stdcall
3057 This is relevant only to NT/Win95 implementations of GNAT,
3058 and specifies that the Stdcall calling sequence will be used, as defined
3059 by the NT API.
3061 @findex DLL
3062 @cindex Convention DLL
3063 @item DLL
3064 This is equivalent to Stdcall.
3066 @findex Win32
3067 @cindex Convention Win32
3068 @item Win32
3069 This is equivalent to Stdcall.
3070 @end ifset
3072 @findex Stubbed
3073 @cindex Convention Stubbed
3074 @item Stubbed
3075 This is a special convention that indicates that the compiler
3076 should provide a stub body that raises @code{Program_Error}.
3077 @end table
3079 @noindent
3080 GNAT additionally provides a useful pragma @code{Convention_Identifier}
3081 that can be used to parametrize conventions and allow additional synonyms
3082 to be specified. For example if you have legacy code in which the convention
3083 identifier Fortran77 was used for Fortran, you can use the configuration
3084 pragma:
3086 @smallexample @c ada
3087 pragma Convention_Identifier (Fortran77, Fortran);
3088 @end smallexample
3090 @noindent
3091 And from now on the identifier Fortran77 may be used as a convention
3092 identifier (for example in an @code{Import} pragma) with the same
3093 meaning as Fortran.
3095 @node Building Mixed Ada & C++ Programs
3096 @section Building Mixed Ada & C++ Programs
3098 @noindent
3099 A programmer inexperienced with mixed-language development may find that
3100 building an application containing both Ada and C++ code can be a
3101 challenge. As a matter of fact, interfacing with C++ has not been
3102 standardized in the Ada 95 Reference Manual due to the immaturity of --
3103 and lack of standards for -- C++ at the time. This section gives a few
3104 hints that should make this task easier. The first section addresses
3105 the differences regarding interfacing with C. The second section
3106 looks into the delicate problem of linking the complete application from
3107 its Ada and C++ parts. The last section gives some hints on how the GNAT
3108 run time can be adapted in order to allow inter-language dispatching
3109 with a new C++ compiler.
3111 @menu
3112 * Interfacing to C++::
3113 * Linking a Mixed C++ & Ada Program::
3114 * A Simple Example::
3115 * Adapting the Run Time to a New C++ Compiler::
3116 @end menu
3118 @node Interfacing to C++
3119 @subsection Interfacing to C++
3121 @noindent
3122 GNAT supports interfacing with C++ compilers generating code that is
3123 compatible with the standard Application Binary Interface of the given
3124 platform.
3126 @noindent
3127 Interfacing can be done at 3 levels: simple data, subprograms, and
3128 classes. In the first two cases, GNAT offers a specific @var{Convention
3129 CPP} that behaves exactly like @var{Convention C}. Usually, C++ mangles
3130 the names of subprograms, and currently, GNAT does not provide any help
3131 to solve the demangling problem. This problem can be addressed in two
3132 ways:
3133 @itemize @bullet
3134 @item
3135 by modifying the C++ code in order to force a C convention using
3136 the @code{extern "C"} syntax.
3138 @item
3139 by figuring out the mangled name and use it as the Link_Name argument of
3140 the pragma import.
3141 @end itemize
3143 @noindent
3144 Interfacing at the class level can be achieved by using the GNAT specific
3145 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
3146 Reference Manual for additional information.
3148 @node Linking a Mixed C++ & Ada Program
3149 @subsection Linking a Mixed C++ & Ada Program
3151 @noindent
3152 Usually the linker of the C++ development system must be used to link
3153 mixed applications because most C++ systems will resolve elaboration
3154 issues (such as calling constructors on global class instances)
3155 transparently during the link phase. GNAT has been adapted to ease the
3156 use of a foreign linker for the last phase. Three cases can be
3157 considered:
3158 @enumerate
3160 @item
3161 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
3162 The C++ linker can simply be called by using the C++ specific driver
3163 called @code{c++}. Note that this setup is not very common because it
3164 may involve recompiling the whole GCC tree from sources, which makes it
3165 harder to upgrade the compilation system for one language without
3166 destabilizing the other.
3168 @smallexample
3169 $ c++ -c file1.C
3170 $ c++ -c file2.C
3171 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
3172 @end smallexample
3174 @item
3175 Using GNAT and G++ from two different GCC installations: If both
3176 compilers are on the PATH, the previous method may be used. It is
3177 important to note that environment variables such as C_INCLUDE_PATH,
3178 GCC_EXEC_PREFIX, BINUTILS_ROOT, and GCC_ROOT will affect both compilers
3179 at the same time and may make one of the two compilers operate
3180 improperly if set during invocation of the wrong compiler.  It is also
3181 very important that the linker uses the proper @file{libgcc.a} GCC
3182 library -- that is, the one from the C++ compiler installation. The
3183 implicit link command as suggested in the gnatmake command from the
3184 former example can be replaced by an explicit link command with the
3185 full-verbosity option in order to verify which library is used:
3186 @smallexample
3187 $ gnatbind ada_unit
3188 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
3189 @end smallexample
3190 If there is a problem due to interfering environment variables, it can
3191 be worked around by using an intermediate script. The following example
3192 shows the proper script to use when GNAT has not been installed at its
3193 default location and g++ has been installed at its default location:
3195 @smallexample
3196 $ cat ./my_script
3197 #!/bin/sh
3198 unset BINUTILS_ROOT
3199 unset GCC_ROOT
3200 c++ $*
3201 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
3202 @end smallexample
3204 @item
3205 Using a non-GNU C++ compiler: The commands previously described can be
3206 used to insure that the C++ linker is used. Nonetheless, you need to add
3207 the path to libgcc explicitly, since some libraries needed by GNAT are
3208 located in this directory:
3210 @smallexample
3211 $ cat ./my_script
3212 #!/bin/sh
3213 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
3214 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
3215 @end smallexample
3217 Where CC is the name of the non-GNU C++ compiler.
3219 @end enumerate
3221 @node A Simple Example
3222 @subsection  A Simple Example
3223 @noindent
3224 The following example, provided as part of the GNAT examples, shows how
3225 to achieve procedural interfacing between Ada and C++ in both
3226 directions. The C++ class A has two methods. The first method is exported
3227 to Ada by the means of an extern C wrapper function. The second method
3228 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
3229 a limited record with a layout comparable to the C++ class. The Ada
3230 subprogram, in turn, calls the C++ method. So, starting from the C++
3231 main program, the process passes back and forth between the two
3232 languages.
3234 @noindent
3235 Here are the compilation commands:
3236 @smallexample
3237 $ gnatmake -c simple_cpp_interface
3238 $ c++ -c cpp_main.C
3239 $ c++ -c ex7.C
3240 $ gnatbind -n simple_cpp_interface
3241 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
3242       -lstdc++ ex7.o cpp_main.o
3243 @end smallexample
3245 @noindent
3246 Here are the corresponding sources:
3247 @smallexample
3249 //cpp_main.C
3251 #include "ex7.h"
3253 extern "C" @{
3254   void adainit (void);
3255   void adafinal (void);
3256   void method1 (A *t);
3259 void method1 (A *t)
3261   t->method1 ();
3264 int main ()
3266   A obj;
3267   adainit ();
3268   obj.method2 (3030);
3269   adafinal ();
3272 //ex7.h
3274 class Origin @{
3275  public:
3276   int o_value;
3278 class A : public Origin @{
3279  public:
3280   void method1 (void);
3281   void method2 (int v);
3282   A();
3283   int   a_value;
3286 //ex7.C
3288 #include "ex7.h"
3289 #include <stdio.h>
3291 extern "C" @{ void ada_method2 (A *t, int v);@}
3293 void A::method1 (void)
3295   a_value = 2020;
3296   printf ("in A::method1, a_value = %d \n",a_value);
3300 void A::method2 (int v)
3302    ada_method2 (this, v);
3303    printf ("in A::method2, a_value = %d \n",a_value);
3307 A::A(void)
3309    a_value = 1010;
3310   printf ("in A::A, a_value = %d \n",a_value);
3313 -- Ada sources
3314 @b{package} @b{body} Simple_Cpp_Interface @b{is}
3316    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
3317    @b{begin}
3318       Method1 (This);
3319       This.A_Value := V;
3320    @b{end} Ada_Method2;
3322 @b{end} Simple_Cpp_Interface;
3324 @b{package} Simple_Cpp_Interface @b{is}
3325    @b{type} A @b{is} @b{limited}
3326       @b{record}
3327          O_Value : Integer;
3328          A_Value : Integer;
3329       @b{end} @b{record};
3330    @b{pragma} Convention (C, A);
3332    @b{procedure} Method1 (This : @b{in} @b{out} A);
3333    @b{pragma} Import (C, Method1);
3335    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
3336    @b{pragma} Export (C, Ada_Method2);
3338 @b{end} Simple_Cpp_Interface;
3339 @end smallexample
3341 @node Adapting the Run Time to a New C++ Compiler
3342 @subsection Adapting the Run Time to a New C++ Compiler
3343 @noindent
3344 GNAT offers the capability to derive Ada 95 tagged types directly from
3345 preexisting C++ classes and . See ``Interfacing with C++'' in the
3346 @cite{GNAT Reference Manual}. The mechanism used by GNAT for achieving
3347 such a goal
3348 has been made user configurable through a GNAT library unit
3349 @code{Interfaces.CPP}. The default version of this file is adapted to
3350 the GNU C++ compiler. Internal knowledge of the virtual
3351 table layout used by the new C++ compiler is needed to configure
3352 properly this unit. The Interface of this unit is known by the compiler
3353 and cannot be changed except for the value of the constants defining the
3354 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
3355 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
3356 of this unit for more details.
3358 @node Comparison between GNAT and C/C++ Compilation Models
3359 @section Comparison between GNAT and C/C++ Compilation Models
3361 @noindent
3362 The GNAT model of compilation is close to the C and C++ models. You can
3363 think of Ada specs as corresponding to header files in C. As in C, you
3364 don't need to compile specs; they are compiled when they are used. The
3365 Ada @code{with} is similar in effect to the @code{#include} of a C
3366 header.
3368 One notable difference is that, in Ada, you may compile specs separately
3369 to check them for semantic and syntactic accuracy. This is not always
3370 possible with C headers because they are fragments of programs that have
3371 less specific syntactic or semantic rules.
3373 The other major difference is the requirement for running the binder,
3374 which performs two important functions. First, it checks for
3375 consistency. In C or C++, the only defense against assembling
3376 inconsistent programs lies outside the compiler, in a makefile, for
3377 example. The binder satisfies the Ada requirement that it be impossible
3378 to construct an inconsistent program when the compiler is used in normal
3379 mode.
3381 @cindex Elaboration order control
3382 The other important function of the binder is to deal with elaboration
3383 issues. There are also elaboration issues in C++ that are handled
3384 automatically. This automatic handling has the advantage of being
3385 simpler to use, but the C++ programmer has no control over elaboration.
3386 Where @code{gnatbind} might complain there was no valid order of
3387 elaboration, a C++ compiler would simply construct a program that
3388 malfunctioned at run time.
3390 @node Comparison between GNAT and Conventional Ada Library Models
3391 @section Comparison between GNAT and Conventional Ada Library Models
3393 @noindent
3394 This section is intended to be useful to Ada programmers who have
3395 previously used an Ada compiler implementing the traditional Ada library
3396 model, as described in the Ada 95 Language Reference Manual. If you
3397 have not used such a system, please go on to the next section.
3399 @cindex GNAT library
3400 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
3401 source files themselves acts as the library. Compiling Ada programs does
3402 not generate any centralized information, but rather an object file and
3403 a ALI file, which are of interest only to the binder and linker.
3404 In a traditional system, the compiler reads information not only from
3405 the source file being compiled, but also from the centralized library.
3406 This means that the effect of a compilation depends on what has been
3407 previously compiled. In particular:
3409 @itemize @bullet
3410 @item
3411 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3412 to the version of the unit most recently compiled into the library.
3414 @item
3415 Inlining is effective only if the necessary body has already been
3416 compiled into the library.
3418 @item
3419 Compiling a unit may obsolete other units in the library.
3420 @end itemize
3422 @noindent
3423 In GNAT, compiling one unit never affects the compilation of any other
3424 units because the compiler reads only source files. Only changes to source
3425 files can affect the results of a compilation. In particular:
3427 @itemize @bullet
3428 @item
3429 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3430 to the source version of the unit that is currently accessible to the
3431 compiler.
3433 @item
3434 @cindex Inlining
3435 Inlining requires the appropriate source files for the package or
3436 subprogram bodies to be available to the compiler. Inlining is always
3437 effective, independent of the order in which units are complied.
3439 @item
3440 Compiling a unit never affects any other compilations. The editing of
3441 sources may cause previous compilations to be out of date if they
3442 depended on the source file being modified.
3443 @end itemize
3445 @noindent
3446 The most important result of these differences is that order of compilation
3447 is never significant in GNAT. There is no situation in which one is
3448 required to do one compilation before another. What shows up as order of
3449 compilation requirements in the traditional Ada library becomes, in
3450 GNAT, simple source dependencies; in other words, there is only a set
3451 of rules saying what source files must be present when a file is
3452 compiled.
3454 @ifset vms
3455 @node Placement of temporary files
3456 @section Placement of temporary files
3457 @cindex Temporary files (user control over placement)
3459 @noindent
3460 GNAT creates temporary files in the directory designated by the environment
3461 variable @env{TMPDIR}.
3462 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3463 for detailed information on how environment variables are resolved.
3464 For most users the easiest way to make use of this feature is to simply
3465 define @env{TMPDIR} as a job level logical name).
3466 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3467 for compiler temporary files, then you can include something like the
3468 following command in your @file{LOGIN.COM} file:
3470 @smallexample
3471 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3472 @end smallexample
3474 @noindent
3475 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3476 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3477 designated by @env{TEMP}.
3478 If none of these environment variables are defined then GNAT uses the
3479 directory designated by the logical name @code{SYS$SCRATCH:}
3480 (by default the user's home directory). If all else fails
3481 GNAT uses the current directory for temporary files.
3482 @end ifset
3484 @c *************************
3485 @node Compiling Using gcc
3486 @chapter Compiling Using @command{gcc}
3488 @noindent
3489 This chapter discusses how to compile Ada programs using the @command{gcc}
3490 command. It also describes the set of switches
3491 that can be used to control the behavior of the compiler.
3492 @menu
3493 * Compiling Programs::
3494 * Switches for gcc::
3495 * Search Paths and the Run-Time Library (RTL)::
3496 * Order of Compilation Issues::
3497 * Examples::
3498 @end menu
3500 @node Compiling Programs
3501 @section Compiling Programs
3503 @noindent
3504 The first step in creating an executable program is to compile the units
3505 of the program using the @command{gcc} command. You must compile the
3506 following files:
3508 @itemize @bullet
3509 @item
3510 the body file (@file{.adb}) for a library level subprogram or generic
3511 subprogram
3513 @item
3514 the spec file (@file{.ads}) for a library level package or generic
3515 package that has no body
3517 @item
3518 the body file (@file{.adb}) for a library level package
3519 or generic package that has a body
3521 @end itemize
3523 @noindent
3524 You need @emph{not} compile the following files
3526 @itemize @bullet
3528 @item
3529 the spec of a library unit which has a body
3531 @item
3532 subunits
3533 @end itemize
3535 @noindent
3536 because they are compiled as part of compiling related units. GNAT
3537 package specs
3538 when the corresponding body is compiled, and subunits when the parent is
3539 compiled.
3541 @cindex cannot generate code
3542 If you attempt to compile any of these files, you will get one of the
3543 following error messages (where fff is the name of the file you compiled):
3545 @smallexample
3546 cannot generate code for file @var{fff} (package spec)
3547 to check package spec, use -gnatc
3549 cannot generate code for file @var{fff} (missing subunits)
3550 to check parent unit, use -gnatc
3552 cannot generate code for file @var{fff} (subprogram spec)
3553 to check subprogram spec, use -gnatc
3555 cannot generate code for file @var{fff} (subunit)
3556 to check subunit, use -gnatc
3557 @end smallexample
3559 @noindent
3560 As indicated by the above error messages, if you want to submit
3561 one of these files to the compiler to check for correct semantics
3562 without generating code, then use the @option{-gnatc} switch.
3564 The basic command for compiling a file containing an Ada unit is
3566 @smallexample
3567 $ gcc -c [@var{switches}] @file{file name}
3568 @end smallexample
3570 @noindent
3571 where @var{file name} is the name of the Ada file (usually
3572 having an extension
3573 @file{.ads} for a spec or @file{.adb} for a body).
3574 @ifclear vms
3575 You specify the
3576 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3577 @end ifclear
3578 The result of a successful compilation is an object file, which has the
3579 same name as the source file but an extension of @file{.o} and an Ada
3580 Library Information (ALI) file, which also has the same name as the
3581 source file, but with @file{.ali} as the extension. GNAT creates these
3582 two output files in the current directory, but you may specify a source
3583 file in any directory using an absolute or relative path specification
3584 containing the directory information.
3586 @findex gnat1
3587 @command{gcc} is actually a driver program that looks at the extensions of
3588 the file arguments and loads the appropriate compiler. For example, the
3589 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3590 These programs are in directories known to the driver program (in some
3591 configurations via environment variables you set), but need not be in
3592 your path. The @command{gcc} driver also calls the assembler and any other
3593 utilities needed to complete the generation of the required object
3594 files.
3596 It is possible to supply several file names on the same @command{gcc}
3597 command. This causes @command{gcc} to call the appropriate compiler for
3598 each file. For example, the following command lists three separate
3599 files to be compiled:
3601 @smallexample
3602 $ gcc -c x.adb y.adb z.c
3603 @end smallexample
3605 @noindent
3606 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3607 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3608 The compiler generates three object files @file{x.o}, @file{y.o} and
3609 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3610 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3611 @ifclear vms
3612 except for
3613 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3614 @end ifclear
3616 @node Switches for gcc
3617 @section Switches for @command{gcc}
3619 @noindent
3620 The @command{gcc} command accepts switches that control the
3621 compilation process. These switches are fully described in this section.
3622 First we briefly list all the switches, in alphabetical order, then we
3623 describe the switches in more detail in functionally grouped sections.
3625 @menu
3626 * Output and Error Message Control::
3627 * Warning Message Control::
3628 * Debugging and Assertion Control::
3629 * Validity Checking::
3630 * Style Checking::
3631 * Run-Time Checks::
3632 * Stack Overflow Checking::
3633 * Using gcc for Syntax Checking::
3634 * Using gcc for Semantic Checking::
3635 * Compiling Ada 83 Programs::
3636 * Character Set Control::
3637 * File Naming Control::
3638 * Subprogram Inlining Control::
3639 * Auxiliary Output Control::
3640 * Debugging Control::
3641 * Exception Handling Control::
3642 * Units to Sources Mapping Files::
3643 * Integrated Preprocessing::
3644 * Code Generation Control::
3645 @ifset vms
3646 * Return Codes::
3647 @end ifset
3648 @end menu
3650 @table @option
3651 @c !sort!
3652 @ifclear vms
3653 @cindex @option{-b} (@command{gcc})
3654 @item -b @var{target}
3655 Compile your program to run on @var{target}, which is the name of a
3656 system configuration. You must have a GNAT cross-compiler built if
3657 @var{target} is not the same as your host system.
3659 @item -B@var{dir}
3660 @cindex @option{-B} (@command{gcc})
3661 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3662 from @var{dir} instead of the default location. Only use this switch
3663 when multiple versions of the GNAT compiler are available. See the
3664 @command{gcc} manual page for further details. You would normally use the
3665 @option{-b} or @option{-V} switch instead.
3667 @item -c
3668 @cindex @option{-c} (@command{gcc})
3669 Compile. Always use this switch when compiling Ada programs.
3671 Note: for some other languages when using @command{gcc}, notably in
3672 the case of C and C++, it is possible to use
3673 use @command{gcc} without a @option{-c} switch to
3674 compile and link in one step. In the case of GNAT, you
3675 cannot use this approach, because the binder must be run
3676 and @command{gcc} cannot be used to run the GNAT binder.
3677 @end ifclear
3679 @item -fno-inline
3680 @cindex @option{-fno-inline} (@command{gcc})
3681 Suppresses all back-end inlining, even if other optimization or inlining
3682 switches are set.
3683 This includes suppression of inlining that results
3684 from the use of the pragma @code{Inline_Always}.
3685 See also @option{-gnatn} and @option{-gnatN}.
3687 @item -fno-strict-aliasing
3688 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3689 Causes the compiler to avoid assumptions regarding non-aliasing
3690 of objects of different types. See
3691 @ref{Optimization and Strict Aliasing} for details.
3693 @item -fstack-check
3694 @cindex @option{-fstack-check} (@command{gcc})
3695 Activates stack checking.
3696 See @ref{Stack Overflow Checking} for details of the use of this option.
3698 @item ^-g^/DEBUG^
3699 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3700 Generate debugging information. This information is stored in the object
3701 file and copied from there to the final executable file by the linker,
3702 where it can be read by the debugger. You must use the
3703 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3705 @item -gnat83
3706 @cindex @option{-gnat83} (@command{gcc})
3707 Enforce Ada 83 restrictions.
3709 @item -gnata
3710 @cindex @option{-gnata} (@command{gcc})
3711 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3712 activated.
3714 @item -gnatA
3715 @cindex @option{-gnatA} (@command{gcc})
3716 Avoid processing @file{gnat.adc}. If a gnat.adc file is present,
3717 it will be ignored.
3719 @item -gnatb
3720 @cindex @option{-gnatb} (@command{gcc})
3721 Generate brief messages to @file{stderr} even if verbose mode set.
3723 @item -gnatc
3724 @cindex @option{-gnatc} (@command{gcc})
3725 Check syntax and semantics only (no code generation attempted).
3727 @item -gnatd
3728 @cindex @option{-gnatd} (@command{gcc})
3729 Specify debug options for the compiler. The string of characters after
3730 the @option{-gnatd} specify the specific debug options. The possible
3731 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3732 compiler source file @file{debug.adb} for details of the implemented
3733 debug options. Certain debug options are relevant to applications
3734 programmers, and these are documented at appropriate points in this
3735 users guide.
3737 @item -gnatD
3738 @cindex @option{-gnatD} (@command{gcc})
3739 Create expanded source files for source level debugging. This switch
3740 also suppress generation of cross-reference information
3741 (see @option{-gnatx}).
3743 @item -gnatec=@var{path}
3744 @cindex @option{-gnatec} (@command{gcc})
3745 Specify a configuration pragma file
3746 @ifclear vms
3747 (the equal sign is optional)
3748 @end ifclear
3749 (@pxref{The Configuration Pragmas Files}).
3751 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
3752 @cindex @option{-gnateD} (@command{gcc})
3753 Defines a symbol, associated with value, for preprocessing.
3754 (@pxref{Integrated Preprocessing}).
3756 @item -gnatef
3757 @cindex @option{-gnatef} (@command{gcc})
3758 Display full source path name in brief error messages.
3760 @item -gnatem=@var{path}
3761 @cindex @option{-gnatem} (@command{gcc})
3762 Specify a mapping file
3763 @ifclear vms
3764 (the equal sign is optional)
3765 @end ifclear
3766 (@pxref{Units to Sources Mapping Files}).
3768 @item -gnatep=@var{file}
3769 @cindex @option{-gnatep} (@command{gcc})
3770 Specify a preprocessing data file
3771 @ifclear vms
3772 (the equal sign is optional)
3773 @end ifclear
3774 (@pxref{Integrated Preprocessing}).
3776 @item -gnatE
3777 @cindex @option{-gnatE} (@command{gcc})
3778 Full dynamic elaboration checks.
3780 @item -gnatf
3781 @cindex @option{-gnatf} (@command{gcc})
3782 Full errors. Multiple errors per line, all undefined references, do not
3783 attempt to suppress cascaded errors.
3785 @item -gnatF
3786 @cindex @option{-gnatF} (@command{gcc})
3787 Externals names are folded to all uppercase.
3789 @item -gnatg
3790 @cindex @option{-gnatg} (@command{gcc})
3791 Internal GNAT implementation mode. This should not be used for
3792 applications programs, it is intended only for use by the compiler
3793 and its run-time library. For documentation, see the GNAT sources.
3794 Note that @option{-gnatg} implies @option{-gnatwu} so that warnings
3795 are generated on unreferenced entities, and all warnings are treated
3796 as errors.
3798 @item -gnatG
3799 @cindex @option{-gnatG} (@command{gcc})
3800 List generated expanded code in source form.
3802 @item ^-gnath^/HELP^
3803 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3804 Output usage information. The output is written to @file{stdout}.
3806 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3807 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3808 Identifier character set
3809 @ifclear vms
3810 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3811 @end ifclear
3812 @ifset vms
3813 For details of the possible selections for @var{c},
3814 see @ref{Character Set Control}.
3815 @end ifset
3817 @item -gnatk=@var{n}
3818 @cindex @option{-gnatk} (@command{gcc})
3819 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3821 @item -gnatl
3822 @cindex @option{-gnatl} (@command{gcc})
3823 Output full source listing with embedded error messages.
3825 @item -gnatL
3826 @cindex @option{-gnatL} (@command{gcc})
3827 Use the longjmp/setjmp method for exception handling
3829 @item -gnatm=@var{n}
3830 @cindex @option{-gnatm} (@command{gcc})
3831 Limit number of detected error or warning messages to @var{n}
3832 where @var{n} is in the range 1..999_999. The default setting if
3833 no switch is given is 9999. Compilation is terminated if this
3834 limit is exceeded.
3836 @item -gnatn
3837 @cindex @option{-gnatn} (@command{gcc})
3838 Activate inlining for subprograms for which
3839 pragma @code{inline} is specified. This inlining is performed
3840 by the GCC back-end.
3842 @item -gnatN
3843 @cindex @option{-gnatN} (@command{gcc})
3844 Activate front end inlining for subprograms for which
3845 pragma @code{Inline} is specified. This inlining is performed
3846 by the front end and will be visible in the
3847 @option{-gnatG} output.
3848 In some cases, this has proved more effective than the back end
3849 inlining resulting from the use of
3850 @option{-gnatn}.
3851 Note that
3852 @option{-gnatN} automatically implies
3853 @option{-gnatn} so it is not necessary
3854 to specify both options. There are a few cases that the back-end inlining
3855 catches that cannot be dealt with in the front-end.
3857 @item -gnato
3858 @cindex @option{-gnato} (@command{gcc})
3859 Enable numeric overflow checking (which is not normally enabled by
3860 default). Not that division by zero is a separate check that is not
3861 controlled by this switch (division by zero checking is on by default).
3863 @item -gnatp
3864 @cindex @option{-gnatp} (@command{gcc})
3865 Suppress all checks.
3867 @item -gnatP
3868 @cindex @option{-gnatP} (@command{gcc})
3869 Enable polling. This is required on some systems (notably Windows NT) to
3870 obtain asynchronous abort and asynchronous transfer of control capability.
3871 See the description of pragma Polling in the GNAT Reference Manual for
3872 full details.
3874 @item -gnatq
3875 @cindex @option{-gnatq} (@command{gcc})
3876 Don't quit; try semantics, even if parse errors.
3878 @item -gnatQ
3879 @cindex @option{-gnatQ} (@command{gcc})
3880 Don't quit; generate @file{ALI} and tree files even if illegalities.
3882 @item ^-gnatR[0/1/2/3[s]]^/REPRESENTATION_INFO^
3883 @cindex @option{-gnatR} (@command{gcc})
3884 Output representation information for declared types and objects.
3886 @item -gnats
3887 @cindex @option{-gnats} (@command{gcc})
3888 Syntax check only.
3890 @item -gnatS
3891 @cindex @option{-gnatS} (@command{gcc})
3892 Print package Standard.
3894 @item -gnatt
3895 @cindex @option{-gnatt} (@command{gcc})
3896 Generate tree output file.
3898 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
3899 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
3900 All compiler tables start at @var{nnn} times usual starting size.
3902 @item -gnatu
3903 @cindex @option{-gnatu} (@command{gcc})
3904 List units for this compilation.
3906 @item -gnatU
3907 @cindex @option{-gnatU} (@command{gcc})
3908 Tag all error messages with the unique string ``error:''
3910 @item -gnatv
3911 @cindex @option{-gnatv} (@command{gcc})
3912 Verbose mode. Full error output with source lines to @file{stdout}.
3914 @item -gnatV
3915 @cindex @option{-gnatV} (@command{gcc})
3916 Control level of validity checking. See separate section describing
3917 this feature.
3919 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}[,...])^
3920 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
3921 Warning mode where
3922 ^@var{xxx} is a string of option letters that^the list of options^ denotes
3923 the exact warnings that
3924 are enabled or disabled (@pxref{Warning Message Control}).
3926 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3927 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
3928 Wide character encoding method
3929 @ifclear vms
3930 (@var{e}=n/h/u/s/e/8).
3931 @end ifclear
3932 @ifset vms
3933 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3934 @end ifset
3936 @item -gnatx
3937 @cindex @option{-gnatx} (@command{gcc})
3938 Suppress generation of cross-reference information.
3940 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3941 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
3942 Enable built-in style checks (@pxref{Style Checking}).
3944 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3945 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
3946 Distribution stub generation and compilation
3947 @ifclear vms
3948 (@var{m}=r/c for receiver/caller stubs).
3949 @end ifclear
3950 @ifset vms
3951 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3952 to be generated and compiled).
3953 @end ifset
3955 @item -gnatZ
3956 Use the zero cost method for exception handling
3958 @item ^-I^/SEARCH=^@var{dir}
3959 @cindex @option{^-I^/SEARCH^} (@command{gcc})
3960 @cindex RTL
3961 Direct GNAT to search the @var{dir} directory for source files needed by
3962 the current compilation
3963 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3965 @item ^-I-^/NOCURRENT_DIRECTORY^
3966 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
3967 @cindex RTL
3968 Except for the source file named in the command line, do not look for source
3969 files in the directory containing the source file named in the command line
3970 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3972 @ifclear vms
3973 @item -mbig-switch
3974 @cindex @option{-mbig-switch} (@command{gcc})
3975 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
3976 This standard gcc switch causes the compiler to use larger offsets in its
3977 jump table representation for @code{case} statements.
3978 This may result in less efficient code, but is sometimes necessary
3979 (for example on HP-UX targets)
3980 @cindex HP-UX and @option{-mbig-switch} option
3981 in order to compile large and/or nested @code{case} statements.
3983 @item -o @var{file}
3984 @cindex @option{-o} (@command{gcc})
3985 This switch is used in @command{gcc} to redirect the generated object file
3986 and its associated ALI file. Beware of this switch with GNAT, because it may
3987 cause the object file and ALI file to have different names which in turn
3988 may confuse the binder and the linker.
3989 @end ifclear
3991 @item -nostdinc
3992 @cindex @option{-nostdinc} (@command{gcc})
3993 Inhibit the search of the default location for the GNAT Run Time
3994 Library (RTL) source files.
3996 @item -nostdlib
3997 @cindex @option{-nostdlib} (@command{gcc})
3998 Inhibit the search of the default location for the GNAT Run Time
3999 Library (RTL) ALI files.
4001 @ifclear vms
4002 @item -O[@var{n}]
4003 @cindex @option{-O} (@command{gcc})
4004 @var{n} controls the optimization level.
4006 @table @asis
4007 @item n = 0
4008 No optimization, the default setting if no @option{-O} appears
4010 @item n = 1
4011 Normal optimization, the default if you specify @option{-O} without
4012 an operand.
4014 @item n = 2
4015 Extensive optimization
4017 @item n = 3
4018 Extensive optimization with automatic inlining of subprograms not
4019 specified by pragma @code{Inline}. This applies only to
4020 inlining within a unit. For details on control of inlining
4021 see @ref{Subprogram Inlining Control}.
4022 @end table
4023 @end ifclear
4025 @ifset vms
4026 @item  /NOOPTIMIZE
4027 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4028 Equivalent to @option{/OPTIMIZE=NONE}.
4029 This is the default behavior in the absence of an @option{/OPTMIZE}
4030 qualifier.
4032 @item /OPTIMIZE[=(keyword[,...])]
4033 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4034 Selects the level of optimization for your program. The supported
4035 keywords are as follows:
4036 @table @code
4037 @item   ALL
4038 Perform most optimizations, including those that
4039 are expensive.
4040 This is the default if the @option{/OPTMIZE} qualifier is supplied
4041 without keyword options.
4043 @item   NONE
4044 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4046 @item SOME
4047 Perform some optimizations, but omit ones that are costly.
4049 @item   DEVELOPMENT
4050 Same as @code{SOME}.
4052 @item   INLINING
4053 Full optimization, and also attempt automatic inlining of small
4054 subprograms within a unit even when pragma @code{Inline}
4055 is not specified (@pxref{Inlining of Subprograms}).
4057 @item   UNROLL_LOOPS
4058 Try to unroll loops. This keyword may be specified together with
4059 any keyword above other than @code{NONE}. Loop unrolling
4060 usually, but not always, improves the performance of programs.
4061 @end table
4062 @end ifset
4064 @ifclear vms
4065 @item -pass-exit-codes
4066 @cindex @option{-pass-exit-codes} (@command{gcc})
4067 Catch exit codes from the compiler and use the most meaningful as
4068 exit status.
4069 @end ifclear
4071 @item --RTS=@var{rts-path}
4072 @cindex @option{--RTS} (@command{gcc})
4073 Specifies the default location of the runtime library. Same meaning as the
4074 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4076 @item ^-S^/ASM^
4077 @cindex @option{^-S^/ASM^} (@command{gcc})
4078 ^Used in place of @option{-c} to^Used to^
4079 cause the assembler source file to be
4080 generated, using @file{^.s^.S^} as the extension,
4081 instead of the object file.
4082 This may be useful if you need to examine the generated assembly code.
4084 @item ^-fverbose-asm^/VERBOSE_ASM^
4085 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4086 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4087 to cause the generated assembly code file to be annotated with variable
4088 names, making it significantly easier to follow.
4090 @item ^-v^/VERBOSE^
4091 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4092 Show commands generated by the @command{gcc} driver. Normally used only for
4093 debugging purposes or if you need to be sure what version of the
4094 compiler you are executing.
4096 @ifclear vms
4097 @item -V @var{ver}
4098 @cindex @option{-V} (@command{gcc})
4099 Execute @var{ver} version of the compiler. This is the @command{gcc}
4100 version, not the GNAT version.
4101 @end ifclear
4103 @end table
4105 @ifclear vms
4106 You may combine a sequence of GNAT switches into a single switch. For
4107 example, the combined switch
4109 @cindex Combining GNAT switches
4110 @smallexample
4111 -gnatofi3
4112 @end smallexample
4114 @noindent
4115 is equivalent to specifying the following sequence of switches:
4117 @smallexample
4118 -gnato -gnatf -gnati3
4119 @end smallexample
4120 @end ifclear
4122 @c NEED TO CHECK THIS FOR VMS
4124 @noindent
4125 The following restrictions apply to the combination of switches
4126 in this manner:
4128 @itemize @bullet
4129 @item
4130 The switch @option{-gnatc} if combined with other switches must come
4131 first in the string.
4133 @item
4134 The switch @option{-gnats} if combined with other switches must come
4135 first in the string.
4137 @item
4138 The switches
4139 @option{^-gnatz^/DISTRIBUTION_STUBS^}, @option{-gnatzc}, and @option{-gnatzr}
4140 may not be combined with any other switches.
4142 @ifclear vms
4143 @item
4144 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4145 switch), then all further characters in the switch are interpreted
4146 as style modifiers (see description of @option{-gnaty}).
4148 @item
4149 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4150 switch), then all further characters in the switch are interpreted
4151 as debug flags (see description of @option{-gnatd}).
4153 @item
4154 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4155 switch), then all further characters in the switch are interpreted
4156 as warning mode modifiers (see description of @option{-gnatw}).
4158 @item
4159 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4160 switch), then all further characters in the switch are interpreted
4161 as validity checking options (see description of @option{-gnatV}).
4162 @end ifclear
4163 @end itemize
4165 @node Output and Error Message Control
4166 @subsection Output and Error Message Control
4167 @findex stderr
4169 @noindent
4170 The standard default format for error messages is called ``brief format''.
4171 Brief format messages are written to @file{stderr} (the standard error
4172 file) and have the following form:
4174 @smallexample
4175 e.adb:3:04: Incorrect spelling of keyword "function"
4176 e.adb:4:20: ";" should be "is"
4177 @end smallexample
4179 @noindent
4180 The first integer after the file name is the line number in the file,
4181 and the second integer is the column number within the line.
4182 @code{glide} can parse the error messages
4183 and point to the referenced character.
4184 The following switches provide control over the error message
4185 format:
4187 @table @option
4188 @c !sort!
4189 @item -gnatv
4190 @cindex @option{-gnatv} (@command{gcc})
4191 @findex stdout
4192 @ifclear vms
4193 The v stands for verbose.
4194 @end ifclear
4195 The effect of this setting is to write long-format error
4196 messages to @file{stdout} (the standard output file.
4197 The same program compiled with the
4198 @option{-gnatv} switch would generate:
4200 @smallexample
4201 @cartouche
4202 3. funcion X (Q : Integer)
4203    |
4204 >>> Incorrect spelling of keyword "function"
4205 4. return Integer;
4206                  |
4207 >>> ";" should be "is"
4208 @end cartouche
4209 @end smallexample
4211 @noindent
4212 The vertical bar indicates the location of the error, and the @samp{>>>}
4213 prefix can be used to search for error messages. When this switch is
4214 used the only source lines output are those with errors.
4216 @item -gnatl
4217 @cindex @option{-gnatl} (@command{gcc})
4218 @ifclear vms
4219 The @code{l} stands for list.
4220 @end ifclear
4221 This switch causes a full listing of
4222 the file to be generated. The output might look as follows:
4224 @smallexample
4225 @cartouche
4226  1. procedure E is
4227  2.    V : Integer;
4228  3.    funcion X (Q : Integer)
4229        |
4230     >>> Incorrect spelling of keyword "function"
4231  4.     return Integer;
4232                       |
4233     >>> ";" should be "is"
4234  5.    begin
4235  6.       return Q + Q;
4236  7.    end;
4237  8. begin
4238  9.    V := X + X;
4239 10.end E;
4240 @end cartouche
4241 @end smallexample
4243 @noindent
4244 @findex stderr
4245 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4246 standard output is redirected, a brief summary is written to
4247 @file{stderr} (standard error) giving the number of error messages and
4248 warning messages generated.
4250 @item -gnatU
4251 @cindex @option{-gnatU} (@command{gcc})
4252 This switch forces all error messages to be preceded by the unique
4253 string ``error:''. This means that error messages take a few more
4254 characters in space, but allows easy searching for and identification
4255 of error messages.
4257 @item -gnatb
4258 @cindex @option{-gnatb} (@command{gcc})
4259 @ifclear vms
4260 The @code{b} stands for brief.
4261 @end ifclear
4262 This switch causes GNAT to generate the
4263 brief format error messages to @file{stderr} (the standard error
4264 file) as well as the verbose
4265 format message or full listing (which as usual is written to
4266 @file{stdout} (the standard output file).
4268 @item -gnatm^^=^@var{n}
4269 @cindex @option{-gnatm} (@command{gcc})
4270 @ifclear vms
4271 The @code{m} stands for maximum.
4272 @end ifclear
4273 @var{n} is a decimal integer in the
4274 range of 1 to 999 and limits the number of error messages to be
4275 generated. For example, using @option{-gnatm2} might yield
4277 @smallexample
4278 e.adb:3:04: Incorrect spelling of keyword "function"
4279 e.adb:5:35: missing ".."
4280 fatal error: maximum errors reached
4281 compilation abandoned
4282 @end smallexample
4284 @item -gnatf
4285 @cindex @option{-gnatf} (@command{gcc})
4286 @cindex Error messages, suppressing
4287 @ifclear vms
4288 The @code{f} stands for full.
4289 @end ifclear
4290 Normally, the compiler suppresses error messages that are likely to be
4291 redundant. This switch causes all error
4292 messages to be generated. In particular, in the case of
4293 references to undefined variables. If a given variable is referenced
4294 several times, the normal format of messages is
4295 @smallexample
4296 e.adb:7:07: "V" is undefined (more references follow)
4297 @end smallexample
4299 @noindent
4300 where the parenthetical comment warns that there are additional
4301 references to the variable @code{V}. Compiling the same program with the
4302 @option{-gnatf} switch yields
4304 @smallexample
4305 e.adb:7:07: "V" is undefined
4306 e.adb:8:07: "V" is undefined
4307 e.adb:8:12: "V" is undefined
4308 e.adb:8:16: "V" is undefined
4309 e.adb:9:07: "V" is undefined
4310 e.adb:9:12: "V" is undefined
4311 @end smallexample
4313 @noindent
4314 The @option{-gnatf} switch also generates additional information for
4315 some error messages.  Some examples are:
4317 @itemize @bullet
4318 @item
4319 Full details on entities not available in high integrity mode
4320 @item
4321 Details on possibly non-portable unchecked conversion
4322 @item
4323 List possible interpretations for ambiguous calls
4324 @item
4325 Additional details on incorrect parameters
4326 @end itemize
4328 @item -gnatq
4329 @cindex @option{-gnatq} (@command{gcc})
4330 @ifclear vms
4331 The @code{q} stands for quit (really ``don't quit'').
4332 @end ifclear
4333 In normal operation mode, the compiler first parses the program and
4334 determines if there are any syntax errors. If there are, appropriate
4335 error messages are generated and compilation is immediately terminated.
4336 This switch tells
4337 GNAT to continue with semantic analysis even if syntax errors have been
4338 found. This may enable the detection of more errors in a single run. On
4339 the other hand, the semantic analyzer is more likely to encounter some
4340 internal fatal error when given a syntactically invalid tree.
4342 @item -gnatQ
4343 @cindex @option{-gnatQ} (@command{gcc})
4344 In normal operation mode, the @file{ALI} file is not generated if any
4345 illegalities are detected in the program. The use of @option{-gnatQ} forces
4346 generation of the @file{ALI} file. This file is marked as being in
4347 error, so it cannot be used for binding purposes, but it does contain
4348 reasonably complete cross-reference information, and thus may be useful
4349 for use by tools (e.g. semantic browsing tools or integrated development
4350 environments) that are driven from the @file{ALI} file. This switch
4351 implies @option{-gnatq}, since the semantic phase must be run to get a
4352 meaningful ALI file.
4354 In addition, if @option{-gnatt} is also specified, then the tree file is
4355 generated even if there are illegalities. It may be useful in this case
4356 to also specify @option{-gnatq} to ensure that full semantic processing
4357 occurs. The resulting tree file can be processed by ASIS, for the purpose
4358 of providing partial information about illegal units, but if the error
4359 causes the tree to be badly malformed, then ASIS may crash during the
4360 analysis.
4362 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4363 being in error, @command{gnatmake} will attempt to recompile the source when it
4364 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4366 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4367 since ALI files are never generated if @option{-gnats} is set.
4369 @end table
4371 @node Warning Message Control
4372 @subsection Warning Message Control
4373 @cindex Warning messages
4374 @noindent
4375 In addition to error messages, which correspond to illegalities as defined
4376 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
4377 situations.
4379 First, the compiler considers some constructs suspicious and generates a
4380 warning message to alert you to a possible error. Second, if the
4381 compiler detects a situation that is sure to raise an exception at
4382 run time, it generates a warning message. The following shows an example
4383 of warning messages:
4384 @smallexample
4385 e.adb:4:24: warning: creation of object may raise Storage_Error
4386 e.adb:10:17: warning: static value out of range
4387 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4388 @end smallexample
4390 @noindent
4391 GNAT considers a large number of situations as appropriate
4392 for the generation of warning messages. As always, warnings are not
4393 definite indications of errors. For example, if you do an out-of-range
4394 assignment with the deliberate intention of raising a
4395 @code{Constraint_Error} exception, then the warning that may be
4396 issued does not indicate an error. Some of the situations for which GNAT
4397 issues warnings (at least some of the time) are given in the following
4398 list. This list is not complete, and new warnings are often added to
4399 subsequent versions of GNAT. The list is intended to give a general idea
4400 of the kinds of warnings that are generated.
4402 @itemize @bullet
4403 @item
4404 Possible infinitely recursive calls
4406 @item
4407 Out-of-range values being assigned
4409 @item
4410 Possible order of elaboration problems
4412 @item
4413 Unreachable code
4415 @item
4416 Fixed-point type declarations with a null range
4418 @item
4419 Direct_IO or Sequential_IO instantiated with a type that has access values
4421 @item
4422 Variables that are never assigned a value
4424 @item
4425 Variables that are referenced before being initialized
4427 @item
4428 Task entries with no corresponding @code{accept} statement
4430 @item
4431 Duplicate accepts for the same task entry in a @code{select}
4433 @item
4434 Objects that take too much storage
4436 @item
4437 Unchecked conversion between types of differing sizes
4439 @item
4440 Missing @code{return} statement along some execution path in a function
4442 @item
4443 Incorrect (unrecognized) pragmas
4445 @item
4446 Incorrect external names
4448 @item
4449 Allocation from empty storage pool
4451 @item
4452 Potentially blocking operation in protected type
4454 @item
4455 Suspicious parenthesization of expressions
4457 @item
4458 Mismatching bounds in an aggregate
4460 @item
4461 Attempt to return local value by reference
4463 @item
4464 Premature instantiation of a generic body
4466 @item
4467 Attempt to pack aliased components
4469 @item
4470 Out of bounds array subscripts
4472 @item
4473 Wrong length on string assignment
4475 @item
4476 Violations of style rules if style checking is enabled
4478 @item
4479 Unused @code{with} clauses
4481 @item
4482 @code{Bit_Order} usage that does not have any effect
4484 @item
4485 @code{Standard.Duration} used to resolve universal fixed expression
4487 @item
4488 Dereference of possibly null value
4490 @item
4491 Declaration that is likely to cause storage error
4493 @item
4494 Internal GNAT unit @code{with}'ed by application unit
4496 @item
4497 Values known to be out of range at compile time
4499 @item
4500 Unreferenced labels and variables
4502 @item
4503 Address overlays that could clobber memory
4505 @item
4506 Unexpected initialization when address clause present
4508 @item
4509 Bad alignment for address clause
4511 @item
4512 Useless type conversions
4514 @item
4515 Redundant assignment statements and other redundant constructs
4517 @item
4518 Useless exception handlers
4520 @item
4521 Accidental hiding of name by child unit
4523 @item
4524 Access before elaboration detected at compile time
4526 @item
4527 A range in a @code{for} loop that is known to be null or might be null
4529 @end itemize
4531 @noindent
4532 The following switches are available to control the handling of
4533 warning messages:
4535 @table @option
4536 @c !sort!
4537 @item -gnatwa
4538 @emph{Activate all optional errors.}
4539 @cindex @option{-gnatwa} (@command{gcc})
4540 This switch activates most optional warning messages, see remaining list
4541 in this section for details on optional warning messages that can be
4542 individually controlled.  The warnings that are not turned on by this
4543 switch are
4544 @option{-gnatwd} (implicit dereferencing),
4545 @option{-gnatwh} (hiding),
4546 and @option{-gnatwl} (elaboration warnings).
4547 All other optional warnings are turned on.
4549 @item -gnatwA
4550 @emph{Suppress all optional errors.}
4551 @cindex @option{-gnatwA} (@command{gcc})
4552 This switch suppresses all optional warning messages, see remaining list
4553 in this section for details on optional warning messages that can be
4554 individually controlled.
4556 @item -gnatwc
4557 @emph{Activate warnings on conditionals.}
4558 @cindex @option{-gnatwc} (@command{gcc})
4559 @cindex Conditionals, constant
4560 This switch activates warnings for conditional expressions used in
4561 tests that are known to be True or False at compile time. The default
4562 is that such warnings are not generated.
4563 Note that this warning does
4564 not get issued for the use of boolean variables or constants whose
4565 values are known at compile time, since this is a standard technique
4566 for conditional compilation in Ada, and this would generate too many
4567 ``false positive'' warnings.
4568 This warning can also be turned on using @option{-gnatwa}.
4570 @item -gnatwC
4571 @emph{Suppress warnings on conditionals.}
4572 @cindex @option{-gnatwC} (@command{gcc})
4573 This switch suppresses warnings for conditional expressions used in
4574 tests that are known to be True or False at compile time.
4576 @item -gnatwd
4577 @emph{Activate warnings on implicit dereferencing.}
4578 @cindex @option{-gnatwd} (@command{gcc})
4579 If this switch is set, then the use of a prefix of an access type
4580 in an indexed component, slice, or selected component without an
4581 explicit @code{.all} will generate a warning. With this warning
4582 enabled, access checks occur only at points where an explicit
4583 @code{.all} appears in the source code (assuming no warnings are
4584 generated as a result of this switch). The default is that such
4585 warnings are not generated.
4586 Note that @option{-gnatwa} does not affect the setting of
4587 this warning option.
4589 @item -gnatwD
4590 @emph{Suppress warnings on implicit dereferencing.}
4591 @cindex @option{-gnatwD} (@command{gcc})
4592 @cindex Implicit dereferencing
4593 @cindex Dereferencing, implicit
4594 This switch suppresses warnings for implicit dereferences in
4595 indexed components, slices, and selected components.
4597 @item -gnatwe
4598 @emph{Treat warnings as errors.}
4599 @cindex @option{-gnatwe} (@command{gcc})
4600 @cindex Warnings, treat as error
4601 This switch causes warning messages to be treated as errors.
4602 The warning string still appears, but the warning messages are counted
4603 as errors, and prevent the generation of an object file.
4605 @item -gnatwf
4606 @emph{Activate warnings on unreferenced formals.}
4607 @cindex @option{-gnatwf} (@command{gcc})
4608 @cindex Formals, unreferenced
4609 This switch causes a warning to be generated if a formal parameter
4610 is not referenced in the body of the subprogram. This warning can
4611 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
4613 @item -gnatwF
4614 @emph{Suppress warnings on unreferenced formals.}
4615 @cindex @option{-gnatwF} (@command{gcc})
4616 This switch suppresses warnings for unreferenced formal
4617 parameters. Note that the
4618 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4619 effect of warning on unreferenced entities other than subprogram
4620 formals.
4622 @item -gnatwg
4623 @emph{Activate warnings on unrecognized pragmas.}
4624 @cindex @option{-gnatwg} (@command{gcc})
4625 @cindex Pragmas, unrecognized
4626 This switch causes a warning to be generated if an unrecognized
4627 pragma is encountered. Apart from issuing this warning, the
4628 pragma is ignored and has no effect. This warning can
4629 also be turned on using @option{-gnatwa}. The default
4630 is that such warnings are issued (satisfying the Ada Reference
4631 Manual requirement that such warnings appear).
4633 @item -gnatwG
4634 @emph{Suppress warnings on unrecognized pragmas.}
4635 @cindex @option{-gnatwG} (@command{gcc})
4636 This switch suppresses warnings for unrecognized pragmas.
4638 @item -gnatwh
4639 @emph{Activate warnings on hiding.}
4640 @cindex @option{-gnatwh} (@command{gcc})
4641 @cindex Hiding of Declarations
4642 This switch activates warnings on hiding declarations.
4643 A declaration is considered hiding
4644 if it is for a non-overloadable entity, and it declares an entity with the
4645 same name as some other entity that is directly or use-visible. The default
4646 is that such warnings are not generated.
4647 Note that @option{-gnatwa} does not affect the setting of this warning option.
4649 @item -gnatwH
4650 @emph{Suppress warnings on hiding.}
4651 @cindex @option{-gnatwH} (@command{gcc})
4652 This switch suppresses warnings on hiding declarations.
4654 @item -gnatwi
4655 @emph{Activate warnings on implementation units.}
4656 @cindex @option{-gnatwi} (@command{gcc})
4657 This switch activates warnings for a @code{with} of an internal GNAT
4658 implementation unit, defined as any unit from the @code{Ada},
4659 @code{Interfaces}, @code{GNAT},
4660 ^^@code{DEC},^ or @code{System}
4661 hierarchies that is not
4662 documented in either the Ada Reference Manual or the GNAT
4663 Programmer's Reference Manual. Such units are intended only
4664 for internal implementation purposes and should not be @code{with}'ed
4665 by user programs. The default is that such warnings are generated
4666 This warning can also be turned on using @option{-gnatwa}.
4668 @item -gnatwI
4669 @emph{Disable warnings on implementation units.}
4670 @cindex @option{-gnatwI} (@command{gcc})
4671 This switch disables warnings for a @code{with} of an internal GNAT
4672 implementation unit.
4674 @item -gnatwj
4675 @emph{Activate warnings on obsolescent features (Annex J).}
4676 @cindex @option{-gnatwj} (@command{gcc})
4677 @cindex Features, obsolescent
4678 @cindex Obsolescent features
4679 If this warning option is activated, then warnings are generated for
4680 calls to subprograms marked with @code{pragma Obsolescent} and
4681 for use of features in Annex J of the Ada Reference Manual. In the
4682 case of Annex J, not all features are flagged. In particular use
4683 of the renamed packages (like @code{Text_IO}) and use of package
4684 @code{ASCII} are not flagged, since these are very common and
4685 would generate many annoying positive warnings. The default is that
4686 such warnings are not generated.
4688 In addition to the above cases, warnings are also generated for
4689 GNAT features that have been provided in past versions but which
4690 have been superceded (typically by features in the new Ada standard).
4691 For example, @code{pragma Ravenscar} will be flagged since its
4692 function is replaced by @code{pragma Profile(Ravenscar)}.
4694 Note that this warning option functions differently from the
4695 restriction @code{No_Obsolescent_Features} in two respects.
4696 First, the restriction applies only to annex J features.
4697 Second, the restriction does flag uses of package @code{ASCII}.
4699 @item -gnatwJ
4700 @emph{Suppress warnings on obsolescent features (Annex J).}
4701 @cindex @option{-gnatwJ} (@command{gcc})
4702 This switch disables warnings on use of obsolescent features.
4704 @item -gnatwk
4705 @emph{Activate warnings on variables that could be constants.}
4706 @cindex @option{-gnatwk} (@command{gcc})
4707 This switch activates warnings for variables that are initialized but
4708 never modified, and then could be declared constants.
4710 @item -gnatwK
4711 @emph{Suppress warnings on variables that could be constants.}
4712 @cindex @option{-gnatwK} (@command{gcc})
4713 This switch disables warnings on variables that could be declared constants.
4715 @item -gnatwl
4716 @emph{Activate warnings for missing elaboration pragmas.}
4717 @cindex @option{-gnatwl} (@command{gcc})
4718 @cindex Elaboration, warnings
4719 This switch activates warnings on missing
4720 @code{pragma Elaborate_All} statements.
4721 See the section in this guide on elaboration checking for details on
4722 when such pragma should be used. Warnings are also generated if you
4723 are using the static mode of elaboration, and a @code{pragma Elaborate}
4724 is encountered. The default is that such warnings
4725 are not generated.
4726 This warning is not automatically turned on by the use of @option{-gnatwa}.
4728 @item -gnatwL
4729 @emph{Suppress warnings for missing elaboration pragmas.}
4730 @cindex @option{-gnatwL} (@command{gcc})
4731 This switch suppresses warnings on missing pragma Elaborate_All statements.
4732 See the section in this guide on elaboration checking for details on
4733 when such pragma should be used.
4735 @item -gnatwm
4736 @emph{Activate warnings on modified but unreferenced variables.}
4737 @cindex @option{-gnatwm} (@command{gcc})
4738 This switch activates warnings for variables that are assigned (using
4739 an initialization value or with one or more assignment statements) but
4740 whose value is never read. The warning is suppressed for volatile
4741 variables and also for variables that are renamings of other variables
4742 or for which an address clause is given.
4743 This warning can also be turned on using @option{-gnatwa}.
4745 @item -gnatwM
4746 @emph{Disable warnings on modified but unreferenced variables.}
4747 @cindex @option{-gnatwM} (@command{gcc})
4748 This switch disables warnings for variables that are assigned or
4749 initialized, but never read.
4751 @item -gnatwn
4752 @emph{Set normal warnings mode.}
4753 @cindex @option{-gnatwn} (@command{gcc})
4754 This switch sets normal warning mode, in which enabled warnings are
4755 issued and treated as warnings rather than errors. This is the default
4756 mode. the switch @option{-gnatwn} can be used to cancel the effect of
4757 an explicit @option{-gnatws} or
4758 @option{-gnatwe}. It also cancels the effect of the
4759 implicit @option{-gnatwe} that is activated by the
4760 use of @option{-gnatg}.
4762 @item -gnatwo
4763 @emph{Activate warnings on address clause overlays.}
4764 @cindex @option{-gnatwo} (@command{gcc})
4765 @cindex Address Clauses, warnings
4766 This switch activates warnings for possibly unintended initialization
4767 effects of defining address clauses that cause one variable to overlap
4768 another. The default is that such warnings are generated.
4769 This warning can also be turned on using @option{-gnatwa}.
4771 @item -gnatwO
4772 @emph{Suppress warnings on address clause overlays.}
4773 @cindex @option{-gnatwO} (@command{gcc})
4774 This switch suppresses warnings on possibly unintended initialization
4775 effects of defining address clauses that cause one variable to overlap
4776 another.
4778 @item -gnatwp
4779 @emph{Activate warnings on ineffective pragma Inlines.}
4780 @cindex @option{-gnatwp} (@command{gcc})
4781 @cindex Inlining, warnings
4782 This switch activates warnings for failure of front end inlining
4783 (activated by @option{-gnatN}) to inline a particular call. There are
4784 many reasons for not being able to inline a call, including most
4785 commonly that the call is too complex to inline.
4786 This warning can also be turned on using @option{-gnatwa}.
4788 @item -gnatwP
4789 @emph{Suppress warnings on ineffective pragma Inlines.}
4790 @cindex @option{-gnatwP} (@command{gcc})
4791 This switch suppresses warnings on ineffective pragma Inlines. If the
4792 inlining mechanism cannot inline a call, it will simply ignore the
4793 request silently.
4795 @item -gnatwr
4796 @emph{Activate warnings on redundant constructs.}
4797 @cindex @option{-gnatwr} (@command{gcc})
4798 This switch activates warnings for redundant constructs. The following
4799 is the current list of constructs regarded as redundant:
4800 This warning can also be turned on using @option{-gnatwa}.
4802 @itemize @bullet
4803 @item
4804 Assignment of an item to itself.
4805 @item
4806 Type conversion that converts an expression to its own type.
4807 @item
4808 Use of the attribute @code{Base} where @code{typ'Base} is the same
4809 as @code{typ}.
4810 @item
4811 Use of pragma @code{Pack} when all components are placed by a record
4812 representation clause.
4813 @item
4814 Exception handler containing only a reraise statement (raise with no
4815 operand) which has no effect.
4816 @item
4817 Use of the operator abs on an operand that is known at compile time
4818 to be non-negative
4819 @item
4820 Comparison of boolean expressions to an explicit True value.
4821 @end itemize
4823 @item -gnatwR
4824 @emph{Suppress warnings on redundant constructs.}
4825 @cindex @option{-gnatwR} (@command{gcc})
4826 This switch suppresses warnings for redundant constructs.
4828 @item -gnatws
4829 @emph{Suppress all warnings.}
4830 @cindex @option{-gnatws} (@command{gcc})
4831 This switch completely suppresses the
4832 output of all warning messages from the GNAT front end.
4833 Note that it does not suppress warnings from the @command{gcc} back end.
4834 To suppress these back end warnings as well, use the switch @option{-w}
4835 in addition to @option{-gnatws}.
4837 @item -gnatwu
4838 @emph{Activate warnings on unused entities.}
4839 @cindex @option{-gnatwu} (@command{gcc})
4840 This switch activates warnings to be generated for entities that
4841 are declared but not referenced, and for units that are @code{with}'ed
4842 and not
4843 referenced. In the case of packages, a warning is also generated if
4844 no entities in the package are referenced. This means that if the package
4845 is referenced but the only references are in @code{use}
4846 clauses or @code{renames}
4847 declarations, a warning is still generated. A warning is also generated
4848 for a generic package that is @code{with}'ed but never instantiated.
4849 In the case where a package or subprogram body is compiled, and there
4850 is a @code{with} on the corresponding spec
4851 that is only referenced in the body,
4852 a warning is also generated, noting that the
4853 @code{with} can be moved to the body. The default is that
4854 such warnings are not generated.
4855 This switch also activates warnings on unreferenced formals
4856 (it includes the effect of @option{-gnatwf}).
4857 This warning can also be turned on using @option{-gnatwa}.
4859 @item -gnatwU
4860 @emph{Suppress warnings on unused entities.}
4861 @cindex @option{-gnatwU} (@command{gcc})
4862 This switch suppresses warnings for unused entities and packages.
4863 It also turns off warnings on unreferenced formals (and thus includes
4864 the effect of @option{-gnatwF}).
4866 @item -gnatwv
4867 @emph{Activate warnings on unassigned variables.}
4868 @cindex @option{-gnatwv} (@command{gcc})
4869 @cindex Unassigned variable warnings
4870 This switch activates warnings for access to variables which
4871 may not be properly initialized. The default is that
4872 such warnings are generated.
4874 @item -gnatwV
4875 @emph{Suppress warnings on unassigned variables.}
4876 @cindex @option{-gnatwV} (@command{gcc})
4877 This switch suppresses warnings for access to variables which
4878 may not be properly initialized.
4880 @item -gnatwx
4881 @emph{Activate warnings on Export/Import pragmas.}
4882 @cindex @option{-gnatwx} (@command{gcc})
4883 @cindex Export/Import pragma warnings
4884 This switch activates warnings on Export/Import pragmas when
4885 the compiler detects a possible conflict between the Ada and
4886 foreign language calling sequences. For example, the use of
4887 default parameters in a convention C procedure is dubious
4888 because the C compiler cannot supply the proper default, so
4889 a warning is issued. The default is that such warnings are
4890 generated.
4892 @item -gnatwX
4893 @emph{Suppress warnings on Export/Import pragmas.}
4894 @cindex @option{-gnatwX} (@command{gcc})
4895 This switch suppresses warnings on Export/Import pragmas.
4896 The sense of this is that you are telling the compiler that
4897 you know what you are doing in writing the pragma, and it
4898 should not complain at you.
4900 @item -gnatwz
4901 @emph{Activate warnings on unchecked conversions.}
4902 @cindex @option{-gnatwz} (@command{gcc})
4903 @cindex Unchecked_Conversion warnings
4904 This switch activates warnings for unchecked conversions
4905 where the types are known at compile time to have different
4906 sizes. The default
4907 is that such warnings are generated.
4909 @item -gnatwZ
4910 @emph{Suppress warnings on unchecked conversions.}
4911 @cindex @option{-gnatwZ} (@command{gcc})
4912 This switch suppresses warnings for unchecked conversions
4913 where the types are known at compile time to have different
4914 sizes.
4916 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
4917 @cindex @option{-Wuninitialized}
4918 The warnings controlled by the @option{-gnatw} switch are generated by the
4919 front end of the compiler. In some cases, the @option{^gcc^GCC^} back end
4920 can provide additional warnings. One such useful warning is provided by
4921 @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^}. This must be used in
4922 conjunction with tunrning on optimization mode. This causes the flow
4923 analysis circuits of the back end optimizer to output additional
4924 warnings about uninitialized variables.
4926 @item ^-w^/NO_BACK_END_WARNINGS^
4927 @cindex @option{-w}
4928 This switch suppresses warnings from the @option{^gcc^GCC^} back end. It may
4929 be used in conjunction with @option{-gnatws} to ensure that all warnings
4930 are suppressed during the entire compilation process.
4932 @end table
4934 @noindent
4935 @ifclear vms
4936 A string of warning parameters can be used in the same parameter. For example:
4938 @smallexample
4939 -gnatwaLe
4940 @end smallexample
4942 @noindent
4943 will turn on all optional warnings except for elaboration pragma warnings,
4944 and also specify that warnings should be treated as errors.
4945 @end ifclear
4946 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
4948 @table @option
4949 @c !sort!
4950 @item -gnatwC
4951 @item -gnatwD
4952 @item -gnatwF
4953 @item -gnatwg
4954 @item -gnatwH
4955 @item -gnatwi
4956 @item -gnatwJ
4957 @item -gnatwK
4958 @item -gnatwL
4959 @item -gnatwM
4960 @item -gnatwn
4961 @item -gnatwo
4962 @item -gnatwP
4963 @item -gnatwR
4964 @item -gnatwU
4965 @item -gnatwv
4966 @item -gnatwz
4967 @item -gnatwx
4969 @end table
4971 @node Debugging and Assertion Control
4972 @subsection Debugging and Assertion Control
4974 @table @option
4975 @item -gnata
4976 @cindex @option{-gnata} (@command{gcc})
4977 @findex Assert
4978 @findex Debug
4979 @cindex Assertions
4981 @noindent
4982 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4983 are ignored. This switch, where @samp{a} stands for assert, causes
4984 @code{Assert} and @code{Debug} pragmas to be activated.
4986 The pragmas have the form:
4988 @smallexample
4989 @cartouche
4990    @b{pragma} Assert (@var{Boolean-expression} [,
4991                       @var{static-string-expression}])
4992    @b{pragma} Debug (@var{procedure call})
4993 @end cartouche
4994 @end smallexample
4996 @noindent
4997 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4998 If the result is @code{True}, the pragma has no effect (other than
4999 possible side effects from evaluating the expression). If the result is
5000 @code{False}, the exception @code{Assert_Failure} declared in the package
5001 @code{System.Assertions} is
5002 raised (passing @var{static-string-expression}, if present, as the
5003 message associated with the exception). If no string expression is
5004 given the default is a string giving the file name and line number
5005 of the pragma.
5007 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5008 @code{pragma Debug} may appear within a declaration sequence, allowing
5009 debugging procedures to be called between declarations.
5011 @ifset vms
5012 @item /DEBUG[=debug-level]
5013 @itemx  /NODEBUG
5014 Specifies how much debugging information is to be included in
5015 the resulting object file where 'debug-level' is one of the following:
5016 @table @code
5017 @item   TRACEBACK
5018 Include both debugger symbol records and traceback
5019 the object file.
5020 This is the default setting.
5021 @item   ALL
5022 Include both debugger symbol records and traceback in
5023 object file.
5024 @item   NONE
5025 Excludes both debugger symbol records and traceback
5026 the object file. Same as /NODEBUG.
5027 @item   SYMBOLS
5028 Includes only debugger symbol records in the object
5029 file. Note that this doesn't include traceback information.
5030 @end table
5031 @end ifset
5032 @end table
5034 @node Validity Checking
5035 @subsection Validity Checking
5036 @findex Validity Checking
5038 @noindent
5039 The Ada 95 Reference Manual has specific requirements for checking
5040 for invalid values. In particular, RM 13.9.1 requires that the
5041 evaluation of invalid values (for example from unchecked conversions),
5042 not result in erroneous execution. In GNAT, the result of such an
5043 evaluation in normal default mode is to either use the value
5044 unmodified, or to raise Constraint_Error in those cases where use
5045 of the unmodified value would cause erroneous execution. The cases
5046 where unmodified values might lead to erroneous execution are case
5047 statements (where a wild jump might result from an invalid value),
5048 and subscripts on the left hand side (where memory corruption could
5049 occur as a result of an invalid value).
5051 The @option{-gnatV^@var{x}^^} switch allows more control over the validity
5052 checking mode.
5053 @ifclear vms
5054 The @code{x} argument is a string of letters that
5055 indicate validity checks that are performed or not performed in addition
5056 to the default checks described above.
5057 @end ifclear
5058 @ifset vms
5059 The options allowed for this qualifier
5060 indicate validity checks that are performed or not performed in addition
5061 to the default checks described above.
5062 @end ifset
5064 @table @option
5065 @c !sort!
5066 @item -gnatVa
5067 @emph{All validity checks.}
5068 @cindex @option{-gnatVa} (@command{gcc})
5069 All validity checks are turned on.
5070 @ifclear vms
5071 That is, @option{-gnatVa} is
5072 equivalent to @option{gnatVcdfimorst}.
5073 @end ifclear
5075 @item -gnatVc
5076 @emph{Validity checks for copies.}
5077 @cindex @option{-gnatVc} (@command{gcc})
5078 The right hand side of assignments, and the initializing values of
5079 object declarations are validity checked.
5081 @item -gnatVd
5082 @emph{Default (RM) validity checks.}
5083 @cindex @option{-gnatVd} (@command{gcc})
5084 Some validity checks are done by default following normal Ada semantics
5085 (RM 13.9.1 (9-11)).
5086 A check is done in case statements that the expression is within the range
5087 of the subtype. If it is not, Constraint_Error is raised.
5088 For assignments to array components, a check is done that the expression used
5089 as index is within the range. If it is not, Constraint_Error is raised.
5090 Both these validity checks may be turned off using switch @option{-gnatVD}.
5091 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5092 switch @option{-gnatVd} will leave the checks turned on.
5093 Switch @option{-gnatVD} should be used only if you are sure that all such
5094 expressions have valid values. If you use this switch and invalid values
5095 are present, then the program is erroneous, and wild jumps or memory
5096 overwriting may occur.
5098 @item -gnatVf
5099 @emph{Validity checks for floating-point values.}
5100 @cindex @option{-gnatVf} (@command{gcc})
5101 In the absence of this switch, validity checking occurs only for discrete
5102 values. If @option{-gnatVf} is specified, then validity checking also applies
5103 for floating-point values, and NaN's and infinities are considered invalid,
5104 as well as out of range values for constrained types. Note that this means
5105 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
5106 in which floating-point values are checked depends on the setting of other
5107 options. For example,
5108 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5109 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5110 (the order does not matter) specifies that floating-point parameters of mode
5111 @code{in} should be validity checked.
5113 @item -gnatVi
5114 @emph{Validity checks for @code{in} mode parameters}
5115 @cindex @option{-gnatVi} (@command{gcc})
5116 Arguments for parameters of mode @code{in} are validity checked in function
5117 and procedure calls at the point of call.
5119 @item -gnatVm
5120 @emph{Validity checks for @code{in out} mode parameters.}
5121 @cindex @option{-gnatVm} (@command{gcc})
5122 Arguments for parameters of mode @code{in out} are validity checked in
5123 procedure calls at the point of call. The @code{'m'} here stands for
5124 modify, since this concerns parameters that can be modified by the call.
5125 Note that there is no specific option to test @code{out} parameters,
5126 but any reference within the subprogram will be tested in the usual
5127 manner, and if an invalid value is copied back, any reference to it
5128 will be subject to validity checking.
5130 @item -gnatVn
5131 @emph{No validity checks.}
5132 @cindex @option{-gnatVn} (@command{gcc})
5133 This switch turns off all validity checking, including the default checking
5134 for case statements and left hand side subscripts. Note that the use of
5135 the switch @option{-gnatp} suppresses all run-time checks, including
5136 validity checks, and thus implies @option{-gnatVn}. When this switch
5137 is used, it cancels any other @option{-gnatV} previously issued.
5139 @item -gnatVo
5140 @emph{Validity checks for operator and attribute operands.}
5141 @cindex @option{-gnatVo} (@command{gcc})
5142 Arguments for predefined operators and attributes are validity checked.
5143 This includes all operators in package @code{Standard},
5144 the shift operators defined as intrinsic in package @code{Interfaces}
5145 and operands for attributes such as @code{Pos}. Checks are also made
5146 on individual component values for composite comparisons.
5148 @item -gnatVp
5149 @emph{Validity checks for parameters.}
5150 @cindex @option{-gnatVp} (@command{gcc})
5151 This controls the treatment of parameters within a subprogram (as opposed
5152 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5153 of parameters on a call. If either of these call options is used, then
5154 normally an assumption is made within a subprogram that the input arguments
5155 have been validity checking at the point of call, and do not need checking
5156 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5157 is not made, and parameters are not assumed to be valid, so their validity
5158 will be checked (or rechecked) within the subprogram.
5160 @item -gnatVr
5161 @emph{Validity checks for function returns.}
5162 @cindex @option{-gnatVr} (@command{gcc})
5163 The expression in @code{return} statements in functions is validity
5164 checked.
5166 @item -gnatVs
5167 @emph{Validity checks for subscripts.}
5168 @cindex @option{-gnatVs} (@command{gcc})
5169 All subscripts expressions are checked for validity, whether they appear
5170 on the right side or left side (in default mode only left side subscripts
5171 are validity checked).
5173 @item -gnatVt
5174 @emph{Validity checks for tests.}
5175 @cindex @option{-gnatVt} (@command{gcc})
5176 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5177 statements are checked, as well as guard expressions in entry calls.
5179 @end table
5181 @noindent
5182 The @option{-gnatV} switch may be followed by
5183 ^a string of letters^a list of options^
5184 to turn on a series of validity checking options.
5185 For example,
5186 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5187 specifies that in addition to the default validity checking, copies and
5188 function return expressions are to be validity checked.
5189 In order to make it easier
5190 to specify the desired combination of effects,
5191 @ifclear vms
5192 the upper case letters @code{CDFIMORST} may
5193 be used to turn off the corresponding lower case option.
5194 @end ifclear
5195 @ifset vms
5196 the prefix @code{NO} on an option turns off the corresponding validity
5197 checking:
5198 @itemize @bullet
5199 @item @code{NOCOPIES}
5200 @item @code{NODEFAULT}
5201 @item @code{NOFLOATS}
5202 @item @code{NOIN_PARAMS}
5203 @item @code{NOMOD_PARAMS}
5204 @item @code{NOOPERANDS}
5205 @item @code{NORETURNS}
5206 @item @code{NOSUBSCRIPTS}
5207 @item @code{NOTESTS}
5208 @end itemize
5209 @end ifset
5210 Thus
5211 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
5212 turns on all validity checking options except for
5213 checking of @code{@b{in out}} procedure arguments.
5215 The specification of additional validity checking generates extra code (and
5216 in the case of @option{-gnatVa} the code expansion can be substantial.
5217 However, these additional checks can be very useful in detecting
5218 uninitialized variables, incorrect use of unchecked conversion, and other
5219 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
5220 is useful in conjunction with the extra validity checking, since this
5221 ensures that wherever possible uninitialized variables have invalid values.
5223 See also the pragma @code{Validity_Checks} which allows modification of
5224 the validity checking mode at the program source level, and also allows for
5225 temporary disabling of validity checks.
5227 @node Style Checking
5228 @subsection Style Checking
5229 @findex Style checking
5231 @noindent
5232 The @option{-gnaty^x^(option,option,...)^} switch
5233 @cindex @option{-gnaty} (@command{gcc})
5234 causes the compiler to
5235 enforce specified style rules. A limited set of style rules has been used
5236 in writing the GNAT sources themselves. This switch allows user programs
5237 to activate all or some of these checks. If the source program fails a
5238 specified style check, an appropriate warning message is given, preceded by
5239 the character sequence ``(style)''.
5240 @ifset vms
5241 @code{(option,option,...)} is a sequence of keywords
5242 @end ifset
5243 @ifclear vms
5244 The string @var{x} is a sequence of letters or digits
5245 @end ifclear
5246 indicating the particular style
5247 checks to be performed. The following checks are defined:
5249 @table @option
5250 @c !sort!
5251 @item 1-9
5252 @emph{Specify indentation level.}
5253 If a digit from 1-9 appears
5254 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
5255 then proper indentation is checked, with the digit indicating the
5256 indentation level required.
5257 The general style of required indentation is as specified by
5258 the examples in the Ada Reference Manual. Full line comments must be
5259 aligned with the @code{--} starting on a column that is a multiple of
5260 the alignment level.
5262 @item ^a^ATTRIBUTE^
5263 @emph{Check attribute casing.}
5264 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty}
5265 then attribute names, including the case of keywords such as @code{digits}
5266 used as attributes names, must be written in mixed case, that is, the
5267 initial letter and any letter following an underscore must be uppercase.
5268 All other letters must be lowercase.
5270 @item ^b^BLANKS^
5271 @emph{Blanks not allowed at statement end.}
5272 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
5273 trailing blanks are not allowed at the end of statements. The purpose of this
5274 rule, together with h (no horizontal tabs), is to enforce a canonical format
5275 for the use of blanks to separate source tokens.
5277 @item ^c^COMMENTS^
5278 @emph{Check comments.}
5279 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty}
5280 then comments must meet the following set of rules:
5282 @itemize @bullet
5284 @item
5285 The ``@code{--}'' that starts the column must either start in column one,
5286 or else at least one blank must precede this sequence.
5288 @item
5289 Comments that follow other tokens on a line must have at least one blank
5290 following the ``@code{--}'' at the start of the comment.
5292 @item
5293 Full line comments must have two blanks following the ``@code{--}'' that
5294 starts the comment, with the following exceptions.
5296 @item
5297 A line consisting only of the ``@code{--}'' characters, possibly preceded
5298 by blanks is permitted.
5300 @item
5301 A comment starting with ``@code{--x}'' where @code{x} is a special character
5302 is permitted.
5303 This allows proper processing of the output generated by specialized tools
5304 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
5305 annotation
5306 language (where ``@code{--#}'' is used). For the purposes of this rule, a
5307 special character is defined as being in one of the ASCII ranges
5308 @code{16#21#..16#2F#} or @code{16#3A#..16#3F#}.
5309 Note that this usage is not permitted
5310 in GNAT implementation units (i.e. when @option{-gnatg} is used).
5312 @item
5313 A line consisting entirely of minus signs, possibly preceded by blanks, is
5314 permitted. This allows the construction of box comments where lines of minus
5315 signs are used to form the top and bottom of the box.
5317 @item
5318 A comment that starts and ends with ``@code{--}'' is permitted as long as at
5319 least one blank follows the initial ``@code{--}''. Together with the preceding
5320 rule, this allows the construction of box comments, as shown in the following
5321 example:
5322 @smallexample
5323 ---------------------------
5324 -- This is a box comment --
5325 -- with two text lines.  --
5326 ---------------------------
5327 @end smallexample
5328 @end itemize
5330 @item ^e^END^
5331 @emph{Check end/exit labels.}
5332 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
5333 optional labels on @code{end} statements ending subprograms and on
5334 @code{exit} statements exiting named loops, are required to be present.
5336 @item ^f^VTABS^
5337 @emph{No form feeds or vertical tabs.}
5338 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
5339 neither form feeds nor vertical tab characters are permitted
5340 in the source text.
5342 @item ^h^HTABS^
5343 @emph{No horizontal tabs.}
5344 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
5345 horizontal tab characters are not permitted in the source text.
5346 Together with the b (no blanks at end of line) check, this
5347 enforces a canonical form for the use of blanks to separate
5348 source tokens.
5350 @item ^i^IF_THEN^
5351 @emph{Check if-then layout.}
5352 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
5353 then the keyword @code{then} must appear either on the same
5354 line as corresponding @code{if}, or on a line on its own, lined
5355 up under the @code{if} with at least one non-blank line in between
5356 containing all or part of the condition to be tested.
5358 @item ^k^KEYWORD^
5359 @emph{Check keyword casing.}
5360 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
5361 all keywords must be in lower case (with the exception of keywords
5362 such as @code{digits} used as attribute names to which this check
5363 does not apply).
5365 @item ^l^LAYOUT^
5366 @emph{Check layout.}
5367 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
5368 layout of statement and declaration constructs must follow the
5369 recommendations in the Ada Reference Manual, as indicated by the
5370 form of the syntax rules. For example an @code{else} keyword must
5371 be lined up with the corresponding @code{if} keyword.
5373 There are two respects in which the style rule enforced by this check
5374 option are more liberal than those in the Ada Reference Manual. First
5375 in the case of record declarations, it is permissible to put the
5376 @code{record} keyword on the same line as the @code{type} keyword, and
5377 then the @code{end} in @code{end record} must line up under @code{type}.
5378 For example, either of the following two layouts is acceptable:
5380 @smallexample @c ada
5381 @cartouche
5382 type q is record
5383    a : integer;
5384    b : integer;
5385 end record;
5387 type q is
5388    record
5389       a : integer;
5390       b : integer;
5391    end record;
5392 @end cartouche
5393 @end smallexample
5395 @noindent
5396 Second, in the case of a block statement, a permitted alternative
5397 is to put the block label on the same line as the @code{declare} or
5398 @code{begin} keyword, and then line the @code{end} keyword up under
5399 the block label. For example both the following are permitted:
5401 @smallexample @c ada
5402 @cartouche
5403 Block : declare
5404    A : Integer := 3;
5405 begin
5406    Proc (A, A);
5407 end Block;
5409 Block :
5410    declare
5411       A : Integer := 3;
5412    begin
5413       Proc (A, A);
5414    end Block;
5415 @end cartouche
5416 @end smallexample
5418 @noindent
5419 The same alternative format is allowed for loops. For example, both of
5420 the following are permitted:
5422 @smallexample @c ada
5423 @cartouche
5424 Clear : while J < 10 loop
5425    A (J) := 0;
5426 end loop Clear;
5428 Clear :
5429    while J < 10 loop
5430       A (J) := 0;
5431    end loop Clear;
5432 @end cartouche
5433 @end smallexample
5435 @item ^Lnnn^MAX_NESTING=nnn^
5436 @emph{Set maximum nesting level}
5437 If the sequence ^Lnnn^MAX_NESTING=nnn^, where nnn is a decimal number in
5438 the range 0-999, appears in the string after @option{-gnaty} then the
5439 maximum level of nesting of constructs (including subprograms, loops,
5440 blocks, packages, and conditionals) may not exceed the given value. A
5441 value of zero disconnects this style check.
5443 @item ^m^LINE_LENGTH^
5444 @emph{Check maximum line length.}
5445 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
5446 then the length of source lines must not exceed 79 characters, including
5447 any trailing blanks. The value of 79 allows convenient display on an
5448 80 character wide device or window, allowing for possible special
5449 treatment of 80 character lines. Note that this count is of raw
5450 characters in the source text. This means that a tab character counts
5451 as one character in this count and a wide character sequence counts as
5452 several characters (however many are needed in the encoding).
5454 @item ^Mnnn^MAX_LENGTH=nnn^
5455 @emph{Set maximum line length.}
5456 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
5457 the string after @option{-gnaty} then the length of lines must not exceed the
5458 given value.
5460 @item ^n^STANDARD_CASING^
5461 @emph{Check casing of entities in Standard.}
5462 If the ^letter n^word STANDARD_CASING^ appears in the string
5463 after @option{-gnaty} then any identifier from Standard must be cased
5464 to match the presentation in the Ada Reference Manual (for example,
5465 @code{Integer} and @code{ASCII.NUL}).
5467 @item ^o^ORDERED_SUBPROGRAMS^
5468 @emph{Check order of subprogram bodies.}
5469 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
5470 after @option{-gnaty} then all subprogram bodies in a given scope
5471 (e.g. a package body) must be in alphabetical order. The ordering
5472 rule uses normal Ada rules for comparing strings, ignoring casing
5473 of letters, except that if there is a trailing numeric suffix, then
5474 the value of this suffix is used in the ordering (e.g. Junk2 comes
5475 before Junk10).
5477 @item ^p^PRAGMA^
5478 @emph{Check pragma casing.}
5479 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
5480 pragma names must be written in mixed case, that is, the
5481 initial letter and any letter following an underscore must be uppercase.
5482 All other letters must be lowercase.
5484 @item ^r^REFERENCES^
5485 @emph{Check references.}
5486 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
5487 then all identifier references must be cased in the same way as the
5488 corresponding declaration. No specific casing style is imposed on
5489 identifiers. The only requirement is for consistency of references
5490 with declarations.
5492 @item ^s^SPECS^
5493 @emph{Check separate specs.}
5494 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
5495 separate declarations (``specs'') are required for subprograms (a
5496 body is not allowed to serve as its own declaration). The only
5497 exception is that parameterless library level procedures are
5498 not required to have a separate declaration. This exception covers
5499 the most frequent form of main program procedures.
5501 @item ^t^TOKEN^
5502 @emph{Check token spacing.}
5503 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
5504 the following token spacing rules are enforced:
5506 @itemize @bullet
5508 @item
5509 The keywords @code{@b{abs}} and @code{@b{not}} must be followed by a space.
5511 @item
5512 The token @code{=>} must be surrounded by spaces.
5514 @item
5515 The token @code{<>} must be preceded by a space or a left parenthesis.
5517 @item
5518 Binary operators other than @code{**} must be surrounded by spaces.
5519 There is no restriction on the layout of the @code{**} binary operator.
5521 @item
5522 Colon must be surrounded by spaces.
5524 @item
5525 Colon-equal (assignment, initialization) must be surrounded by spaces.
5527 @item
5528 Comma must be the first non-blank character on the line, or be
5529 immediately preceded by a non-blank character, and must be followed
5530 by a space.
5532 @item
5533 If the token preceding a left parenthesis ends with a letter or digit, then
5534 a space must separate the two tokens.
5536 @item
5537 A right parenthesis must either be the first non-blank character on
5538 a line, or it must be preceded by a non-blank character.
5540 @item
5541 A semicolon must not be preceded by a space, and must not be followed by
5542 a non-blank character.
5544 @item
5545 A unary plus or minus may not be followed by a space.
5547 @item
5548 A vertical bar must be surrounded by spaces.
5549 @end itemize
5551 @item ^x^XTRA_PARENS^
5552 @emph{Check extra parentheses.}
5553 Check for the use of an unnecessary extra level of parentheses (C-style)
5554 around conditions in @code{if} statements, @code{while} statements and
5555 @code{exit} statements.
5557 @end table
5559 @noindent
5560 In the above rules, appearing in column one is always permitted, that is,
5561 counts as meeting either a requirement for a required preceding space,
5562 or as meeting a requirement for no preceding space.
5564 Appearing at the end of a line is also always permitted, that is, counts
5565 as meeting either a requirement for a following space, or as meeting
5566 a requirement for no following space.
5568 @noindent
5569 If any of these style rules is violated, a message is generated giving
5570 details on the violation. The initial characters of such messages are
5571 always ``@code{(style)}''. Note that these messages are treated as warning
5572 messages, so they normally do not prevent the generation of an object
5573 file. The @option{-gnatwe} switch can be used to treat warning messages,
5574 including style messages, as fatal errors.
5576 The switch
5577 @ifclear vms
5578 @option{-gnaty} on its own (that is not
5579 followed by any letters or digits),
5580 is equivalent to @code{gnaty3abcefhiklmprst}, that is all checking
5581 options enabled with the exception of -gnatyo,
5582 @end ifclear
5583 @ifset vms
5584 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
5585 the exception of ORDERED_SUBPROGRAMS,
5586 @end ifset
5587 with an indentation level of 3. This is the standard
5588 checking option that is used for the GNAT sources.
5590 The switch
5591 @ifclear vms
5592 @option{-gnatyN}
5593 @end ifclear
5594 @ifset vms
5595 /STYLE_CHECKS=NONE
5596 @end ifset
5597 clears any previously set style checks.
5599 @node Run-Time Checks
5600 @subsection Run-Time Checks
5601 @cindex Division by zero
5602 @cindex Access before elaboration
5603 @cindex Checks, division by zero
5604 @cindex Checks, access before elaboration
5606 @noindent
5607 If you compile with the default options, GNAT will insert many run-time
5608 checks into the compiled code, including code that performs range
5609 checking against constraints, but not arithmetic overflow checking for
5610 integer operations (including division by zero) or checks for access
5611 before elaboration on subprogram calls. All other run-time checks, as
5612 required by the Ada 95 Reference Manual, are generated by default.
5613 The following @command{gcc} switches refine this default behavior:
5615 @table @option
5616 @c !sort!
5617 @item -gnatp
5618 @cindex @option{-gnatp} (@command{gcc})
5619 @cindex Suppressing checks
5620 @cindex Checks, suppressing
5621 @findex Suppress
5622 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
5623 had been present in the source. Validity checks are also suppressed (in
5624 other words @option{-gnatp} also implies @option{-gnatVn}.
5625 Use this switch to improve the performance
5626 of the code at the expense of safety in the presence of invalid data or
5627 program bugs.
5629 @item -gnato
5630 @cindex @option{-gnato} (@command{gcc})
5631 @cindex Overflow checks
5632 @cindex Check, overflow
5633 Enables overflow checking for integer operations.
5634 This causes GNAT to generate slower and larger executable
5635 programs by adding code to check for overflow (resulting in raising
5636 @code{Constraint_Error} as required by standard Ada
5637 semantics). These overflow checks correspond to situations in which
5638 the true value of the result of an operation may be outside the base
5639 range of the result type. The following example shows the distinction:
5641 @smallexample @c ada
5642 X1 : Integer := Integer'Last;
5643 X2 : Integer range 1 .. 5 := 5;
5644 X3 : Integer := Integer'Last;
5645 X4 : Integer range 1 .. 5 := 5;
5646 F  : Float := 2.0E+20;
5648 X1 := X1 + 1;
5649 X2 := X2 + 1;
5650 X3 := Integer (F);
5651 X4 := Integer (F);
5652 @end smallexample
5654 @noindent
5655 Here the first addition results in a value that is outside the base range
5656 of Integer, and hence requires an overflow check for detection of the
5657 constraint error. Thus the first assignment to @code{X1} raises a
5658 @code{Constraint_Error} exception only if @option{-gnato} is set.
5660 The second increment operation results in a violation
5661 of the explicit range constraint, and such range checks are always
5662 performed (unless specifically suppressed with a pragma @code{suppress}
5663 or the use of @option{-gnatp}).
5665 The two conversions of @code{F} both result in values that are outside
5666 the base range of type @code{Integer} and thus will raise
5667 @code{Constraint_Error} exceptions only if @option{-gnato} is used.
5668 The fact that the result of the second conversion is assigned to
5669 variable @code{X4} with a restricted range is irrelevant, since the problem
5670 is in the conversion, not the assignment.
5672 Basically the rule is that in the default mode (@option{-gnato} not
5673 used), the generated code assures that all integer variables stay
5674 within their declared ranges, or within the base range if there is
5675 no declared range. This prevents any serious problems like indexes
5676 out of range for array operations.
5678 What is not checked in default mode is an overflow that results in
5679 an in-range, but incorrect value. In the above example, the assignments
5680 to @code{X1}, @code{X2}, @code{X3} all give results that are within the
5681 range of the target variable, but the result is wrong in the sense that
5682 it is too large to be represented correctly. Typically the assignment
5683 to @code{X1} will result in wrap around to the largest negative number.
5684 The conversions of @code{F} will result in some @code{Integer} value
5685 and if that integer value is out of the @code{X4} range then the
5686 subsequent assignment would generate an exception.
5688 @findex Machine_Overflows
5689 Note that the @option{-gnato} switch does not affect the code generated
5690 for any floating-point operations; it applies only to integer
5691 semantics).
5692 For floating-point, GNAT has the @code{Machine_Overflows}
5693 attribute set to @code{False} and the normal mode of operation is to
5694 generate IEEE NaN and infinite values on overflow or invalid operations
5695 (such as dividing 0.0 by 0.0).
5697 The reason that we distinguish overflow checking from other kinds of
5698 range constraint checking is that a failure of an overflow check can
5699 generate an incorrect value, but cannot cause erroneous behavior. This
5700 is unlike the situation with a constraint check on an array subscript,
5701 where failure to perform the check can result in random memory description,
5702 or the range check on a case statement, where failure to perform the check
5703 can cause a wild jump.
5705 Note again that @option{-gnato} is off by default, so overflow checking is
5706 not performed in default mode. This means that out of the box, with the
5707 default settings, GNAT does not do all the checks expected from the
5708 language description in the Ada Reference Manual. If you want all constraint
5709 checks to be performed, as described in this Manual, then you must
5710 explicitly use the -gnato switch either on the @command{gnatmake} or
5711 @command{gcc} command.
5713 @item -gnatE
5714 @cindex @option{-gnatE} (@command{gcc})
5715 @cindex Elaboration checks
5716 @cindex Check, elaboration
5717 Enables dynamic checks for access-before-elaboration
5718 on subprogram calls and generic instantiations.
5719 For full details of the effect and use of this switch,
5720 @xref{Compiling Using gcc}.
5721 @end table
5723 @findex Unsuppress
5724 @noindent
5725 The setting of these switches only controls the default setting of the
5726 checks. You may modify them using either @code{Suppress} (to remove
5727 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
5728 the program source.
5730 @node Stack Overflow Checking
5731 @subsection Stack Overflow Checking
5732 @cindex Stack Overflow Checking
5733 @cindex -fstack-check
5735 @noindent
5736 For most operating systems, @command{gcc} does not perform stack overflow
5737 checking by default. This means that if the main environment task or
5738 some other task exceeds the available stack space, then unpredictable
5739 behavior will occur.
5741 To activate stack checking, compile all units with the gcc option
5742 @option{-fstack-check}. For example:
5744 @smallexample
5745 gcc -c -fstack-check package1.adb
5746 @end smallexample
5748 @noindent
5749 Units compiled with this option will generate extra instructions to check
5750 that any use of the stack (for procedure calls or for declaring local
5751 variables in declare blocks) do not exceed the available stack space.
5752 If the space is exceeded, then a @code{Storage_Error} exception is raised.
5754 For declared tasks, the stack size is always controlled by the size
5755 given in an applicable @code{Storage_Size} pragma (or is set to
5756 the default size if no pragma is used.
5758 For the environment task, the stack size depends on
5759 system defaults and is unknown to the compiler. The stack
5760 may even dynamically grow on some systems, precluding the
5761 normal Ada semantics for stack overflow. In the worst case,
5762 unbounded stack usage, causes unbounded stack expansion
5763 resulting in the system running out of virtual memory.
5765 The stack checking may still work correctly if a fixed
5766 size stack is allocated, but this cannot be guaranteed.
5767 To ensure that a clean exception is signalled for stack
5768 overflow, set the environment variable
5769 @code{GNAT_STACK_LIMIT} to indicate the maximum
5770 stack area that can be used, as in:
5771 @cindex GNAT_STACK_LIMIT
5773 @smallexample
5774 SET GNAT_STACK_LIMIT 1600
5775 @end smallexample
5777 @noindent
5778 The limit is given in kilobytes, so the above declaration would
5779 set the stack limit of the environment task to 1.6 megabytes.
5780 Note that the only purpose of this usage is to limit the amount
5781 of stack used by the environment task. If it is necessary to
5782 increase the amount of stack for the environment task, then this
5783 is an operating systems issue, and must be addressed with the
5784 appropriate operating systems commands.
5786 @node Using gcc for Syntax Checking
5787 @subsection Using @command{gcc} for Syntax Checking
5788 @table @option
5789 @item -gnats
5790 @cindex @option{-gnats} (@command{gcc})
5791 @ifclear vms
5793 @noindent
5794 The @code{s} stands for ``syntax''.
5795 @end ifclear
5797 Run GNAT in syntax checking only mode. For
5798 example, the command
5800 @smallexample
5801 $ gcc -c -gnats x.adb
5802 @end smallexample
5804 @noindent
5805 compiles file @file{x.adb} in syntax-check-only mode. You can check a
5806 series of files in a single command
5807 @ifclear vms
5808 , and can use wild cards to specify such a group of files.
5809 Note that you must specify the @option{-c} (compile
5810 only) flag in addition to the @option{-gnats} flag.
5811 @end ifclear
5813 You may use other switches in conjunction with @option{-gnats}. In
5814 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
5815 format of any generated error messages.
5817 When the source file is empty or contains only empty lines and/or comments,
5818 the output is a warning:
5820 @smallexample
5821 $ gcc -c -gnats -x ada toto.txt
5822 toto.txt:1:01: warning: empty file, contains no compilation units
5824 @end smallexample
5826 Otherwise, the output is simply the error messages, if any. No object file or
5827 ALI file is generated by a syntax-only compilation. Also, no units other
5828 than the one specified are accessed. For example, if a unit @code{X}
5829 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
5830 check only mode does not access the source file containing unit
5831 @code{Y}.
5833 @cindex Multiple units, syntax checking
5834 Normally, GNAT allows only a single unit in a source file. However, this
5835 restriction does not apply in syntax-check-only mode, and it is possible
5836 to check a file containing multiple compilation units concatenated
5837 together. This is primarily used by the @code{gnatchop} utility
5838 (@pxref{Renaming Files Using gnatchop}).
5839 @end table
5841 @node Using gcc for Semantic Checking
5842 @subsection Using @command{gcc} for Semantic Checking
5843 @table @option
5844 @item -gnatc
5845 @cindex @option{-gnatc} (@command{gcc})
5847 @ifclear vms
5848 @noindent
5849 The @code{c} stands for ``check''.
5850 @end ifclear
5851 Causes the compiler to operate in semantic check mode,
5852 with full checking for all illegalities specified in the
5853 Ada 95 Reference Manual, but without generation of any object code
5854 (no object file is generated).
5856 Because dependent files must be accessed, you must follow the GNAT
5857 semantic restrictions on file structuring to operate in this mode:
5859 @itemize @bullet
5860 @item
5861 The needed source files must be accessible
5862 (@pxref{Search Paths and the Run-Time Library (RTL)}).
5864 @item
5865 Each file must contain only one compilation unit.
5867 @item
5868 The file name and unit name must match (@pxref{File Naming Rules}).
5869 @end itemize
5871 The output consists of error messages as appropriate. No object file is
5872 generated. An @file{ALI} file is generated for use in the context of
5873 cross-reference tools, but this file is marked as not being suitable
5874 for binding (since no object file is generated).
5875 The checking corresponds exactly to the notion of
5876 legality in the Ada 95 Reference Manual.
5878 Any unit can be compiled in semantics-checking-only mode, including
5879 units that would not normally be compiled (subunits,
5880 and specifications where a separate body is present).
5881 @end table
5883 @node Compiling Ada 83 Programs
5884 @subsection Compiling Ada 83 Programs
5885 @table @option
5886 @cindex Ada 83 compatibility
5887 @item -gnat83
5888 @cindex @option{-gnat83} (@command{gcc})
5889 @cindex ACVC, Ada 83 tests
5891 @noindent
5892 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
5893 specify that an Ada 83 program is to be compiled in Ada 83 mode. If you specify
5894 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
5895 where this can be done easily.
5896 It is not possible to guarantee this switch does a perfect
5897 job; for example, some subtle tests, such as are
5898 found in earlier ACVC tests (and that have been removed from the ACATS suite
5899 for Ada 95), might not compile correctly.
5900 Nevertheless, this switch may be useful in some circumstances, for example
5901 where, due to contractual reasons, legacy code needs to be maintained
5902 using only Ada 83 features.
5904 With few exceptions (most notably the need to use @code{<>} on
5905 @cindex Generic formal parameters
5906 unconstrained generic formal parameters, the use of the new Ada 95
5907 reserved words, and the use of packages
5908 with optional bodies), it is not necessary to use the
5909 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
5910 exceptions, Ada 95 is upwardly compatible with Ada 83. This
5911 means that a correct Ada 83 program is usually also a correct Ada 95
5912 program.
5913 For further information, please refer to @ref{Compatibility and Porting Guide}.
5915 @end table
5917 @node Character Set Control
5918 @subsection Character Set Control
5919 @table @option
5920 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
5921 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
5923 @noindent
5924 Normally GNAT recognizes the Latin-1 character set in source program
5925 identifiers, as described in the Ada 95 Reference Manual.
5926 This switch causes
5927 GNAT to recognize alternate character sets in identifiers. @var{c} is a
5928 single character ^^or word^ indicating the character set, as follows:
5930 @table @code
5931 @item 1
5932 ISO 8859-1 (Latin-1) identifiers
5934 @item 2
5935 ISO 8859-2 (Latin-2) letters allowed in identifiers
5937 @item 3
5938 ISO 8859-3 (Latin-3) letters allowed in identifiers
5940 @item 4
5941 ISO 8859-4 (Latin-4) letters allowed in identifiers
5943 @item 5
5944 ISO 8859-5 (Cyrillic) letters allowed in identifiers
5946 @item 9
5947 ISO 8859-15 (Latin-9) letters allowed in identifiers
5949 @item ^p^PC^
5950 IBM PC letters (code page 437) allowed in identifiers
5952 @item ^8^PC850^
5953 IBM PC letters (code page 850) allowed in identifiers
5955 @item ^f^FULL_UPPER^
5956 Full upper-half codes allowed in identifiers
5958 @item ^n^NO_UPPER^
5959 No upper-half codes allowed in identifiers
5961 @item ^w^WIDE^
5962 Wide-character codes (that is, codes greater than 255)
5963 allowed in identifiers
5964 @end table
5966 @xref{Foreign Language Representation}, for full details on the
5967 implementation of these character sets.
5969 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
5970 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
5971 Specify the method of encoding for wide characters.
5972 @var{e} is one of the following:
5974 @table @code
5976 @item ^h^HEX^
5977 Hex encoding (brackets coding also recognized)
5979 @item ^u^UPPER^
5980 Upper half encoding (brackets encoding also recognized)
5982 @item ^s^SHIFT_JIS^
5983 Shift/JIS encoding (brackets encoding also recognized)
5985 @item ^e^EUC^
5986 EUC encoding (brackets encoding also recognized)
5988 @item ^8^UTF8^
5989 UTF-8 encoding (brackets encoding also recognized)
5991 @item ^b^BRACKETS^
5992 Brackets encoding only (default value)
5993 @end table
5994 For full details on the these encoding
5995 methods see @ref{Wide Character Encodings}.
5996 Note that brackets coding is always accepted, even if one of the other
5997 options is specified, so for example @option{-gnatW8} specifies that both
5998 brackets and @code{UTF-8} encodings will be recognized. The units that are
5999 with'ed directly or indirectly will be scanned using the specified
6000 representation scheme, and so if one of the non-brackets scheme is
6001 used, it must be used consistently throughout the program. However,
6002 since brackets encoding is always recognized, it may be conveniently
6003 used in standard libraries, allowing these libraries to be used with
6004 any of the available coding schemes.
6005 scheme. If no @option{-gnatW?} parameter is present, then the default
6006 representation is Brackets encoding only.
6008 Note that the wide character representation that is specified (explicitly
6009 or by default) for the main program also acts as the default encoding used
6010 for Wide_Text_IO files if not specifically overridden by a WCEM form
6011 parameter.
6013 @end table
6014 @node File Naming Control
6015 @subsection File Naming Control
6017 @table @option
6018 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
6019 @cindex @option{-gnatk} (@command{gcc})
6020 Activates file name ``krunching''. @var{n}, a decimal integer in the range
6021 1-999, indicates the maximum allowable length of a file name (not
6022 including the @file{.ads} or @file{.adb} extension). The default is not
6023 to enable file name krunching.
6025 For the source file naming rules, @xref{File Naming Rules}.
6026 @end table
6028 @node Subprogram Inlining Control
6029 @subsection Subprogram Inlining Control
6031 @table @option
6032 @c !sort!
6033 @item -gnatn
6034 @cindex @option{-gnatn} (@command{gcc})
6035 @ifclear vms
6036 The @code{n} here is intended to suggest the first syllable of the
6037 word ``inline''.
6038 @end ifclear
6039 GNAT recognizes and processes @code{Inline} pragmas. However, for the
6040 inlining to actually occur, optimization must be enabled. To enable
6041 inlining of subprograms specified by pragma @code{Inline},
6042 you must also specify this switch.
6043 In the absence of this switch, GNAT does not attempt
6044 inlining and does not need to access the bodies of
6045 subprograms for which @code{pragma Inline} is specified if they are not
6046 in the current unit.
6048 If you specify this switch the compiler will access these bodies,
6049 creating an extra source dependency for the resulting object file, and
6050 where possible, the call will be inlined.
6051 For further details on when inlining is possible
6052 see @ref{Inlining of Subprograms}.
6054 @item -gnatN
6055 @cindex @option{-gnatN} (@command{gcc})
6056 The front end inlining activated by this switch is generally more extensive,
6057 and quite often more effective than the standard @option{-gnatn} inlining mode.
6058 It will also generate additional dependencies.
6059 Note that
6060 @option{-gnatN} automatically implies @option{-gnatn} so it is not necessary
6061 to specify both options.
6062 @end table
6064 @node Auxiliary Output Control
6065 @subsection Auxiliary Output Control
6067 @table @option
6068 @item -gnatt
6069 @cindex @option{-gnatt} (@command{gcc})
6070 @cindex Writing internal trees
6071 @cindex Internal trees, writing to file
6072 Causes GNAT to write the internal tree for a unit to a file (with the
6073 extension @file{.adt}.
6074 This not normally required, but is used by separate analysis tools.
6075 Typically
6076 these tools do the necessary compilations automatically, so you should
6077 not have to specify this switch in normal operation.
6079 @item -gnatu
6080 @cindex @option{-gnatu} (@command{gcc})
6081 Print a list of units required by this compilation on @file{stdout}.
6082 The listing includes all units on which the unit being compiled depends
6083 either directly or indirectly.
6085 @ifclear vms
6086 @item -pass-exit-codes
6087 @cindex @option{-pass-exit-codes} (@command{gcc})
6088 If this switch is not used, the exit code returned by @command{gcc} when
6089 compiling multiple files indicates whether all source files have
6090 been successfully used to generate object files or not.
6092 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
6093 exit status and allows an integrated development environment to better
6094 react to a compilation failure. Those exit status are:
6096 @table @asis
6097 @item 5
6098 There was an error in at least one source file.
6099 @item 3
6100 At least one source file did not generate an object file.
6101 @item 2
6102 The compiler died unexpectedly (internal error for example).
6103 @item 0
6104 An object file has been generated for every source file.
6105 @end table
6106 @end ifclear
6107 @end table
6109 @node Debugging Control
6110 @subsection Debugging Control
6112 @table @option
6113 @c !sort!
6114 @cindex Debugging options
6115 @ifclear vms
6116 @item -gnatd@var{x}
6117 @cindex @option{-gnatd} (@command{gcc})
6118 Activate internal debugging switches. @var{x} is a letter or digit, or
6119 string of letters or digits, which specifies the type of debugging
6120 outputs desired. Normally these are used only for internal development
6121 or system debugging purposes. You can find full documentation for these
6122 switches in the body of the @code{Debug} unit in the compiler source
6123 file @file{debug.adb}.
6124 @end ifclear
6126 @item -gnatG
6127 @cindex @option{-gnatG} (@command{gcc})
6128 This switch causes the compiler to generate auxiliary output containing
6129 a pseudo-source listing of the generated expanded code. Like most Ada
6130 compilers, GNAT works by first transforming the high level Ada code into
6131 lower level constructs. For example, tasking operations are transformed
6132 into calls to the tasking run-time routines. A unique capability of GNAT
6133 is to list this expanded code in a form very close to normal Ada source.
6134 This is very useful in understanding the implications of various Ada
6135 usage on the efficiency of the generated code. There are many cases in
6136 Ada (e.g. the use of controlled types), where simple Ada statements can
6137 generate a lot of run-time code. By using @option{-gnatG} you can identify
6138 these cases, and consider whether it may be desirable to modify the coding
6139 approach to improve efficiency.
6141 The format of the output is very similar to standard Ada source, and is
6142 easily understood by an Ada programmer. The following special syntactic
6143 additions correspond to low level features used in the generated code that
6144 do not have any exact analogies in pure Ada source form. The following
6145 is a partial list of these special constructions. See the specification
6146 of package @code{Sprint} in file @file{sprint.ads} for a full list.
6148 @table @code
6149 @item new @var{xxx} [storage_pool = @var{yyy}]
6150 Shows the storage pool being used for an allocator.
6152 @item at end @var{procedure-name};
6153 Shows the finalization (cleanup) procedure for a scope.
6155 @item (if @var{expr} then @var{expr} else @var{expr})
6156 Conditional expression equivalent to the @code{x?y:z} construction in C.
6158 @item @var{target}^^^(@var{source})
6159 A conversion with floating-point truncation instead of rounding.
6161 @item @var{target}?(@var{source})
6162 A conversion that bypasses normal Ada semantic checking. In particular
6163 enumeration types and fixed-point types are treated simply as integers.
6165 @item @var{target}?^^^(@var{source})
6166 Combines the above two cases.
6168 @item @var{x} #/ @var{y}
6169 @itemx @var{x} #mod @var{y}
6170 @itemx @var{x} #* @var{y}
6171 @itemx @var{x} #rem @var{y}
6172 A division or multiplication of fixed-point values which are treated as
6173 integers without any kind of scaling.
6175 @item free @var{expr} [storage_pool = @var{xxx}]
6176 Shows the storage pool associated with a @code{free} statement.
6178 @item freeze @var{typename} [@var{actions}]
6179 Shows the point at which @var{typename} is frozen, with possible
6180 associated actions to be performed at the freeze point.
6182 @item reference @var{itype}
6183 Reference (and hence definition) to internal type @var{itype}.
6185 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
6186 Intrinsic function call.
6188 @item @var{labelname} : label
6189 Declaration of label @var{labelname}.
6191 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
6192 A multiple concatenation (same effect as @var{expr} & @var{expr} &
6193 @var{expr}, but handled more efficiently).
6195 @item [constraint_error]
6196 Raise the @code{Constraint_Error} exception.
6198 @item @var{expression}'reference
6199 A pointer to the result of evaluating @var{expression}.
6201 @item @var{target-type}!(@var{source-expression})
6202 An unchecked conversion of @var{source-expression} to @var{target-type}.
6204 @item [@var{numerator}/@var{denominator}]
6205 Used to represent internal real literals (that) have no exact
6206 representation in base 2-16 (for example, the result of compile time
6207 evaluation of the expression 1.0/27.0).
6208 @end table
6210 @item -gnatD
6211 @cindex @option{-gnatD} (@command{gcc})
6212 When used in conjunction with @option{-gnatG}, this switch causes
6213 the expanded source, as described above for
6214 @option{-gnatG} to be written to files with names
6215 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
6216 instead of to the standard ooutput file. For
6217 example, if the source file name is @file{hello.adb}, then a file
6218 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
6219 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
6220 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
6221 you to do source level debugging using the generated code which is
6222 sometimes useful for complex code, for example to find out exactly
6223 which part of a complex construction raised an exception. This switch
6224 also suppress generation of cross-reference information (see
6225 @option{-gnatx}) since otherwise the cross-reference information
6226 would refer to the @file{^.dg^.DG^} file, which would cause
6227 confusion since this is not the original source file.
6229 Note that @option{-gnatD} actually implies @option{-gnatG}
6230 automatically, so it is not necessary to give both options.
6231 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
6233 @ifclear vms
6234 @item -gnatR[0|1|2|3[s]]
6235 @cindex @option{-gnatR} (@command{gcc})
6236 This switch controls output from the compiler of a listing showing
6237 representation information for declared types and objects. For
6238 @option{-gnatR0}, no information is output (equivalent to omitting
6239 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
6240 so @option{-gnatR} with no parameter has the same effect), size and alignment
6241 information is listed for declared array and record types. For
6242 @option{-gnatR2}, size and alignment information is listed for all
6243 expression information for values that are computed at run time for
6244 variant records. These symbolic expressions have a mostly obvious
6245 format with #n being used to represent the value of the n'th
6246 discriminant. See source files @file{repinfo.ads/adb} in the
6247 @code{GNAT} sources for full details on the format of @option{-gnatR3}
6248 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
6249 the output is to a file with the name @file{^file.rep^file_REP^} where
6250 file is the name of the corresponding source file.
6251 @end ifclear
6252 @ifset vms
6253 @item /REPRESENTATION_INFO
6254 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
6255 This qualifier controls output from the compiler of a listing showing
6256 representation information for declared types and objects. For
6257 @option{/REPRESENTATION_INFO=NONE}, no information is output
6258 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
6259 @option{/REPRESENTATION_INFO} without option is equivalent to
6260 @option{/REPRESENTATION_INFO=ARRAYS}.
6261 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
6262 information is listed for declared array and record types. For
6263 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
6264 is listed for all expression information for values that are computed
6265 at run time for variant records. These symbolic expressions have a mostly
6266 obvious format with #n being used to represent the value of the n'th
6267 discriminant. See source files @file{REPINFO.ADS/ADB} in the
6268 @code{GNAT} sources for full details on the format of
6269 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
6270 If _FILE is added at the end of an option
6271 (e.g. @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
6272 then the output is to a file with the name @file{file_REP} where
6273 file is the name of the corresponding source file.
6274 @end ifset
6276 @item -gnatS
6277 @cindex @option{-gnatS} (@command{gcc})
6278 The use of the switch @option{-gnatS} for an
6279 Ada compilation will cause the compiler to output a
6280 representation of package Standard in a form very
6281 close to standard Ada. It is not quite possible to
6282 do this entirely in standard Ada (since new
6283 numeric base types cannot be created in standard
6284 Ada), but the output is easily
6285 readable to any Ada programmer, and is useful to
6286 determine the characteristics of target dependent
6287 types in package Standard.
6289 @item -gnatx
6290 @cindex @option{-gnatx} (@command{gcc})
6291 Normally the compiler generates full cross-referencing information in
6292 the @file{ALI} file. This information is used by a number of tools,
6293 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
6294 suppresses this information. This saves some space and may slightly
6295 speed up compilation, but means that these tools cannot be used.
6296 @end table
6298 @node Exception Handling Control
6299 @subsection Exception Handling Control
6301 @noindent
6302 GNAT uses two methods for handling exceptions at run-time. The
6303 @code{longjmp/setjmp} method saves the context when entering
6304 a frame with an exception handler. Then when an exception is
6305 raised, the context can be restored immediately, without the
6306 need for tracing stack frames. This method provides very fast
6307 exception propagation, but introduces significant overhead for
6308 the use of exception handlers, even if no exception is raised.
6310 The other approach is called ``zero cost'' exception handling.
6311 With this method, the compiler builds static tables to describe
6312 the exception ranges. No dynamic code is required when entering
6313 a frame containing an exception handler. When an exception is
6314 raised, the tables are used to control a back trace of the
6315 subprogram invocation stack to locate the required exception
6316 handler. This method has considerably poorer performance for
6317 the propagation of exceptions, but there is no overhead for
6318 exception handlers if no exception is raised. Note that in this
6319 mode and in the context of mixed Ada and C/C++ programming,
6320 to propagate an exception through a C/C++ code, the C/C++ code
6321 must be compiled with the @option{-funwind-tables} GCC's
6322 option.
6324 The following switches can be used to control which of the
6325 two exception handling methods is used.
6327 @table @option
6328 @c !sort!
6330 @item -gnatL
6331 @cindex @option{-gnatL} (@command{gcc})
6332 This switch causes the longjmp/setjmp approach to be used
6333 for exception handling. If this is the default mechanism for the
6334 target (see below), then this has no effect. If the default
6335 mechanism for the target is zero cost exceptions, then
6336 this switch can be used to modify this default, but it must be
6337 used for all units in the partition, including all run-time
6338 library units. One way to achieve this is to use the
6339 @option{-a} and @option{-f} switches for @command{gnatmake}.
6340 This option is rarely used. One case in which it may be
6341 advantageous is if you have an application where exception
6342 raising is common and the overall performance of the
6343 application is improved by favoring exception propagation.
6345 @item -gnatZ
6346 @cindex @option{-gnatZ} (@command{gcc})
6347 @cindex Zero Cost Exceptions
6348 This switch causes the zero cost approach to be sed
6349 for exception handling. If this is the default mechanism for the
6350 target (see below), then this has no effect. If the default
6351 mechanism for the target is longjmp/setjmp exceptions, then
6352 this switch can be used to modify this default, but it must be
6353 used for all units in the partition, including all run-time
6354 library units. One way to achieve this is to use the
6355 @option{-a} and @option{-f} switches for @command{gnatmake}.
6356 This option can only be used if the zero cost approach
6357 is available for the target in use (see below).
6358 @end table
6360 @noindent
6361 The @code{longjmp/setjmp} approach is available on all targets, but
6362 the @code{zero cost} approach is only available on selected targets.
6363 To determine whether zero cost exceptions can be used for a
6364 particular target, look at the private part of the file system.ads.
6365 Either @code{GCC_ZCX_Support} or @code{Front_End_ZCX_Support} must
6366 be True to use the zero cost approach. If both of these switches
6367 are set to False, this means that zero cost exception handling
6368 is not yet available for that target. The switch
6369 @code{ZCX_By_Default} indicates the default approach. If this
6370 switch is set to True, then the @code{zero cost} approach is
6371 used by default.
6373 @node Units to Sources Mapping Files
6374 @subsection Units to Sources Mapping Files
6376 @table @option
6378 @item -gnatem^^=^@var{path}
6379 @cindex @option{-gnatem} (@command{gcc})
6380 A mapping file is a way to communicate to the compiler two mappings:
6381 from unit names to file names (without any directory information) and from
6382 file names to path names (with full directory information). These mappings
6383 are used by the compiler to short-circuit the path search.
6385 The use of mapping files is not required for correct operation of the
6386 compiler, but mapping files can improve efficiency, particularly when
6387 sources are read over a slow network connection. In normal operation,
6388 you need not be concerned with the format or use of mapping files,
6389 and the @option{-gnatem} switch is not a switch that you would use
6390 explicitly. it is intended only for use by automatic tools such as
6391 @command{gnatmake} running under the project file facility. The
6392 description here of the format of mapping files is provided
6393 for completeness and for possible use by other tools.
6395 A mapping file is a sequence of sets of three lines. In each set,
6396 the first line is the unit name, in lower case, with ``@code{%s}''
6397 appended for
6398 specifications and ``@code{%b}'' appended for bodies; the second line is the
6399 file name; and the third line is the path name.
6401 Example:
6402 @smallexample
6403    main%b
6404    main.2.ada
6405    /gnat/project1/sources/main.2.ada
6406 @end smallexample
6408 When the switch @option{-gnatem} is specified, the compiler will create
6409 in memory the two mappings from the specified file. If there is any problem
6410 (non existent file, truncated file or duplicate entries), no mapping
6411 will be created.
6413 Several @option{-gnatem} switches may be specified; however, only the last
6414 one on the command line will be taken into account.
6416 When using a project file, @command{gnatmake} create a temporary mapping file
6417 and communicates it to the compiler using this switch.
6419 @end table
6421 @node Integrated Preprocessing
6422 @subsection Integrated Preprocessing
6424 @noindent
6425 GNAT sources may be preprocessed immediately before compilation; the actual
6426 text of the source is not the text of the source file, but is derived from it
6427 through a process called preprocessing. Integrated preprocessing is specified
6428 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
6429 indicates, through a text file, the preprocessing data to be used.
6430 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
6432 @noindent
6433 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
6434 used when Integrated Preprocessing is used. The reason is that preprocessing
6435 with another Preprocessing Data file without changing the sources will
6436 not trigger recompilation without this switch.
6438 @noindent
6439 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
6440 always trigger recompilation for sources that are preprocessed,
6441 because @command{gnatmake} cannot compute the checksum of the source after
6442 preprocessing.
6444 @noindent
6445 The actual preprocessing function is described in details in section
6446 @ref{Preprocessing Using gnatprep}. This section only describes how integrated
6447 preprocessing is triggered and parameterized.
6449 @table @code
6451 @item -gnatep=@var{file}
6452 @cindex @option{-gnatep} (@command{gcc})
6453 This switch indicates to the compiler the file name (without directory
6454 information) of the preprocessor data file to use. The preprocessor data file
6455 should be found in the source directories.
6457 @noindent
6458 A preprocessing data file is a text file with significant lines indicating
6459 how should be preprocessed either a specific source or all sources not
6460 mentioned in other lines. A significant line is a non empty, non comment line.
6461 Comments are similar to Ada comments.
6463 @noindent
6464 Each significant line starts with either a literal string or the character '*'.
6465 A literal string is the file name (without directory information) of the source
6466 to preprocess. A character '*' indicates the preprocessing for all the sources
6467 that are not specified explicitly on other lines (order of the lines is not
6468 significant). It is an error to have two lines with the same file name or two
6469 lines starting with the character '*'.
6471 @noindent
6472 After the file name or the character '*', another optional literal string
6473 indicating the file name of the definition file to be used for preprocessing
6474 (@pxref{Form of Definitions File}). The definition files are found by the
6475 compiler in one of the source directories. In some cases, when compiling
6476 a source in a directory other than the current directory, if the definition
6477 file is in the current directory, it may be necessary to add the current
6478 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
6479 the compiler would not find the definition file.
6481 @noindent
6482 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
6483 be found. Those ^switches^switches^ are:
6485 @table @code
6487 @item -b
6488 Causes both preprocessor lines and the lines deleted by
6489 preprocessing to be replaced by blank lines, preserving the line number.
6490 This ^switch^switch^ is always implied; however, if specified after @option{-c}
6491 it cancels the effect of @option{-c}.
6493 @item -c
6494 Causes both preprocessor lines and the lines deleted
6495 by preprocessing to be retained as comments marked
6496 with the special string ``@code{--! }''.
6498 @item -Dsymbol=value
6499 Define or redefine a symbol, associated with value. A symbol is an Ada
6500 identifier, or an Ada reserved word, with the exception of @code{if},
6501 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6502 @code{value} is either a literal string, an Ada identifier or any Ada reserved
6503 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
6504 same name defined in a definition file.
6506 @item -s
6507 Causes a sorted list of symbol names and values to be
6508 listed on the standard output file.
6510 @item -u
6511 Causes undefined symbols to be treated as having the value @code{FALSE}
6512 in the context
6513 of a preprocessor test. In the absence of this option, an undefined symbol in
6514 a @code{#if} or @code{#elsif} test will be treated as an error.
6516 @end table
6518 @noindent
6519 Examples of valid lines in a preprocessor data file:
6521 @smallexample
6522   "toto.adb"  "prep.def" -u
6523   --  preprocess "toto.adb", using definition file "prep.def",
6524   --  undefined symbol are False.
6526   * -c -DVERSION=V101
6527   --  preprocess all other sources without a definition file;
6528   --  suppressed lined are commented; symbol VERSION has the value V101.
6530   "titi.adb" "prep2.def" -s
6531   --  preprocess "titi.adb", using definition file "prep2.def";
6532   --  list all symbols with their values.
6533 @end smallexample
6535 @item ^-gnateD^/DATA_PREPROCESSING=^symbol[=value]
6536 @cindex @option{-gnateD} (@command{gcc})
6537 Define or redefine a preprocessing symbol, associated with value. If no value
6538 is given on the command line, then the value of the symbol is @code{True}.
6539 A symbol is an identifier, following normal Ada (case-insensitive)
6540 rules for its syntax, and value is any sequence (including an empty sequence)
6541 of characters from the set (letters, digits, period, underline).
6542 Ada reserved words may be used as symbols, with the exceptions of @code{if},
6543 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
6545 @noindent
6546 A symbol declared with this ^switch^switch^ on the command line replaces a
6547 symbol with the same name either in a definition file or specified with a
6548 ^switch^switch^ -D in the preprocessor data file.
6550 @noindent
6551 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
6553 @end table
6555 @node Code Generation Control
6556 @subsection Code Generation Control
6558 @noindent
6560 The GCC technology provides a wide range of target dependent
6561 @option{-m} switches for controlling
6562 details of code generation with respect to different versions of
6563 architectures. This includes variations in instruction sets (e.g.
6564 different members of the power pc family), and different requirements
6565 for optimal arrangement of instructions (e.g. different members of
6566 the x86 family). The list of available @option{-m} switches may be
6567 found in the GCC documentation.
6569 Use of the these @option{-m} switches may in some cases result in improved
6570 code performance.
6572 The GNAT Pro technology is tested and qualified without any
6573 @option{-m} switches,
6574 so generally the most reliable approach is to avoid the use of these
6575 switches. However, we generally expect most of these switches to work
6576 successfully with GNAT Pro, and many customers have reported successful
6577 use of these options.
6579 Our general advice is to avoid the use of @option{-m} switches unless
6580 special needs lead to requirements in this area. In particular,
6581 there is no point in using @option{-m} switches to improve performance
6582 unless you actually see a performance improvement.
6584 @ifset vms
6585 @node Return Codes
6586 @subsection Return Codes
6587 @cindex Return Codes
6588 @cindex @option{/RETURN_CODES=VMS}
6590 @noindent
6591 On VMS, GNAT compiled programs return POSIX-style codes by default,
6592 e.g. @option{/RETURN_CODES=POSIX}.
6594 To enable VMS style return codes, use GNAT BIND and LINK with the option
6595 @option{/RETURN_CODES=VMS}. For example:
6597 @smallexample
6598 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
6599 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
6600 @end smallexample
6602 @noindent
6603 Programs built with /RETURN_CODES=VMS are suitable to be called in
6604 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
6605 are suitable for spawning with appropriate GNAT RTL routines.
6607 @end ifset
6609 @node Search Paths and the Run-Time Library (RTL)
6610 @section Search Paths and the Run-Time Library (RTL)
6612 @noindent
6613 With the GNAT source-based library system, the compiler must be able to
6614 find source files for units that are needed by the unit being compiled.
6615 Search paths are used to guide this process.
6617 The compiler compiles one source file whose name must be given
6618 explicitly on the command line. In other words, no searching is done
6619 for this file. To find all other source files that are needed (the most
6620 common being the specs of units), the compiler examines the following
6621 directories, in the following order:
6623 @enumerate
6624 @item
6625 The directory containing the source file of the main unit being compiled
6626 (the file name on the command line).
6628 @item
6629 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
6630 @command{gcc} command line, in the order given.
6632 @item
6633 @findex ADA_INCLUDE_PATH
6634 Each of the directories listed in the value of the
6635 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
6636 @ifclear vms
6637 Construct this value
6638 exactly as the @code{PATH} environment variable: a list of directory
6639 names separated by colons (semicolons when working with the NT version).
6640 @end ifclear
6641 @ifset vms
6642 Normally, define this value as a logical name containing a comma separated
6643 list of directory names.
6645 This variable can also be defined by means of an environment string
6646 (an argument to the DEC C exec* set of functions).
6648 Logical Name:
6649 @smallexample
6650 DEFINE ANOTHER_PATH FOO:[BAG]
6651 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
6652 @end smallexample
6654 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
6655 first, followed by the standard Ada 95
6656 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
6657 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
6658 (Text_IO, Sequential_IO, etc)
6659 instead of the Ada95 packages. Thus, in order to get the Ada 95
6660 packages by default, ADA_INCLUDE_PATH must be redefined.
6661 @end ifset
6663 @item
6664 @findex ADA_PRJ_INCLUDE_FILE
6665 Each of the directories listed in the text file whose name is given
6666 by the @code{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
6668 @noindent
6669 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
6670 driver when project files are used. It should not normally be set
6671 by other means.
6673 @item
6674 The content of the @file{ada_source_path} file which is part of the GNAT
6675 installation tree and is used to store standard libraries such as the
6676 GNAT Run Time Library (RTL) source files.
6677 @ifclear vms
6678 @ref{Installing a library}
6679 @end ifclear
6680 @end enumerate
6682 @noindent
6683 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
6684 inhibits the use of the directory
6685 containing the source file named in the command line. You can still
6686 have this directory on your search path, but in this case it must be
6687 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
6689 Specifying the switch @option{-nostdinc}
6690 inhibits the search of the default location for the GNAT Run Time
6691 Library (RTL) source files.
6693 The compiler outputs its object files and ALI files in the current
6694 working directory.
6695 @ifclear vms
6696 Caution: The object file can be redirected with the @option{-o} switch;
6697 however, @command{gcc} and @code{gnat1} have not been coordinated on this
6698 so the @file{ALI} file will not go to the right place. Therefore, you should
6699 avoid using the @option{-o} switch.
6700 @end ifclear
6702 @findex System.IO
6703 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
6704 children make up the GNAT RTL, together with the simple @code{System.IO}
6705 package used in the @code{"Hello World"} example. The sources for these units
6706 are needed by the compiler and are kept together in one directory. Not
6707 all of the bodies are needed, but all of the sources are kept together
6708 anyway. In a normal installation, you need not specify these directory
6709 names when compiling or binding. Either the environment variables or
6710 the built-in defaults cause these files to be found.
6712 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
6713 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
6714 consisting of child units of @code{GNAT}. This is a collection of generally
6715 useful types, subprograms, etc. See the @cite{GNAT Reference Manual} for
6716 further details.
6718 Besides simplifying access to the RTL, a major use of search paths is
6719 in compiling sources from multiple directories. This can make
6720 development environments much more flexible.
6722 @node Order of Compilation Issues
6723 @section Order of Compilation Issues
6725 @noindent
6726 If, in our earlier example, there was a spec for the @code{hello}
6727 procedure, it would be contained in the file @file{hello.ads}; yet this
6728 file would not have to be explicitly compiled. This is the result of the
6729 model we chose to implement library management. Some of the consequences
6730 of this model are as follows:
6732 @itemize @bullet
6733 @item
6734 There is no point in compiling specs (except for package
6735 specs with no bodies) because these are compiled as needed by clients. If
6736 you attempt a useless compilation, you will receive an error message.
6737 It is also useless to compile subunits because they are compiled as needed
6738 by the parent.
6740 @item
6741 There are no order of compilation requirements: performing a
6742 compilation never obsoletes anything. The only way you can obsolete
6743 something and require recompilations is to modify one of the
6744 source files on which it depends.
6746 @item
6747 There is no library as such, apart from the ALI files
6748 (@pxref{The Ada Library Information Files}, for information on the format
6749 of these files). For now we find it convenient to create separate ALI files,
6750 but eventually the information therein may be incorporated into the object
6751 file directly.
6753 @item
6754 When you compile a unit, the source files for the specs of all units
6755 that it @code{with}'s, all its subunits, and the bodies of any generics it
6756 instantiates must be available (reachable by the search-paths mechanism
6757 described above), or you will receive a fatal error message.
6758 @end itemize
6760 @node Examples
6761 @section Examples
6763 @noindent
6764 The following are some typical Ada compilation command line examples:
6766 @table @code
6767 @item $ gcc -c xyz.adb
6768 Compile body in file @file{xyz.adb} with all default options.
6770 @ifclear vms
6771 @item $ gcc -c -O2 -gnata xyz-def.adb
6772 @end ifclear
6773 @ifset vms
6774 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
6775 @end ifset
6777 Compile the child unit package in file @file{xyz-def.adb} with extensive
6778 optimizations, and pragma @code{Assert}/@code{Debug} statements
6779 enabled.
6781 @item $ gcc -c -gnatc abc-def.adb
6782 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
6783 mode.
6784 @end table
6786 @node Binding Using gnatbind
6787 @chapter Binding Using @code{gnatbind}
6788 @findex gnatbind
6790 @menu
6791 * Running gnatbind::
6792 * Switches for gnatbind::
6793 * Command-Line Access::
6794 * Search Paths for gnatbind::
6795 * Examples of gnatbind Usage::
6796 @end menu
6798 @noindent
6799 This chapter describes the GNAT binder, @code{gnatbind}, which is used
6800 to bind compiled GNAT objects. The @code{gnatbind} program performs
6801 four separate functions:
6803 @enumerate
6804 @item
6805 Checks that a program is consistent, in accordance with the rules in
6806 Chapter 10 of the Ada 95 Reference Manual. In particular, error
6807 messages are generated if a program uses inconsistent versions of a
6808 given unit.
6810 @item
6811 Checks that an acceptable order of elaboration exists for the program
6812 and issues an error message if it cannot find an order of elaboration
6813 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
6815 @item
6816 Generates a main program incorporating the given elaboration order.
6817 This program is a small Ada package (body and spec) that
6818 must be subsequently compiled
6819 using the GNAT compiler. The necessary compilation step is usually
6820 performed automatically by @command{gnatlink}. The two most important
6821 functions of this program
6822 are to call the elaboration routines of units in an appropriate order
6823 and to call the main program.
6825 @item
6826 Determines the set of object files required by the given main program.
6827 This information is output in the forms of comments in the generated program,
6828 to be read by the @command{gnatlink} utility used to link the Ada application.
6829 @end enumerate
6831 @node Running gnatbind
6832 @section Running @code{gnatbind}
6834 @noindent
6835 The form of the @code{gnatbind} command is
6837 @smallexample
6838 $ gnatbind [@i{switches}] @i{mainprog}[.ali] [@i{switches}]
6839 @end smallexample
6841 @noindent
6842 where @file{@i{mainprog}.adb} is the Ada file containing the main program
6843 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
6844 package in two files whose names are
6845 @file{b~@i{mainprog}.ads}, and @file{b~@i{mainprog}.adb}.
6846 For example, if given the
6847 parameter @file{hello.ali}, for a main program contained in file
6848 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
6849 and @file{b~hello.adb}.
6851 When doing consistency checking, the binder takes into consideration
6852 any source files it can locate. For example, if the binder determines
6853 that the given main program requires the package @code{Pack}, whose
6854 @file{.ALI}
6855 file is @file{pack.ali} and whose corresponding source spec file is
6856 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
6857 (using the same search path conventions as previously described for the
6858 @command{gcc} command). If it can locate this source file, it checks that
6859 the time stamps
6860 or source checksums of the source and its references to in @file{ALI} files
6861 match. In other words, any @file{ALI} files that mentions this spec must have
6862 resulted from compiling this version of the source file (or in the case
6863 where the source checksums match, a version close enough that the
6864 difference does not matter).
6866 @cindex Source files, use by binder
6867 The effect of this consistency checking, which includes source files, is
6868 that the binder ensures that the program is consistent with the latest
6869 version of the source files that can be located at bind time. Editing a
6870 source file without compiling files that depend on the source file cause
6871 error messages to be generated by the binder.
6873 For example, suppose you have a main program @file{hello.adb} and a
6874 package @code{P}, from file @file{p.ads} and you perform the following
6875 steps:
6877 @enumerate
6878 @item
6879 Enter @code{gcc -c hello.adb} to compile the main program.
6881 @item
6882 Enter @code{gcc -c p.ads} to compile package @code{P}.
6884 @item
6885 Edit file @file{p.ads}.
6887 @item
6888 Enter @code{gnatbind hello}.
6889 @end enumerate
6891 @noindent
6892 At this point, the file @file{p.ali} contains an out-of-date time stamp
6893 because the file @file{p.ads} has been edited. The attempt at binding
6894 fails, and the binder generates the following error messages:
6896 @smallexample
6897 error: "hello.adb" must be recompiled ("p.ads" has been modified)
6898 error: "p.ads" has been modified and must be recompiled
6899 @end smallexample
6901 @noindent
6902 Now both files must be recompiled as indicated, and then the bind can
6903 succeed, generating a main program. You need not normally be concerned
6904 with the contents of this file, but for reference purposes a sample
6905 binder output file is given in @ref{Example of Binder Output File}.
6907 In most normal usage, the default mode of @command{gnatbind} which is to
6908 generate the main package in Ada, as described in the previous section.
6909 In particular, this means that any Ada programmer can read and understand
6910 the generated main program. It can also be debugged just like any other
6911 Ada code provided the @option{^-g^/DEBUG^} switch is used for
6912 @command{gnatbind} and @command{gnatlink}.
6914 However for some purposes it may be convenient to generate the main
6915 program in C rather than Ada. This may for example be helpful when you
6916 are generating a mixed language program with the main program in C. The
6917 GNAT compiler itself is an example.
6918 The use of the @option{^-C^/BIND_FILE=C^} switch
6919 for both @code{gnatbind} and @command{gnatlink} will cause the program to
6920 be generated in C (and compiled using the gnu C compiler).
6922 @node Switches for gnatbind
6923 @section Switches for @command{gnatbind}
6925 @noindent
6926 The following switches are available with @code{gnatbind}; details will
6927 be presented in subsequent sections.
6929 @menu
6930 * Consistency-Checking Modes::
6931 * Binder Error Message Control::
6932 * Elaboration Control::
6933 * Output Control::
6934 * Binding with Non-Ada Main Programs::
6935 * Binding Programs with No Main Subprogram::
6936 @end menu
6938 @table @option
6939 @c !sort!
6940 @item ^-aO^/OBJECT_SEARCH^
6941 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
6942 Specify directory to be searched for ALI files.
6944 @item ^-aI^/SOURCE_SEARCH^
6945 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
6946 Specify directory to be searched for source file.
6948 @item ^-A^/BIND_FILE=ADA^
6949 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatbind})
6950 Generate binder program in Ada (default)
6952 @item ^-b^/REPORT_ERRORS=BRIEF^
6953 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
6954 Generate brief messages to @file{stderr} even if verbose mode set.
6956 @item ^-c^/NOOUTPUT^
6957 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
6958 Check only, no generation of binder output file.
6960 @item ^-C^/BIND_FILE=C^
6961 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatbind})
6962 Generate binder program in C
6964 @item ^-e^/ELABORATION_DEPENDENCIES^
6965 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
6966 Output complete list of elaboration-order dependencies.
6968 @item ^-E^/STORE_TRACEBACKS^
6969 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
6970 Store tracebacks in exception occurrences when the target supports it.
6971 This is the default with the zero cost exception mechanism.
6972 @ignore
6973 @c The following may get moved to an appendix
6974 This option is currently supported on the following targets:
6975 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
6976 @end ignore
6977 See also the packages @code{GNAT.Traceback} and
6978 @code{GNAT.Traceback.Symbolic} for more information.
6979 @ifclear vms
6980 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
6981 @command{gcc} option.
6982 @end ifclear
6984 @item ^-F^/FORCE_ELABS_FLAGS^
6985 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
6986 Force the checks of elaboration flags. @command{gnatbind} does not normally
6987 generate checks of elaboration flags for the main executable, except when
6988 a Stand-Alone Library is used. However, there are cases when this cannot be
6989 detected by gnatbind. An example is importing an interface of a Stand-Alone
6990 Library through a pragma Import and only specifying through a linker switch
6991 this Stand-Alone Library. This switch is used to guarantee that elaboration
6992 flag checks are generated.
6994 @item ^-h^/HELP^
6995 @cindex @option{^-h^/HELP^} (@command{gnatbind})
6996 Output usage (help) information
6998 @item ^-I^/SEARCH^
6999 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7000 Specify directory to be searched for source and ALI files.
7002 @item ^-I-^/NOCURRENT_DIRECTORY^
7003 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
7004 Do not look for sources in the current directory where @code{gnatbind} was
7005 invoked, and do not look for ALI files in the directory containing the
7006 ALI file named in the @code{gnatbind} command line.
7008 @item ^-l^/ORDER_OF_ELABORATION^
7009 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
7010 Output chosen elaboration order.
7012 @item ^-Lxxx^/BUILD_LIBRARY=xxx^
7013 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
7014 Bind the units for library building. In this case the adainit and
7015 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
7016 are renamed to ^xxxinit^XXXINIT^ and
7017 ^xxxfinal^XXXFINAL^.
7018 Implies ^-n^/NOCOMPILE^.
7019 @ifclear vms
7020 (@xref{GNAT and Libraries}, for more details.)
7021 @end ifclear
7022 @ifset vms
7023 On OpenVMS, these init and final procedures are exported in uppercase
7024 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
7025 the init procedure will be "TOTOINIT" and the exported name of the final
7026 procedure will be "TOTOFINAL".
7027 @end ifset
7029 @item ^-Mxyz^/RENAME_MAIN=xyz^
7030 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
7031 Rename generated main program from main to xyz
7033 @item ^-m^/ERROR_LIMIT=^@var{n}
7034 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
7035 Limit number of detected errors to @var{n}, where @var{n} is
7036 in the range 1..999_999. The default value if no switch is
7037 given is 9999. Binding is terminated if the limit is exceeded.
7038 @ifset unw
7039 Furthermore, under Windows, the sources pointed to by the libraries path
7040 set in the registry are not searched for.
7041 @end ifset
7043 @item ^-n^/NOMAIN^
7044 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7045 No main program.
7047 @item -nostdinc
7048 @cindex @option{-nostdinc} (@command{gnatbind})
7049 Do not look for sources in the system default directory.
7051 @item -nostdlib
7052 @cindex @option{-nostdlib} (@command{gnatbind})
7053 Do not look for library files in the system default directory.
7055 @item --RTS=@var{rts-path}
7056 @cindex @option{--RTS} (@code{gnatbind})
7057 Specifies the default location of the runtime library. Same meaning as the
7058 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
7060 @item ^-o ^/OUTPUT=^@var{file}
7061 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
7062 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7063 Note that if this option is used, then linking must be done manually,
7064 gnatlink cannot be used.
7066 @item ^-O^/OBJECT_LIST^
7067 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
7068 Output object list.
7070 @item ^-p^/PESSIMISTIC_ELABORATION^
7071 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
7072 Pessimistic (worst-case) elaboration order
7074 @item ^-s^/READ_SOURCES=ALL^
7075 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
7076 Require all source files to be present.
7078 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
7079 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
7080 Specifies the value to be used when detecting uninitialized scalar
7081 objects with pragma Initialize_Scalars.
7082 The @var{xxx} ^string specified with the switch^option^ may be either
7083 @itemize @bullet
7084 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
7085 @item ``@option{^lo^LOW^}'' for the lowest possible value
7086 possible, and the low
7087 @item ``@option{^hi^HIGH^}'' for the highest possible value
7088 @item ``@option{xx}'' for a value consisting of repeated bytes with the
7089 value 16#xx# (i.e. xx is a string of two hexadecimal digits).
7090 @end itemize
7092 In addition, you can specify @option{-Sev} to indicate that the value is
7093 to be set at run time. In this case, the program will look for an environment
7094 @cindex GNAT_INIT_SCALARS
7095 variable of the form @code{GNAT_INIT_SCALARS=xx}, where xx is one
7096 of @option{in/lo/hi/xx} with the same meanings as above.
7097 If no environment variable is found, or if it does not have a valid value,
7098 then the default is @option{in} (invalid values).
7100 @ifclear vms
7101 @item -static
7102 @cindex @option{-static} (@code{gnatbind})
7103 Link against a static GNAT run time.
7105 @item -shared
7106 @cindex @option{-shared} (@code{gnatbind})
7107 Link against a shared GNAT run time when available.
7108 @end ifclear
7110 @item ^-t^/NOTIME_STAMP_CHECK^
7111 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7112 Tolerate time stamp and other consistency errors
7114 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
7115 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
7116 Set the time slice value to @var{n} milliseconds. If the system supports
7117 the specification of a specific time slice value, then the indicated value
7118 is used. If the system does not support specific time slice values, but
7119 does support some general notion of round-robin scheduling, then any
7120 non-zero value will activate round-robin scheduling.
7122 A value of zero is treated specially. It turns off time
7123 slicing, and in addition, indicates to the tasking run time that the
7124 semantics should match as closely as possible the Annex D
7125 requirements of the Ada RM, and in particular sets the default
7126 scheduling policy to @code{FIFO_Within_Priorities}.
7128 @item ^-v^/REPORT_ERRORS=VERBOSE^
7129 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7130 Verbose mode. Write error messages, header, summary output to
7131 @file{stdout}.
7133 @ifclear vms
7134 @item -w@var{x}
7135 @cindex @option{-w} (@code{gnatbind})
7136 Warning mode (@var{x}=s/e for suppress/treat as error)
7137 @end ifclear
7139 @ifset vms
7140 @item /WARNINGS=NORMAL
7141 @cindex @option{/WARNINGS} (@code{gnatbind})
7142 Normal warnings mode. Warnings are issued but ignored
7144 @item /WARNINGS=SUPPRESS
7145 @cindex @option{/WARNINGS} (@code{gnatbind})
7146 All warning messages are suppressed
7148 @item /WARNINGS=ERROR
7149 @cindex @option{/WARNINGS} (@code{gnatbind})
7150 Warning messages are treated as fatal errors
7151 @end ifset
7153 @item ^-x^/READ_SOURCES=NONE^
7154 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
7155 Exclude source files (check object consistency only).
7157 @ifset vms
7158 @item /READ_SOURCES=AVAILABLE
7159 @cindex @option{/READ_SOURCES} (@code{gnatbind})
7160 Default mode, in which sources are checked for consistency only if
7161 they are available.
7162 @end ifset
7164 @item ^-z^/ZERO_MAIN^
7165 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7166 No main subprogram.
7167 @end table
7169 @ifclear vms
7170 @noindent
7171 You may obtain this listing of switches by running @code{gnatbind} with
7172 no arguments.
7173 @end ifclear
7175 @node Consistency-Checking Modes
7176 @subsection Consistency-Checking Modes
7178 @noindent
7179 As described earlier, by default @code{gnatbind} checks
7180 that object files are consistent with one another and are consistent
7181 with any source files it can locate. The following switches control binder
7182 access to sources.
7184 @table @option
7185 @c !sort!
7186 @item ^-s^/READ_SOURCES=ALL^
7187 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
7188 Require source files to be present. In this mode, the binder must be
7189 able to locate all source files that are referenced, in order to check
7190 their consistency. In normal mode, if a source file cannot be located it
7191 is simply ignored. If you specify this switch, a missing source
7192 file is an error.
7194 @item ^-x^/READ_SOURCES=NONE^
7195 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
7196 Exclude source files. In this mode, the binder only checks that ALI
7197 files are consistent with one another. Source files are not accessed.
7198 The binder runs faster in this mode, and there is still a guarantee that
7199 the resulting program is self-consistent.
7200 If a source file has been edited since it was last compiled, and you
7201 specify this switch, the binder will not detect that the object
7202 file is out of date with respect to the source file. Note that this is the
7203 mode that is automatically used by @command{gnatmake} because in this
7204 case the checking against sources has already been performed by
7205 @command{gnatmake} in the course of compilation (i.e. before binding).
7207 @ifset vms
7208 @item /READ_SOURCES=AVAILABLE
7209 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
7210 This is the default mode in which source files are checked if they are
7211 available, and ignored if they are not available.
7212 @end ifset
7213 @end table
7215 @node Binder Error Message Control
7216 @subsection Binder Error Message Control
7218 @noindent
7219 The following switches provide control over the generation of error
7220 messages from the binder:
7222 @table @option
7223 @c !sort!
7224 @item ^-v^/REPORT_ERRORS=VERBOSE^
7225 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
7226 Verbose mode. In the normal mode, brief error messages are generated to
7227 @file{stderr}. If this switch is present, a header is written
7228 to @file{stdout} and any error messages are directed to @file{stdout}.
7229 All that is written to @file{stderr} is a brief summary message.
7231 @item ^-b^/REPORT_ERRORS=BRIEF^
7232 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
7233 Generate brief error messages to @file{stderr} even if verbose mode is
7234 specified. This is relevant only when used with the
7235 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
7237 @ifclear vms
7238 @item -m@var{n}
7239 @cindex @option{-m} (@code{gnatbind})
7240 Limits the number of error messages to @var{n}, a decimal integer in the
7241 range 1-999. The binder terminates immediately if this limit is reached.
7243 @item -M@var{xxx}
7244 @cindex @option{-M} (@code{gnatbind})
7245 Renames the generated main program from @code{main} to @code{xxx}.
7246 This is useful in the case of some cross-building environments, where
7247 the actual main program is separate from the one generated
7248 by @code{gnatbind}.
7249 @end ifclear
7251 @item ^-ws^/WARNINGS=SUPPRESS^
7252 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
7253 @cindex Warnings
7254 Suppress all warning messages.
7256 @item ^-we^/WARNINGS=ERROR^
7257 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
7258 Treat any warning messages as fatal errors.
7260 @ifset vms
7261 @item /WARNINGS=NORMAL
7262 Standard mode with warnings generated, but warnings do not get treated
7263 as errors.
7264 @end ifset
7266 @item ^-t^/NOTIME_STAMP_CHECK^
7267 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
7268 @cindex Time stamp checks, in binder
7269 @cindex Binder consistency checks
7270 @cindex Consistency checks, in binder
7271 The binder performs a number of consistency checks including:
7273 @itemize @bullet
7274 @item
7275 Check that time stamps of a given source unit are consistent
7276 @item
7277 Check that checksums of a given source unit are consistent
7278 @item
7279 Check that consistent versions of @code{GNAT} were used for compilation
7280 @item
7281 Check consistency of configuration pragmas as required
7282 @end itemize
7284 @noindent
7285 Normally failure of such checks, in accordance with the consistency
7286 requirements of the Ada Reference Manual, causes error messages to be
7287 generated which abort the binder and prevent the output of a binder
7288 file and subsequent link to obtain an executable.
7290 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
7291 into warnings, so that
7292 binding and linking can continue to completion even in the presence of such
7293 errors. The result may be a failed link (due to missing symbols), or a
7294 non-functional executable which has undefined semantics.
7295 @emph{This means that
7296 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
7297 with extreme care.}
7298 @end table
7300 @node Elaboration Control
7301 @subsection Elaboration Control
7303 @noindent
7304 The following switches provide additional control over the elaboration
7305 order. For full details see @ref{Elaboration Order Handling in GNAT}.
7307 @table @option
7308 @item ^-p^/PESSIMISTIC_ELABORATION^
7309 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
7310 Normally the binder attempts to choose an elaboration order that is
7311 likely to minimize the likelihood of an elaboration order error resulting
7312 in raising a @code{Program_Error} exception. This switch reverses the
7313 action of the binder, and requests that it deliberately choose an order
7314 that is likely to maximize the likelihood of an elaboration error.
7315 This is useful in ensuring portability and avoiding dependence on
7316 accidental fortuitous elaboration ordering.
7318 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
7319 switch if dynamic
7320 elaboration checking is used (@option{-gnatE} switch used for compilation).
7321 This is because in the default static elaboration mode, all necessary
7322 @code{Elaborate_All} pragmas are implicitly inserted.
7323 These implicit pragmas are still respected by the binder in
7324 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
7325 safe elaboration order is assured.
7326 @end table
7328 @node Output Control
7329 @subsection Output Control
7331 @noindent
7332 The following switches allow additional control over the output
7333 generated by the binder.
7335 @table @option
7336 @c !sort!
7338 @item ^-A^/BIND_FILE=ADA^
7339 @cindex @option{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
7340 Generate binder program in Ada (default). The binder program is named
7341 @file{b~@var{mainprog}.adb} by default. This can be changed with
7342 @option{^-o^/OUTPUT^} @code{gnatbind} option.
7344 @item ^-c^/NOOUTPUT^
7345 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
7346 Check only. Do not generate the binder output file. In this mode the
7347 binder performs all error checks but does not generate an output file.
7349 @item ^-C^/BIND_FILE=C^
7350 @cindex @option{^-C^/BIND_FILE=C^} (@code{gnatbind})
7351 Generate binder program in C. The binder program is named
7352 @file{b_@var{mainprog}.c}.
7353 This can be changed with @option{^-o^/OUTPUT^} @code{gnatbind}
7354 option.
7356 @item ^-e^/ELABORATION_DEPENDENCIES^
7357 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
7358 Output complete list of elaboration-order dependencies, showing the
7359 reason for each dependency. This output can be rather extensive but may
7360 be useful in diagnosing problems with elaboration order. The output is
7361 written to @file{stdout}.
7363 @item ^-h^/HELP^
7364 @cindex @option{^-h^/HELP^} (@code{gnatbind})
7365 Output usage information. The output is written to @file{stdout}.
7367 @item ^-K^/LINKER_OPTION_LIST^
7368 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
7369 Output linker options to @file{stdout}. Includes library search paths,
7370 contents of pragmas Ident and Linker_Options, and libraries added
7371 by @code{gnatbind}.
7373 @item ^-l^/ORDER_OF_ELABORATION^
7374 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
7375 Output chosen elaboration order. The output is written to @file{stdout}.
7377 @item ^-O^/OBJECT_LIST^
7378 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
7379 Output full names of all the object files that must be linked to provide
7380 the Ada component of the program. The output is written to @file{stdout}.
7381 This list includes the files explicitly supplied and referenced by the user
7382 as well as implicitly referenced run-time unit files. The latter are
7383 omitted if the corresponding units reside in shared libraries. The
7384 directory names for the run-time units depend on the system configuration.
7386 @item ^-o ^/OUTPUT=^@var{file}
7387 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
7388 Set name of output file to @var{file} instead of the normal
7389 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
7390 binder generated body filename. In C mode you would normally give
7391 @var{file} an extension of @file{.c} because it will be a C source program.
7392 Note that if this option is used, then linking must be done manually.
7393 It is not possible to use gnatlink in this case, since it cannot locate
7394 the binder file.
7396 @item ^-r^/RESTRICTION_LIST^
7397 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
7398 Generate list of @code{pragma Restrictions} that could be applied to
7399 the current unit. This is useful for code audit purposes, and also may
7400 be used to improve code generation in some cases.
7402 @end table
7404 @node Binding with Non-Ada Main Programs
7405 @subsection Binding with Non-Ada Main Programs
7407 @noindent
7408 In our description so far we have assumed that the main
7409 program is in Ada, and that the task of the binder is to generate a
7410 corresponding function @code{main} that invokes this Ada main
7411 program. GNAT also supports the building of executable programs where
7412 the main program is not in Ada, but some of the called routines are
7413 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
7414 The following switch is used in this situation:
7416 @table @option
7417 @item ^-n^/NOMAIN^
7418 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
7419 No main program. The main program is not in Ada.
7420 @end table
7422 @noindent
7423 In this case, most of the functions of the binder are still required,
7424 but instead of generating a main program, the binder generates a file
7425 containing the following callable routines:
7427 @table @code
7428 @item adainit
7429 @findex adainit
7430 You must call this routine to initialize the Ada part of the program by
7431 calling the necessary elaboration routines. A call to @code{adainit} is
7432 required before the first call to an Ada subprogram.
7434 Note that it is assumed that the basic execution environment must be setup
7435 to be appropriate for Ada execution at the point where the first Ada
7436 subprogram is called. In particular, if the Ada code will do any
7437 floating-point operations, then the FPU must be setup in an appropriate
7438 manner. For the case of the x86, for example, full precision mode is
7439 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7440 that the FPU is in the right state.
7442 @item adafinal
7443 @findex adafinal
7444 You must call this routine to perform any library-level finalization
7445 required by the Ada subprograms. A call to @code{adafinal} is required
7446 after the last call to an Ada subprogram, and before the program
7447 terminates.
7448 @end table
7450 @noindent
7451 If the @option{^-n^/NOMAIN^} switch
7452 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
7453 @cindex Binder, multiple input files
7454 is given, more than one ALI file may appear on
7455 the command line for @code{gnatbind}. The normal @dfn{closure}
7456 calculation is performed for each of the specified units. Calculating
7457 the closure means finding out the set of units involved by tracing
7458 @code{with} references. The reason it is necessary to be able to
7459 specify more than one ALI file is that a given program may invoke two or
7460 more quite separate groups of Ada units.
7462 The binder takes the name of its output file from the last specified ALI
7463 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
7464 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
7465 The output is an Ada unit in source form that can
7466 be compiled with GNAT unless the -C switch is used in which case the
7467 output is a C source file, which must be compiled using the C compiler.
7468 This compilation occurs automatically as part of the @command{gnatlink}
7469 processing.
7471 Currently the GNAT run time requires a FPU using 80 bits mode
7472 precision. Under targets where this is not the default it is required to
7473 call GNAT.Float_Control.Reset before using floating point numbers (this
7474 include float computation, float input and output) in the Ada code. A
7475 side effect is that this could be the wrong mode for the foreign code
7476 where floating point computation could be broken after this call.
7478 @node Binding Programs with No Main Subprogram
7479 @subsection Binding Programs with No Main Subprogram
7481 @noindent
7482 It is possible to have an Ada program which does not have a main
7483 subprogram. This program will call the elaboration routines of all the
7484 packages, then the finalization routines.
7486 The following switch is used to bind programs organized in this manner:
7488 @table @option
7489 @item ^-z^/ZERO_MAIN^
7490 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
7491 Normally the binder checks that the unit name given on the command line
7492 corresponds to a suitable main subprogram. When this switch is used,
7493 a list of ALI files can be given, and the execution of the program
7494 consists of elaboration of these units in an appropriate order.
7495 @end table
7497 @node Command-Line Access
7498 @section Command-Line Access
7500 @noindent
7501 The package @code{Ada.Command_Line} provides access to the command-line
7502 arguments and program name. In order for this interface to operate
7503 correctly, the two variables
7505 @smallexample
7506 @group
7507 int gnat_argc;
7508 char **gnat_argv;
7509 @end group
7510 @end smallexample
7512 @noindent
7513 @findex gnat_argv
7514 @findex gnat_argc
7515 are declared in one of the GNAT library routines. These variables must
7516 be set from the actual @code{argc} and @code{argv} values passed to the
7517 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
7518 generates the C main program to automatically set these variables.
7519 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
7520 set these variables. If they are not set, the procedures in
7521 @code{Ada.Command_Line} will not be available, and any attempt to use
7522 them will raise @code{Constraint_Error}. If command line access is
7523 required, your main program must set @code{gnat_argc} and
7524 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7527 @node Search Paths for gnatbind
7528 @section Search Paths for @code{gnatbind}
7530 @noindent
7531 The binder takes the name of an ALI file as its argument and needs to
7532 locate source files as well as other ALI files to verify object consistency.
7534 For source files, it follows exactly the same search rules as @command{gcc}
7535 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7536 directories searched are:
7538 @enumerate
7539 @item
7540 The directory containing the ALI file named in the command line, unless
7541 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7543 @item
7544 All directories specified by @option{^-I^/SEARCH^}
7545 switches on the @code{gnatbind}
7546 command line, in the order given.
7548 @item
7549 @findex ADA_OBJECTS_PATH
7550 Each of the directories listed in the value of the
7551 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7552 @ifset unw
7553 Construct this value
7554 exactly as the @code{PATH} environment variable: a list of directory
7555 names separated by colons (semicolons when working with the NT version
7556 of GNAT).
7557 @end ifset
7558 @ifset vms
7559 Normally, define this value as a logical name containing a comma separated
7560 list of directory names.
7562 This variable can also be defined by means of an environment string
7563 (an argument to the DEC C exec* set of functions).
7565 Logical Name:
7566 @smallexample
7567 DEFINE ANOTHER_PATH FOO:[BAG]
7568 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7569 @end smallexample
7571 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7572 first, followed by the standard Ada 95
7573 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7574 If this is not redefined, the user will obtain the DEC Ada 83 IO packages
7575 (Text_IO, Sequential_IO, etc)
7576 instead of the Ada95 packages. Thus, in order to get the Ada 95
7577 packages by default, ADA_OBJECTS_PATH must be redefined.
7578 @end ifset
7580 @item
7581 @findex ADA_PRJ_OBJECTS_FILE
7582 Each of the directories listed in the text file whose name is given
7583 by the @code{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
7585 @noindent
7586 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7587 driver when project files are used. It should not normally be set
7588 by other means.
7590 @item
7591 The content of the @file{ada_object_path} file which is part of the GNAT
7592 installation tree and is used to store standard libraries such as the
7593 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
7594 specified.
7595 @ifclear vms
7596 @ref{Installing a library}
7597 @end ifclear
7598 @end enumerate
7600 @noindent
7601 In the binder the switch @option{^-I^/SEARCH^}
7602 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
7603 is used to specify both source and
7604 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
7605 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
7606 instead if you want to specify
7607 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
7608 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
7609 if you want to specify library paths
7610 only. This means that for the binder
7611 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
7612 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
7613 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7614 The binder generates the bind file (a C language source file) in the
7615 current working directory.
7617 @findex Ada
7618 @findex System
7619 @findex Interfaces
7620 @findex GNAT
7621 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7622 children make up the GNAT Run-Time Library, together with the package
7623 GNAT and its children, which contain a set of useful additional
7624 library functions provided by GNAT. The sources for these units are
7625 needed by the compiler and are kept together in one directory. The ALI
7626 files and object files generated by compiling the RTL are needed by the
7627 binder and the linker and are kept together in one directory, typically
7628 different from the directory containing the sources. In a normal
7629 installation, you need not specify these directory names when compiling
7630 or binding. Either the environment variables or the built-in defaults
7631 cause these files to be found.
7633 Besides simplifying access to the RTL, a major use of search paths is
7634 in compiling sources from multiple directories. This can make
7635 development environments much more flexible.
7637 @node Examples of gnatbind Usage
7638 @section Examples of @code{gnatbind} Usage
7640 @noindent
7641 This section contains a number of examples of using the GNAT binding
7642 utility @code{gnatbind}.
7644 @table @code
7645 @item gnatbind hello
7646 The main program @code{Hello} (source program in @file{hello.adb}) is
7647 bound using the standard switch settings. The generated main program is
7648 @file{b~hello.adb}. This is the normal, default use of the binder.
7650 @ifclear vms
7651 @item gnatbind hello -o mainprog.adb
7652 @end ifclear
7653 @ifset vms
7654 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7655 @end ifset
7656 The main program @code{Hello} (source program in @file{hello.adb}) is
7657 bound using the standard switch settings. The generated main program is
7658 @file{mainprog.adb} with the associated spec in
7659 @file{mainprog.ads}. Note that you must specify the body here not the
7660 spec, in the case where the output is in Ada. Note that if this option
7661 is used, then linking must be done manually, since gnatlink will not
7662 be able to find the generated file.
7664 @ifclear vms
7665 @item gnatbind main -C -o mainprog.c -x
7666 @end ifclear
7667 @ifset vms
7668 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7669 @end ifset
7670 The main program @code{Main} (source program in
7671 @file{main.adb}) is bound, excluding source files from the
7672 consistency checking, generating
7673 the file @file{mainprog.c}.
7675 @ifclear vms
7676 @item gnatbind -x main_program -C -o mainprog.c
7677 This command is exactly the same as the previous example. Switches may
7678 appear anywhere in the command line, and single letter switches may be
7679 combined into a single switch.
7680 @end ifclear
7682 @ifclear vms
7683 @item gnatbind -n math dbase -C -o ada-control.c
7684 @end ifclear
7685 @ifset vms
7686 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7687 @end ifset
7688 The main program is in a language other than Ada, but calls to
7689 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7690 to @code{gnatbind} generates the file @file{ada-control.c} containing
7691 the @code{adainit} and @code{adafinal} routines to be called before and
7692 after accessing the Ada units.
7693 @end table
7695 @c ------------------------------------
7696 @node Linking Using gnatlink
7697 @chapter Linking Using @command{gnatlink}
7698 @c ------------------------------------
7699 @findex gnatlink
7701 @noindent
7702 This chapter discusses @command{gnatlink}, a tool that links
7703 an Ada program and builds an executable file. This utility
7704 invokes the system linker ^(via the @command{gcc} command)^^
7705 with a correct list of object files and library references.
7706 @command{gnatlink} automatically determines the list of files and
7707 references for the Ada part of a program. It uses the binder file
7708 generated by the @command{gnatbind} to determine this list.
7710 @menu
7711 * Running gnatlink::
7712 * Switches for gnatlink::
7713 * Setting Stack Size from gnatlink::
7714 * Setting Heap Size from gnatlink::
7715 @end menu
7717 @node Running gnatlink
7718 @section Running @command{gnatlink}
7720 @noindent
7721 The form of the @command{gnatlink} command is
7723 @smallexample
7724 $ gnatlink [@var{switches}] @var{mainprog}[.ali]
7725            [@var{non-Ada objects}] [@var{linker options}]
7726 @end smallexample
7728 @noindent
7729 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
7730 non-Ada objects
7731 or linker options) may be in any order, provided that no non-Ada object may
7732 be mistaken for a main @file{ALI} file.
7733 Any file name @file{F} without the @file{.ali}
7734 extension will be taken as the main @file{ALI} file if a file exists
7735 whose name is the concatenation of @file{F} and @file{.ali}.
7737 @noindent
7738 @file{@var{mainprog}.ali} references the ALI file of the main program.
7739 The @file{.ali} extension of this file can be omitted. From this
7740 reference, @command{gnatlink} locates the corresponding binder file
7741 @file{b~@var{mainprog}.adb} and, using the information in this file along
7742 with the list of non-Ada objects and linker options, constructs a
7743 linker command file to create the executable.
7745 The arguments other than the @command{gnatlink} switches and the main
7746 @file{ALI} file are passed to the linker uninterpreted.
7747 They typically include the names of
7748 object files for units written in other languages than Ada and any library
7749 references required to resolve references in any of these foreign language
7750 units, or in @code{Import} pragmas in any Ada units.
7752 @var{linker options} is an optional list of linker specific
7753 switches.
7754 The default linker called by gnatlink is @var{gcc} which in
7755 turn calls the appropriate system linker.
7756 Standard options for the linker such as @option{-lmy_lib} or
7757 @option{-Ldir} can be added as is.
7758 For options that are not recognized by
7759 @var{gcc} as linker options, use the @var{gcc} switches @option{-Xlinker} or
7760 @option{-Wl,}.
7761 Refer to the GCC documentation for
7762 details. Here is an example showing how to generate a linker map:
7764 @ifclear vms
7765 @smallexample
7766 $ gnatlink my_prog -Wl,-Map,MAPFILE
7767 @end smallexample
7768 @end ifclear
7770 @ifset vms
7771 <<Need example for VMS>>
7772 @end ifset
7774 Using @var{linker options} it is possible to set the program stack and
7775 heap size. See @ref{Setting Stack Size from gnatlink} and
7776 @ref{Setting Heap Size from gnatlink}.
7778 @command{gnatlink} determines the list of objects required by the Ada
7779 program and prepends them to the list of objects passed to the linker.
7780 @command{gnatlink} also gathers any arguments set by the use of
7781 @code{pragma Linker_Options} and adds them to the list of arguments
7782 presented to the linker.
7784 @ifset vms
7785 @command{gnatlink} accepts the following types of extra files on the command
7786 line: objects (.OBJ), libraries (.OLB), sharable images (.EXE), and
7787 options files (.OPT). These are recognized and handled according to their
7788 extension.
7789 @end ifset
7791 @node Switches for gnatlink
7792 @section Switches for @command{gnatlink}
7794 @noindent
7795 The following switches are available with the @command{gnatlink} utility:
7797 @table @option
7798 @c !sort!
7800 @item ^-A^/BIND_FILE=ADA^
7801 @cindex @option{^-A^/BIND_FILE=ADA^} (@command{gnatlink})
7802 The binder has generated code in Ada. This is the default.
7804 @item ^-C^/BIND_FILE=C^
7805 @cindex @option{^-C^/BIND_FILE=C^} (@command{gnatlink})
7806 If instead of generating a file in Ada, the binder has generated one in
7807 C, then the linker needs to know about it. Use this switch to signal
7808 to @command{gnatlink} that the binder has generated C code rather than
7809 Ada code.
7811 @item ^-f^/FORCE_OBJECT_FILE_LIST^
7812 @cindex Command line length
7813 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
7814 On some targets, the command line length is limited, and @command{gnatlink}
7815 will generate a separate file for the linker if the list of object files
7816 is too long.
7817 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
7818 to be generated even if
7819 the limit is not exceeded. This is useful in some cases to deal with
7820 special situations where the command line length is exceeded.
7822 @item ^-g^/DEBUG^
7823 @cindex Debugging information, including
7824 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
7825 The option to include debugging information causes the Ada bind file (in
7826 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7827 @option{^-g^/DEBUG^}.
7828 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7829 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7830 Without @option{^-g^/DEBUG^}, the binder removes these files by
7831 default. The same procedure apply if a C bind file was generated using
7832 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
7833 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7835 @item ^-n^/NOCOMPILE^
7836 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
7837 Do not compile the file generated by the binder. This may be used when
7838 a link is rerun with different options, but there is no need to recompile
7839 the binder file.
7841 @item ^-v^/VERBOSE^
7842 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
7843 Causes additional information to be output, including a full list of the
7844 included object files. This switch option is most useful when you want
7845 to see what set of object files are being used in the link step.
7847 @item ^-v -v^/VERBOSE/VERBOSE^
7848 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
7849 Very verbose mode. Requests that the compiler operate in verbose mode when
7850 it compiles the binder file, and that the system linker run in verbose mode.
7852 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7853 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
7854 @var{exec-name} specifies an alternate name for the generated
7855 executable program. If this switch is omitted, the executable has the same
7856 name as the main unit. For example, @code{gnatlink try.ali} creates
7857 an executable called @file{^try^TRY.EXE^}.
7859 @ifclear vms
7860 @item -b @var{target}
7861 @cindex @option{-b} (@command{gnatlink})
7862 Compile your program to run on @var{target}, which is the name of a
7863 system configuration. You must have a GNAT cross-compiler built if
7864 @var{target} is not the same as your host system.
7866 @item -B@var{dir}
7867 @cindex @option{-B} (@command{gnatlink})
7868 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7869 from @var{dir} instead of the default location. Only use this switch
7870 when multiple versions of the GNAT compiler are available. See the
7871 @command{gcc} manual page for further details. You would normally use the
7872 @option{-b} or @option{-V} switch instead.
7874 @item --GCC=@var{compiler_name}
7875 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
7876 Program used for compiling the binder file. The default is
7877 @command{gcc}. You need to use quotes around @var{compiler_name} if
7878 @code{compiler_name} contains spaces or other separator characters. As
7879 an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to use
7880 @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
7881 inserted after your command name. Thus in the above example the compiler
7882 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
7883 If several @option{--GCC=compiler_name} are used, only the last
7884 @var{compiler_name} is taken into account. However, all the additional
7885 switches are also taken into account. Thus,
7886 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7887 @option{--GCC="bar -x -y -z -t"}.
7889 @item --LINK=@var{name}
7890 @cindex @option{--LINK=} (@command{gnatlink})
7891 @var{name} is the name of the linker to be invoked. This is especially
7892 useful in mixed language programs since languages such as C++ require
7893 their own linker to be used. When this switch is omitted, the default
7894 name for the linker is @command{gcc}. When this switch is used, the
7895 specified linker is called instead of @command{gcc} with exactly the same
7896 parameters that would have been passed to @command{gcc} so if the desired
7897 linker requires different parameters it is necessary to use a wrapper
7898 script that massages the parameters before invoking the real linker. It
7899 may be useful to control the exact invocation by using the verbose
7900 switch.
7902 @end ifclear
7904 @ifset vms
7905 @item /DEBUG=TRACEBACK
7906 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
7907 This qualifier causes sufficient information to be included in the
7908 executable file to allow a traceback, but does not include the full
7909 symbol information needed by the debugger.
7911 @item /IDENTIFICATION="<string>"
7912 @code{"<string>"} specifies the string to be stored in the image file
7913 identification field in the image header.
7914 It overrides any pragma @code{Ident} specified string.
7916 @item /NOINHIBIT-EXEC
7917 Generate the executable file even if there are linker warnings.
7919 @item /NOSTART_FILES
7920 Don't link in the object file containing the ``main'' transfer address.
7921 Used when linking with a foreign language main program compiled with a
7922 Digital compiler.
7924 @item /STATIC
7925 Prefer linking with object libraries over sharable images, even without
7926 /DEBUG.
7927 @end ifset
7929 @end table
7931 @node Setting Stack Size from gnatlink
7932 @section Setting Stack Size from @command{gnatlink}
7934 @noindent
7935 Under Windows systems, it is possible to specify the program stack size from
7936 @command{gnatlink} using either:
7938 @itemize @bullet
7940 @item using @option{-Xlinker} linker option
7942 @smallexample
7943 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7944 @end smallexample
7946 This sets the stack reserve size to 0x10000 bytes and the stack commit
7947 size to 0x1000 bytes.
7949 @item using @option{-Wl} linker option
7951 @smallexample
7952 $ gnatlink hello -Wl,--stack=0x1000000
7953 @end smallexample
7955 This sets the stack reserve size to 0x1000000 bytes. Note that with
7956 @option{-Wl} option it is not possible to set the stack commit size
7957 because the coma is a separator for this option.
7959 @end itemize
7961 @node Setting Heap Size from gnatlink
7962 @section Setting Heap Size from @command{gnatlink}
7964 @noindent
7965 Under Windows systems, it is possible to specify the program heap size from
7966 @command{gnatlink} using either:
7968 @itemize @bullet
7970 @item using @option{-Xlinker} linker option
7972 @smallexample
7973 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7974 @end smallexample
7976 This sets the heap reserve size to 0x10000 bytes and the heap commit
7977 size to 0x1000 bytes.
7979 @item using @option{-Wl} linker option
7981 @smallexample
7982 $ gnatlink hello -Wl,--heap=0x1000000
7983 @end smallexample
7985 This sets the heap reserve size to 0x1000000 bytes. Note that with
7986 @option{-Wl} option it is not possible to set the heap commit size
7987 because the coma is a separator for this option.
7989 @end itemize
7991 @node The GNAT Make Program gnatmake
7992 @chapter The GNAT Make Program @command{gnatmake}
7993 @findex gnatmake
7995 @menu
7996 * Running gnatmake::
7997 * Switches for gnatmake::
7998 * Mode Switches for gnatmake::
7999 * Notes on the Command Line::
8000 * How gnatmake Works::
8001 * Examples of gnatmake Usage::
8002 @end menu
8003 @noindent
8004 A typical development cycle when working on an Ada program consists of
8005 the following steps:
8007 @enumerate
8008 @item
8009 Edit some sources to fix bugs.
8011 @item
8012 Add enhancements.
8014 @item
8015 Compile all sources affected.
8017 @item
8018 Rebind and relink.
8020 @item
8021 Test.
8022 @end enumerate
8024 @noindent
8025 The third step can be tricky, because not only do the modified files
8026 @cindex Dependency rules
8027 have to be compiled, but any files depending on these files must also be
8028 recompiled. The dependency rules in Ada can be quite complex, especially
8029 in the presence of overloading, @code{use} clauses, generics and inlined
8030 subprograms.
8032 @command{gnatmake} automatically takes care of the third and fourth steps
8033 of this process. It determines which sources need to be compiled,
8034 compiles them, and binds and links the resulting object files.
8036 Unlike some other Ada make programs, the dependencies are always
8037 accurately recomputed from the new sources. The source based approach of
8038 the GNAT compilation model makes this possible. This means that if
8039 changes to the source program cause corresponding changes in
8040 dependencies, they will always be tracked exactly correctly by
8041 @command{gnatmake}.
8043 @node Running gnatmake
8044 @section Running @command{gnatmake}
8046 @noindent
8047 The usual form of the @command{gnatmake} command is
8049 @smallexample
8050 $ gnatmake [@var{switches}] @var{file_name}
8051       [@var{file_names}] [@var{mode_switches}]
8052 @end smallexample
8054 @noindent
8055 The only required argument is one @var{file_name}, which specifies
8056 a compilation unit that is a main program. Several @var{file_names} can be
8057 specified: this will result in several executables being built.
8058 If @code{switches} are present, they can be placed before the first
8059 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
8060 If @var{mode_switches} are present, they must always be placed after
8061 the last @var{file_name} and all @code{switches}.
8063 If you are using standard file extensions (.adb and .ads), then the
8064 extension may be omitted from the @var{file_name} arguments. However, if
8065 you are using non-standard extensions, then it is required that the
8066 extension be given. A relative or absolute directory path can be
8067 specified in a @var{file_name}, in which case, the input source file will
8068 be searched for in the specified directory only. Otherwise, the input
8069 source file will first be searched in the directory where
8070 @command{gnatmake} was invoked and if it is not found, it will be search on
8071 the source path of the compiler as described in
8072 @ref{Search Paths and the Run-Time Library (RTL)}.
8074 All @command{gnatmake} output (except when you specify
8075 @option{^-M^/DEPENDENCIES_LIST^}) is to
8076 @file{stderr}. The output produced by the
8077 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
8078 @file{stdout}.
8080 @node Switches for gnatmake
8081 @section Switches for @command{gnatmake}
8083 @noindent
8084 You may specify any of the following switches to @command{gnatmake}:
8086 @table @option
8087 @c !sort!
8088 @ifclear vms
8089 @item --GCC=@var{compiler_name}
8090 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
8091 Program used for compiling. The default is `@command{gcc}'. You need to use
8092 quotes around @var{compiler_name} if @code{compiler_name} contains
8093 spaces or other separator characters. As an example @option{--GCC="foo -x
8094 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
8095 compiler. Note that switch @option{-c} is always inserted after your
8096 command name. Thus in the above example the compiler command that will
8097 be used by @command{gnatmake} will be @code{foo -c -x -y}.
8098 If several @option{--GCC=compiler_name} are used, only the last
8099 @var{compiler_name} is taken into account. However, all the additional
8100 switches are also taken into account. Thus,
8101 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
8102 @option{--GCC="bar -x -y -z -t"}.
8104 @item --GNATBIND=@var{binder_name}
8105 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
8106 Program used for binding. The default is `@code{gnatbind}'. You need to
8107 use quotes around @var{binder_name} if @var{binder_name} contains spaces
8108 or other separator characters. As an example @option{--GNATBIND="bar -x
8109 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
8110 binder. Binder switches that are normally appended by @command{gnatmake} to
8111 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
8113 @item --GNATLINK=@var{linker_name}
8114 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
8115 Program used for linking. The default is `@command{gnatlink}'. You need to
8116 use quotes around @var{linker_name} if @var{linker_name} contains spaces
8117 or other separator characters. As an example @option{--GNATLINK="lan -x
8118 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
8119 linker. Linker switches that are normally appended by @command{gnatmake} to
8120 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
8122 @end ifclear
8124 @item ^-a^/ALL_FILES^
8125 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
8126 Consider all files in the make process, even the GNAT internal system
8127 files (for example, the predefined Ada library files), as well as any
8128 locked files. Locked files are files whose ALI file is write-protected.
8129 By default,
8130 @command{gnatmake} does not check these files,
8131 because the assumption is that the GNAT internal files are properly up
8132 to date, and also that any write protected ALI files have been properly
8133 installed. Note that if there is an installation problem, such that one
8134 of these files is not up to date, it will be properly caught by the
8135 binder.
8136 You may have to specify this switch if you are working on GNAT
8137 itself. The switch @option{^-a^/ALL_FILES^} is also useful
8138 in conjunction with @option{^-f^/FORCE_COMPILE^}
8139 if you need to recompile an entire application,
8140 including run-time files, using special configuration pragmas,
8141 such as a @code{Normalize_Scalars} pragma.
8143 By default
8144 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
8145 internal files with
8146 @ifclear vms
8147 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
8148 @end ifclear
8149 @ifset vms
8150 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
8151 @end ifset
8153 @item ^-b^/ACTIONS=BIND^
8154 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
8155 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
8156 compilation and binding, but no link.
8157 Can be combined with @option{^-l^/ACTIONS=LINK^}
8158 to do binding and linking. When not combined with
8159 @option{^-c^/ACTIONS=COMPILE^}
8160 all the units in the closure of the main program must have been previously
8161 compiled and must be up to date. The root unit specified by @var{file_name}
8162 may be given without extension, with the source extension or, if no GNAT
8163 Project File is specified, with the ALI file extension.
8165 @item ^-c^/ACTIONS=COMPILE^
8166 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
8167 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
8168 is also specified. Do not perform linking, except if both
8169 @option{^-b^/ACTIONS=BIND^} and
8170  @option{^-l^/ACTIONS=LINK^} are also specified.
8171 If the root unit specified by @var{file_name} is not a main unit, this is the
8172 default. Otherwise @command{gnatmake} will attempt binding and linking
8173 unless all objects are up to date and the executable is more recent than
8174 the objects.
8176 @item ^-C^/MAPPING^
8177 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
8178 Use a temporary mapping file. A mapping file is a way to communicate to the
8179 compiler two mappings: from unit names to file names (without any directory
8180 information) and from file names to path names (with full directory
8181 information). These mappings are used by the compiler to short-circuit the path
8182 search. When @command{gnatmake} is invoked with this switch, it will create
8183 a temporary mapping file, initially populated by the project manager,
8184 if @option{^-P^/PROJECT_FILE^} is used, otherwise initially empty.
8185 Each invocation of the compiler will add the newly accessed sources to the
8186 mapping file. This will improve the source search during the next invocation
8187 of the compiler.
8189 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
8190 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
8191 Use a specific mapping file. The file, specified as a path name (absolute or
8192 relative) by this switch, should already exist, otherwise the switch is
8193 ineffective. The specified mapping file will be communicated to the compiler.
8194 This switch is not compatible with a project file
8195 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
8196 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
8198 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
8199 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
8200 Put all object files and ALI file in directory @var{dir}.
8201 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
8202 and ALI files go in the current working directory.
8204 This switch cannot be used when using a project file.
8206 @ifclear vms
8207 @item -eL
8208 @cindex @option{-eL} (@command{gnatmake})
8209 Follow all symbolic links when processing project files.
8210 @end ifclear
8212 @item ^-f^/FORCE_COMPILE^
8213 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
8214 Force recompilations. Recompile all sources, even though some object
8215 files may be up to date, but don't recompile predefined or GNAT internal
8216 files or locked files (files with a write-protected ALI file),
8217 unless the @option{^-a^/ALL_FILES^} switch is also specified.
8219 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
8220 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
8221 When using project files, if some errors or warnings are detected during
8222 parsing and verbose mode is not in effect (no use of switch
8223 ^-v^/VERBOSE^), then error lines start with the full path name of the project
8224 file, rather than its simple file name.
8226 @item ^-i^/IN_PLACE^
8227 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
8228 In normal mode, @command{gnatmake} compiles all object files and ALI files
8229 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
8230 then instead object files and ALI files that already exist are overwritten
8231 in place. This means that once a large project is organized into separate
8232 directories in the desired manner, then @command{gnatmake} will automatically
8233 maintain and update this organization. If no ALI files are found on the
8234 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
8235 the new object and ALI files are created in the
8236 directory containing the source being compiled. If another organization
8237 is desired, where objects and sources are kept in different directories,
8238 a useful technique is to create dummy ALI files in the desired directories.
8239 When detecting such a dummy file, @command{gnatmake} will be forced to
8240 recompile the corresponding source file, and it will be put the resulting
8241 object and ALI files in the directory where it found the dummy file.
8243 @item ^-j^/PROCESSES=^@var{n}
8244 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
8245 @cindex Parallel make
8246 Use @var{n} processes to carry out the (re)compilations. On a
8247 multiprocessor machine compilations will occur in parallel. In the
8248 event of compilation errors, messages from various compilations might
8249 get interspersed (but @command{gnatmake} will give you the full ordered
8250 list of failing compiles at the end). If this is problematic, rerun
8251 the make process with n set to 1 to get a clean list of messages.
8253 @item ^-k^/CONTINUE_ON_ERROR^
8254 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
8255 Keep going. Continue as much as possible after a compilation error. To
8256 ease the programmer's task in case of compilation errors, the list of
8257 sources for which the compile fails is given when @command{gnatmake}
8258 terminates.
8260 If @command{gnatmake} is invoked with several @file{file_names} and with this
8261 switch, if there are compilation errors when building an executable,
8262 @command{gnatmake} will not attempt to build the following executables.
8264 @item ^-l^/ACTIONS=LINK^
8265 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
8266 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
8267 and linking. Linking will not be performed if combined with
8268 @option{^-c^/ACTIONS=COMPILE^}
8269 but not with @option{^-b^/ACTIONS=BIND^}.
8270 When not combined with @option{^-b^/ACTIONS=BIND^}
8271 all the units in the closure of the main program must have been previously
8272 compiled and must be up to date, and the main program needs to have been bound.
8273 The root unit specified by @var{file_name}
8274 may be given without extension, with the source extension or, if no GNAT
8275 Project File is specified, with the ALI file extension.
8277 @item ^-m^/MINIMAL_RECOMPILATION^
8278 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
8279 Specify that the minimum necessary amount of recompilations
8280 be performed. In this mode @command{gnatmake} ignores time
8281 stamp differences when the only
8282 modifications to a source file consist in adding/removing comments,
8283 empty lines, spaces or tabs. This means that if you have changed the
8284 comments in a source file or have simply reformatted it, using this
8285 switch will tell gnatmake not to recompile files that depend on it
8286 (provided other sources on which these files depend have undergone no
8287 semantic modifications). Note that the debugging information may be
8288 out of date with respect to the sources if the @option{-m} switch causes
8289 a compilation to be switched, so the use of this switch represents a
8290 trade-off between compilation time and accurate debugging information.
8292 @item ^-M^/DEPENDENCIES_LIST^
8293 @cindex Dependencies, producing list
8294 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
8295 Check if all objects are up to date. If they are, output the object
8296 dependences to @file{stdout} in a form that can be directly exploited in
8297 a @file{Makefile}. By default, each source file is prefixed with its
8298 (relative or absolute) directory name. This name is whatever you
8299 specified in the various @option{^-aI^/SOURCE_SEARCH^}
8300 and @option{^-I^/SEARCH^} switches. If you use
8301 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
8302 @option{^-q^/QUIET^}
8303 (see below), only the source file names,
8304 without relative paths, are output. If you just specify the
8305 @option{^-M^/DEPENDENCIES_LIST^}
8306 switch, dependencies of the GNAT internal system files are omitted. This
8307 is typically what you want. If you also specify
8308 the @option{^-a^/ALL_FILES^} switch,
8309 dependencies of the GNAT internal files are also listed. Note that
8310 dependencies of the objects in external Ada libraries (see switch
8311 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
8312 are never reported.
8314 @item ^-n^/DO_OBJECT_CHECK^
8315 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
8316 Don't compile, bind, or link. Checks if all objects are up to date.
8317 If they are not, the full name of the first file that needs to be
8318 recompiled is printed.
8319 Repeated use of this option, followed by compiling the indicated source
8320 file, will eventually result in recompiling all required units.
8322 @item ^-o ^/EXECUTABLE=^@var{exec_name}
8323 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
8324 Output executable name. The name of the final executable program will be
8325 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
8326 name for the executable will be the name of the input file in appropriate form
8327 for an executable file on the host system.
8329 This switch cannot be used when invoking @command{gnatmake} with several
8330 @file{file_names}.
8332 @item ^-P^/PROJECT_FILE=^@var{project}
8333 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
8334 Use project file @var{project}. Only one such switch can be used.
8335 @xref{gnatmake and Project Files}.
8337 @item ^-q^/QUIET^
8338 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
8339 Quiet. When this flag is not set, the commands carried out by
8340 @command{gnatmake} are displayed.
8342 @item ^-s^/SWITCH_CHECK/^
8343 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
8344 Recompile if compiler switches have changed since last compilation.
8345 All compiler switches but -I and -o are taken into account in the
8346 following way:
8347 orders between different ``first letter'' switches are ignored, but
8348 orders between same switches are taken into account. For example,
8349 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
8350 is equivalent to @option{-O -g}.
8352 This switch is recommended when Integrated Preprocessing is used.
8354 @item ^-u^/UNIQUE^
8355 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
8356 Unique. Recompile at most the main files. It implies -c. Combined with
8357 -f, it is equivalent to calling the compiler directly. Note that using
8358 ^-u^/UNIQUE^ with a project file and no main has a special meaning
8359 (@pxref{Project Files and Main Subprograms}).
8361 @item ^-U^/ALL_PROJECTS^
8362 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
8363 When used without a project file or with one or several mains on the command
8364 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
8365 on the command line, all sources of all project files are checked and compiled
8366 if not up to date, and libraries are rebuilt, if necessary.
8368 @item ^-v^/REASONS^
8369 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
8370 Verbose. Display the reason for all recompilations @command{gnatmake}
8371 decides are necessary.
8373 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
8374 Indicate the verbosity of the parsing of GNAT project files.
8375 @xref{Switches Related to Project Files}.
8377 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
8378 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
8379 Indicate that sources that are not part of any Project File may be compiled.
8380 Normally, when using Project Files, only sources that are part of a Project
8381 File may be compile. When this switch is used, a source outside of all Project
8382 Files may be compiled. The ALI file and the object file will be put in the
8383 object directory of the main Project. The compilation switches used will only
8384 be those specified on the command line.
8386 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
8387 Indicate that external variable @var{name} has the value @var{value}.
8388 The Project Manager will use this value for occurrences of
8389 @code{external(name)} when parsing the project file.
8390 @xref{Switches Related to Project Files}.
8392 @item ^-z^/NOMAIN^
8393 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
8394 No main subprogram. Bind and link the program even if the unit name
8395 given on the command line is a package name. The resulting executable
8396 will execute the elaboration routines of the package and its closure,
8397 then the finalization routines.
8399 @item ^-g^/DEBUG^
8400 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
8401 Enable debugging. This switch is simply passed to the compiler and to the
8402 linker.
8404 @end table
8406 @table @asis
8407 @item @command{gcc} @asis{switches}
8408 @ifclear vms
8409 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
8410 is passed to @command{gcc} (e.g. @option{-O}, @option{-gnato,} etc.)
8411 @end ifclear
8412 @ifset vms
8413 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8414 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8415 automatically treated as a compiler switch, and passed on to all
8416 compilations that are carried out.
8417 @end ifset
8418 @end table
8420 @noindent
8421 Source and library search path switches:
8423 @table @option
8424 @c !sort!
8425 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8426 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
8427 When looking for source files also look in directory @var{dir}.
8428 The order in which source files search is undertaken is
8429 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8431 @item ^-aL^/SKIP_MISSING=^@var{dir}
8432 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
8433 Consider @var{dir} as being an externally provided Ada library.
8434 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
8435 files have been located in directory @var{dir}. This allows you to have
8436 missing bodies for the units in @var{dir} and to ignore out of date bodies
8437 for the same units. You still need to specify
8438 the location of the specs for these units by using the switches
8439 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
8440 or @option{^-I^/SEARCH=^@var{dir}}.
8441 Note: this switch is provided for compatibility with previous versions
8442 of @command{gnatmake}. The easier method of causing standard libraries
8443 to be excluded from consideration is to write-protect the corresponding
8444 ALI files.
8446 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8447 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
8448 When searching for library and object files, look in directory
8449 @var{dir}. The order in which library files are searched is described in
8450 @ref{Search Paths for gnatbind}.
8452 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8453 @cindex Search paths, for @command{gnatmake}
8454 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
8455 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
8456 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8458 @item ^-I^/SEARCH=^@var{dir}
8459 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
8460 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
8461 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8463 @item ^-I-^/NOCURRENT_DIRECTORY^
8464 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
8465 @cindex Source files, suppressing search
8466 Do not look for source files in the directory containing the source
8467 file named in the command line.
8468 Do not look for ALI or object files in the directory
8469 where @command{gnatmake} was invoked.
8471 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8472 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
8473 @cindex Linker libraries
8474 Add directory @var{dir} to the list of directories in which the linker
8475 will search for libraries. This is equivalent to
8476 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8477 @ifclear vms
8478 Furthermore, under Windows, the sources pointed to by the libraries path
8479 set in the registry are not searched for.
8480 @end ifclear
8482 @item -nostdinc
8483 @cindex @option{-nostdinc} (@command{gnatmake})
8484 Do not look for source files in the system default directory.
8486 @item -nostdlib
8487 @cindex @option{-nostdlib} (@command{gnatmake})
8488 Do not look for library files in the system default directory.
8490 @item --RTS=@var{rts-path}
8491 @cindex @option{--RTS} (@command{gnatmake})
8492 Specifies the default location of the runtime library. GNAT looks for the
8493 runtime
8494 in the following directories, and stops as soon as a valid runtime is found
8495 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
8496 @file{ada_object_path} present):
8498 @itemize @bullet
8499 @item <current directory>/$rts_path
8501 @item <default-search-dir>/$rts_path
8503 @item <default-search-dir>/rts-$rts_path
8504 @end itemize
8506 @noindent
8507 The selected path is handled like a normal RTS path.
8509 @end table
8511 @node Mode Switches for gnatmake
8512 @section Mode Switches for @command{gnatmake}
8514 @noindent
8515 The mode switches (referred to as @code{mode_switches}) allow the
8516 inclusion of switches that are to be passed to the compiler itself, the
8517 binder or the linker. The effect of a mode switch is to cause all
8518 subsequent switches up to the end of the switch list, or up to the next
8519 mode switch, to be interpreted as switches to be passed on to the
8520 designated component of GNAT.
8522 @table @option
8523 @c !sort!
8524 @item -cargs @var{switches}
8525 @cindex @option{-cargs} (@command{gnatmake})
8526 Compiler switches. Here @var{switches} is a list of switches
8527 that are valid switches for @command{gcc}. They will be passed on to
8528 all compile steps performed by @command{gnatmake}.
8530 @item -bargs @var{switches}
8531 @cindex @option{-bargs} (@command{gnatmake})
8532 Binder switches. Here @var{switches} is a list of switches
8533 that are valid switches for @code{gnatbind}. They will be passed on to
8534 all bind steps performed by @command{gnatmake}.
8536 @item -largs @var{switches}
8537 @cindex @option{-largs} (@command{gnatmake})
8538 Linker switches. Here @var{switches} is a list of switches
8539 that are valid switches for @command{gnatlink}. They will be passed on to
8540 all link steps performed by @command{gnatmake}.
8542 @item -margs @var{switches}
8543 @cindex @option{-margs} (@command{gnatmake})
8544 Make switches. The switches are directly interpreted by @command{gnatmake},
8545 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
8546 or @option{-largs}.
8547 @end table
8549 @node Notes on the Command Line
8550 @section Notes on the Command Line
8552 @noindent
8553 This section contains some additional useful notes on the operation
8554 of the @command{gnatmake} command.
8556 @itemize @bullet
8557 @item
8558 @cindex Recompilation, by @command{gnatmake}
8559 If @command{gnatmake} finds no ALI files, it recompiles the main program
8560 and all other units required by the main program.
8561 This means that @command{gnatmake}
8562 can be used for the initial compile, as well as during subsequent steps of
8563 the development cycle.
8565 @item
8566 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8567 is a subunit or body of a generic unit, @command{gnatmake} recompiles
8568 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8569 warning.
8571 @item
8572 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
8573 is used to specify both source and
8574 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8575 instead if you just want to specify
8576 source paths only and @option{^-aO^/OBJECT_SEARCH^}
8577 if you want to specify library paths
8578 only.
8580 @item
8581 @command{gnatmake} will ignore any files whose ALI file is write-protected.
8582 This may conveniently be used to exclude standard libraries from
8583 consideration and in particular it means that the use of the
8584 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
8585 unless @option{^-a^/ALL_FILES^} is also specified.
8587 @item
8588 @command{gnatmake} has been designed to make the use of Ada libraries
8589 particularly convenient. Assume you have an Ada library organized
8590 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8591 of your Ada compilation units,
8592 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
8593 specs of these units, but no bodies. Then to compile a unit
8594 stored in @code{main.adb}, which uses this Ada library you would just type
8596 @smallexample
8597 @ifclear vms
8598 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8599 @end ifclear
8600 @ifset vms
8601 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
8602            /SKIP_MISSING=@i{[OBJ_DIR]} main
8603 @end ifset
8604 @end smallexample
8606 @item
8607 Using @command{gnatmake} along with the
8608 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8609 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8610 this switch,
8611 you can update the comments/format of your
8612 source files without having to recompile everything. Note, however, that
8613 adding or deleting lines in a source files may render its debugging
8614 info obsolete. If the file in question is a spec, the impact is rather
8615 limited, as that debugging info will only be useful during the
8616 elaboration phase of your program. For bodies the impact can be more
8617 significant. In all events, your debugger will warn you if a source file
8618 is more recent than the corresponding object, and alert you to the fact
8619 that the debugging information may be out of date.
8620 @end itemize
8622 @node How gnatmake Works
8623 @section How @command{gnatmake} Works
8625 @noindent
8626 Generally @command{gnatmake} automatically performs all necessary
8627 recompilations and you don't need to worry about how it works. However,
8628 it may be useful to have some basic understanding of the @command{gnatmake}
8629 approach and in particular to understand how it uses the results of
8630 previous compilations without incorrectly depending on them.
8632 First a definition: an object file is considered @dfn{up to date} if the
8633 corresponding ALI file exists and if all the source files listed in the
8634 dependency section of this ALI file have time stamps matching those in
8635 the ALI file. This means that neither the source file itself nor any
8636 files that it depends on have been modified, and hence there is no need
8637 to recompile this file.
8639 @command{gnatmake} works by first checking if the specified main unit is up
8640 to date. If so, no compilations are required for the main unit. If not,
8641 @command{gnatmake} compiles the main program to build a new ALI file that
8642 reflects the latest sources. Then the ALI file of the main unit is
8643 examined to find all the source files on which the main program depends,
8644 and @command{gnatmake} recursively applies the above procedure on all these
8645 files.
8647 This process ensures that @command{gnatmake} only trusts the dependencies
8648 in an existing ALI file if they are known to be correct. Otherwise it
8649 always recompiles to determine a new, guaranteed accurate set of
8650 dependencies. As a result the program is compiled ``upside down'' from what may
8651 be more familiar as the required order of compilation in some other Ada
8652 systems. In particular, clients are compiled before the units on which
8653 they depend. The ability of GNAT to compile in any order is critical in
8654 allowing an order of compilation to be chosen that guarantees that
8655 @command{gnatmake} will recompute a correct set of new dependencies if
8656 necessary.
8658 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
8659 imported by several of the executables, it will be recompiled at most once.
8661 Note: when using non-standard naming conventions
8662 (@pxref{Using Other File Names}), changing through a configuration pragmas
8663 file the version of a source and invoking @command{gnatmake} to recompile may
8664 have no effect, if the previous version of the source is still accessible
8665 by @command{gnatmake}. It may be necessary to use the switch
8666 ^-f^/FORCE_COMPILE^.
8668 @node Examples of gnatmake Usage
8669 @section Examples of @command{gnatmake} Usage
8671 @table @code
8672 @item gnatmake hello.adb
8673 Compile all files necessary to bind and link the main program
8674 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8675 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8677 @item gnatmake main1 main2 main3
8678 Compile all files necessary to bind and link the main programs
8679 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8680 (containing unit @code{Main2}) and @file{main3.adb}
8681 (containing unit @code{Main3}) and bind and link the resulting object files
8682 to generate three executable files @file{^main1^MAIN1.EXE^},
8683 @file{^main2^MAIN2.EXE^}
8684 and @file{^main3^MAIN3.EXE^}.
8686 @ifclear vms
8687 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8688 @end ifclear
8690 @ifset vms
8691 @item gnatmake Main_Unit /QUIET
8692    /COMPILER_QUALIFIERS /OPTIMIZE=ALL
8693    /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8694 @end ifset
8695 Compile all files necessary to bind and link the main program unit
8696 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8697 be done with optimization level 2 and the order of elaboration will be
8698 listed by the binder. @command{gnatmake} will operate in quiet mode, not
8699 displaying commands it is executing.
8700 @end table
8702 @c *************************
8703 @node Improving Performance
8704 @chapter Improving Performance
8705 @cindex Improving performance
8707 @noindent
8708 This chapter presents several topics related to program performance.
8709 It first describes some of the tradeoffs that need to be considered
8710 and some of the techniques for making your program run faster.
8711 It then documents the @command{gnatelim} tool, which can reduce
8712 the size of program executables.
8714 @ifnottex
8715 @menu
8716 * Performance Considerations::
8717 * Reducing the Size of Ada Executables with gnatelim::
8718 @end menu
8719 @end ifnottex
8721 @c *****************************
8722 @node Performance Considerations
8723 @section Performance Considerations
8725 @noindent
8726 The GNAT system provides a number of options that allow a trade-off
8727 between
8729 @itemize @bullet
8730 @item
8731 performance of the generated code
8733 @item
8734 speed of compilation
8736 @item
8737 minimization of dependences and recompilation
8739 @item
8740 the degree of run-time checking.
8741 @end itemize
8743 @noindent
8744 The defaults (if no options are selected) aim at improving the speed
8745 of compilation and minimizing dependences, at the expense of performance
8746 of the generated code:
8748 @itemize @bullet
8749 @item
8750 no optimization
8752 @item
8753 no inlining of subprogram calls
8755 @item
8756 all run-time checks enabled except overflow and elaboration checks
8757 @end itemize
8759 @noindent
8760 These options are suitable for most program development purposes. This
8761 chapter describes how you can modify these choices, and also provides
8762 some guidelines on debugging optimized code.
8764 @menu
8765 * Controlling Run-Time Checks::
8766 * Use of Restrictions::
8767 * Optimization Levels::
8768 * Debugging Optimized Code::
8769 * Inlining of Subprograms::
8770 * Optimization and Strict Aliasing::
8771 @ifset vms
8772 * Coverage Analysis::
8773 @end ifset
8774 @end menu
8776 @node Controlling Run-Time Checks
8777 @subsection Controlling Run-Time Checks
8779 @noindent
8780 By default, GNAT generates all run-time checks, except arithmetic overflow
8781 checking for integer operations and checks for access before elaboration on
8782 subprogram calls. The latter are not required in default mode, because all
8783 necessary checking is done at compile time.
8784 @cindex @option{-gnatp} (@command{gcc})
8785 @cindex @option{-gnato} (@command{gcc})
8786 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
8787 be modified. @xref{Run-Time Checks}.
8789 Our experience is that the default is suitable for most development
8790 purposes.
8792 We treat integer overflow specially because these
8793 are quite expensive and in our experience are not as important as other
8794 run-time checks in the development process. Note that division by zero
8795 is not considered an overflow check, and divide by zero checks are
8796 generated where required by default.
8798 Elaboration checks are off by default, and also not needed by default, since
8799 GNAT uses a static elaboration analysis approach that avoids the need for
8800 run-time checking. This manual contains a full chapter discussing the issue
8801 of elaboration checks, and if the default is not satisfactory for your use,
8802 you should read this chapter.
8804 For validity checks, the minimal checks required by the Ada Reference
8805 Manual (for case statements and assignments to array elements) are on
8806 by default. These can be suppressed by use of the @option{-gnatVn} switch.
8807 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
8808 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
8809 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
8810 are also suppressed entirely if @option{-gnatp} is used.
8812 @cindex Overflow checks
8813 @cindex Checks, overflow
8814 @findex Suppress
8815 @findex Unsuppress
8816 @cindex pragma Suppress
8817 @cindex pragma Unsuppress
8818 Note that the setting of the switches controls the default setting of
8819 the checks. They may be modified using either @code{pragma Suppress} (to
8820 remove checks) or @code{pragma Unsuppress} (to add back suppressed
8821 checks) in the program source.
8823 @node Use of Restrictions
8824 @subsection Use of Restrictions
8826 @noindent
8827 The use of pragma Restrictions allows you to control which features are
8828 permitted in your program. Apart from the obvious point that if you avoid
8829 relatively expensive features like finalization (enforceable by the use
8830 of pragma Restrictions (No_Finalization), the use of this pragma does not
8831 affect the generated code in most cases.
8833 One notable exception to this rule is that the possibility of task abort
8834 results in some distributed overhead, particularly if finalization or
8835 exception handlers are used. The reason is that certain sections of code
8836 have to be marked as non-abortable.
8838 If you use neither the @code{abort} statement, nor asynchronous transfer
8839 of control (@code{select .. then abort}), then this distributed overhead
8840 is removed, which may have a general positive effect in improving
8841 overall performance.  Especially code involving frequent use of tasking
8842 constructs and controlled types will show much improved performance.
8843 The relevant restrictions pragmas are
8845 @smallexample
8846    pragma Restrictions (No_Abort_Statements);
8847    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
8848 @end smallexample
8850 @noindent
8851 It is recommended that these restriction pragmas be used if possible. Note
8852 that this also means that you can write code without worrying about the
8853 possibility of an immediate abort at any point.
8855 @node Optimization Levels
8856 @subsection Optimization Levels
8857 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
8859 @noindent
8860 The default is optimization off. This results in the fastest compile
8861 times, but GNAT makes absolutely no attempt to optimize, and the
8862 generated programs are considerably larger and slower than when
8863 optimization is enabled. You can use the
8864 @ifclear vms
8865 @option{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
8866 @end ifclear
8867 @ifset vms
8868 @code{OPTIMIZE} qualifier
8869 @end ifset
8870 to @command{gcc} to control the optimization level:
8872 @table @option
8873 @item ^-O0^/OPTIMIZE=NONE^
8874 No optimization (the default);
8875 generates unoptimized code but has
8876 the fastest compilation time.
8878 @item ^-O1^/OPTIMIZE=SOME^
8879 Medium level optimization;
8880 optimizes reasonably well but does not
8881 degrade compilation time significantly.
8883 @item ^-O2^/OPTIMIZE=ALL^
8884 @ifset vms
8885 @itemx /OPTIMIZE=DEVELOPMENT
8886 @end ifset
8887 Full optimization;
8888 generates highly optimized code and has
8889 the slowest compilation time.
8891 @item ^-O3^/OPTIMIZE=INLINING^
8892 Full optimization as in @option{-O2},
8893 and also attempts automatic inlining of small
8894 subprograms within a unit (@pxref{Inlining of Subprograms}).
8895 @end table
8897 @noindent
8898 Higher optimization levels perform more global transformations on the
8899 program and apply more expensive analysis algorithms in order to generate
8900 faster and more compact code. The price in compilation time, and the
8901 resulting improvement in execution time,
8902 both depend on the particular application and the hardware environment.
8903 You should experiment to find the best level for your application.
8905 Since the precise set of optimizations done at each level will vary from
8906 release to release (and sometime from target to target), it is best to think
8907 of the optimization settings in general terms.
8908 The @cite{Using GNU GCC} manual contains details about
8909 ^the @option{-O} settings and a number of @option{-f} options that^how to^
8910 individually enable or disable specific optimizations.
8912 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
8913 been tested extensively at all optimization levels. There are some bugs
8914 which appear only with optimization turned on, but there have also been
8915 bugs which show up only in @emph{unoptimized} code. Selecting a lower
8916 level of optimization does not improve the reliability of the code
8917 generator, which in practice is highly reliable at all optimization
8918 levels.
8920 Note regarding the use of @option{-O3}: The use of this optimization level
8921 is generally discouraged with GNAT, since it often results in larger
8922 executables which run more slowly. See further discussion of this point
8923 in @ref{Inlining of Subprograms}.
8925 @node Debugging Optimized Code
8926 @subsection Debugging Optimized Code
8927 @cindex Debugging optimized code
8928 @cindex Optimization and debugging
8930 @noindent
8931 Although it is possible to do a reasonable amount of debugging at
8932 @ifclear vms
8933 non-zero optimization levels,
8934 the higher the level the more likely that
8935 @end ifclear
8936 @ifset vms
8937 @option{/OPTIMIZE} settings other than @code{NONE},
8938 such settings will make it more likely that
8939 @end ifset
8940 source-level constructs will have been eliminated by optimization.
8941 For example, if a loop is strength-reduced, the loop
8942 control variable may be completely eliminated and thus cannot be
8943 displayed in the debugger.
8944 This can only happen at @option{-O2} or @option{-O3}.
8945 Explicit temporary variables that you code might be eliminated at
8946 ^level^setting^ @option{-O1} or higher.
8948 The use of the @option{^-g^/DEBUG^} switch,
8949 @cindex @option{^-g^/DEBUG^} (@command{gcc})
8950 which is needed for source-level debugging,
8951 affects the size of the program executable on disk,
8952 and indeed the debugging information can be quite large.
8953 However, it has no effect on the generated code (and thus does not
8954 degrade performance)
8956 Since the compiler generates debugging tables for a compilation unit before
8957 it performs optimizations, the optimizing transformations may invalidate some
8958 of the debugging data.  You therefore need to anticipate certain
8959 anomalous situations that may arise while debugging optimized code.
8960 These are the most common cases:
8962 @enumerate
8963 @item
8964 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
8965 commands show
8966 the PC bouncing back and forth in the code.  This may result from any of
8967 the following optimizations:
8969 @itemize @bullet
8970 @item
8971 @i{Common subexpression elimination:} using a single instance of code for a
8972 quantity that the source computes several times.  As a result you
8973 may not be able to stop on what looks like a statement.
8975 @item
8976 @i{Invariant code motion:} moving an expression that does not change within a
8977 loop, to the beginning of the loop.
8979 @item
8980 @i{Instruction scheduling:} moving instructions so as to
8981 overlap loads and stores (typically) with other code, or in
8982 general to move computations of values closer to their uses. Often
8983 this causes you to pass an assignment statement without the assignment
8984 happening and then later bounce back to the statement when the
8985 value is actually needed.  Placing a breakpoint on a line of code
8986 and then stepping over it may, therefore, not always cause all the
8987 expected side-effects.
8988 @end itemize
8990 @item
8991 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
8992 two identical pieces of code are merged and the program counter suddenly
8993 jumps to a statement that is not supposed to be executed, simply because
8994 it (and the code following) translates to the same thing as the code
8995 that @emph{was} supposed to be executed.  This effect is typically seen in
8996 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
8997 a @code{break} in a C @code{^switch^switch^} statement.
8999 @item
9000 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
9001 There are various reasons for this effect:
9003 @itemize @bullet
9004 @item
9005 In a subprogram prologue, a parameter may not yet have been moved to its
9006 ``home''.
9008 @item
9009 A variable may be dead, and its register re-used.  This is
9010 probably the most common cause.
9012 @item
9013 As mentioned above, the assignment of a value to a variable may
9014 have been moved.
9016 @item
9017 A variable may be eliminated entirely by value propagation or
9018 other means.  In this case, GCC may incorrectly generate debugging
9019 information for the variable
9020 @end itemize
9022 @noindent
9023 In general, when an unexpected value appears for a local variable or parameter
9024 you should first ascertain if that value was actually computed by
9025 your program, as opposed to being incorrectly reported by the debugger.
9026 Record fields or
9027 array elements in an object designated by an access value
9028 are generally less of a problem, once you have ascertained that the access
9029 value is sensible.
9030 Typically, this means checking variables in the preceding code and in the
9031 calling subprogram to verify that the value observed is explainable from other
9032 values (one must apply the procedure recursively to those
9033 other values); or re-running the code and stopping a little earlier
9034 (perhaps before the call) and stepping to better see how the variable obtained
9035 the value in question; or continuing to step @emph{from} the point of the
9036 strange value to see if code motion had simply moved the variable's
9037 assignments later.
9038 @end enumerate
9040 @noindent
9041 In light of such anomalies, a recommended technique is to use @option{-O0}
9042 early in the software development cycle, when extensive debugging capabilities
9043 are most needed, and then move to @option{-O1} and later @option{-O2} as
9044 the debugger becomes less critical.
9045 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
9046 a release management issue.
9047 @ifclear vms
9048 Note that if you use @option{-g} you can then use the @command{strip} program
9049 on the resulting executable,
9050 which removes both debugging information and global symbols.
9051 @end ifclear
9053 @node Inlining of Subprograms
9054 @subsection Inlining of Subprograms
9056 @noindent
9057 A call to a subprogram in the current unit is inlined if all the
9058 following conditions are met:
9060 @itemize @bullet
9061 @item
9062 The optimization level is at least @option{-O1}.
9064 @item
9065 The called subprogram is suitable for inlining: It must be small enough
9066 and not contain nested subprograms or anything else that @command{gcc}
9067 cannot support in inlined subprograms.
9069 @item
9070 The call occurs after the definition of the body of the subprogram.
9072 @item
9073 @cindex pragma Inline
9074 @findex Inline
9075 Either @code{pragma Inline} applies to the subprogram or it is
9076 small and automatic inlining (optimization level @option{-O3}) is
9077 specified.
9078 @end itemize
9080 @noindent
9081 Calls to subprograms in @code{with}'ed units are normally not inlined.
9082 To achieve this level of inlining, the following conditions must all be
9083 true:
9085 @itemize @bullet
9086 @item
9087 The optimization level is at least @option{-O1}.
9089 @item
9090 The called subprogram is suitable for inlining: It must be small enough
9091 and not contain nested subprograms or anything else @command{gcc} cannot
9092 support in inlined subprograms.
9094 @item
9095 The call appears in a body (not in a package spec).
9097 @item
9098 There is a @code{pragma Inline} for the subprogram.
9100 @item
9101 @cindex @option{-gnatn} (@command{gcc})
9102 The @option{^-gnatn^/INLINE^} switch
9103 is used in the @command{gcc} command line
9104 @end itemize
9106 Note that specifying the @option{-gnatn} switch causes additional
9107 compilation dependencies. Consider the following:
9109 @smallexample @c ada
9110 @cartouche
9111 package R is
9112    procedure Q;
9113    pragma Inline (Q);
9114 end R;
9115 package body R is
9116    ...
9117 end R;
9119 with R;
9120 procedure Main is
9121 begin
9122    ...
9123    R.Q;
9124 end Main;
9125 @end cartouche
9126 @end smallexample
9128 @noindent
9129 With the default behavior (no @option{-gnatn} switch specified), the
9130 compilation of the @code{Main} procedure depends only on its own source,
9131 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
9132 means that editing the body of @code{R} does not require recompiling
9133 @code{Main}.
9135 On the other hand, the call @code{R.Q} is not inlined under these
9136 circumstances. If the @option{-gnatn} switch is present when @code{Main}
9137 is compiled, the call will be inlined if the body of @code{Q} is small
9138 enough, but now @code{Main} depends on the body of @code{R} in
9139 @file{r.adb} as well as on the spec. This means that if this body is edited,
9140 the main program must be recompiled. Note that this extra dependency
9141 occurs whether or not the call is in fact inlined by @command{gcc}.
9143 The use of front end inlining with @option{-gnatN} generates similar
9144 additional dependencies.
9146 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
9147 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
9148 can be used to prevent
9149 all inlining. This switch overrides all other conditions and ensures
9150 that no inlining occurs. The extra dependences resulting from
9151 @option{-gnatn} will still be active, even if
9152 this switch is used to suppress the resulting inlining actions.
9154 Note regarding the use of @option{-O3}: There is no difference in inlining
9155 behavior between @option{-O2} and @option{-O3} for subprograms with an explicit
9156 pragma @code{Inline} assuming the use of @option{-gnatn}
9157 or @option{-gnatN} (the switches that activate inlining). If you have used
9158 pragma @code{Inline} in appropriate cases, then it is usually much better
9159 to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which
9160 in this case only has the effect of inlining subprograms you did not
9161 think should be inlined. We often find that the use of @option{-O3} slows
9162 down code by performing excessive inlining, leading to increased instruction
9163 cache pressure from the increased code size. So the bottom line here is
9164 that you should not automatically assume that @option{-O3} is better than
9165 @option{-O2}, and indeed you should use @option{-O3} only if tests show that
9166 it actually improves performance.
9168 @node Optimization and Strict Aliasing
9169 @subsection Optimization and Strict Aliasing
9170 @cindex Aliasing
9171 @cindex Strict Aliasing
9172 @cindex No_Strict_Aliasing
9174 @noindent
9175 The strong typing capabilities of Ada allow an optimizer to generate
9176 efficient code in situations where other languages would be forced to
9177 make worst case assumptions preventing such optimizations. Consider
9178 the following example:
9180 @smallexample @c ada
9181 @cartouche
9182 procedure R is
9183    type Int1 is new Integer;
9184    type Int2 is new Integer;
9185    type Int1A is access Int1;
9186    type Int2A is access Int2;
9187    Int1V : Int1A;
9188    Int2V : Int2A;
9189    ...
9191 begin
9192    ...
9193    for J in Data'Range loop
9194       if Data (J) = Int1V.all then
9195          Int2V.all := Int2V.all + 1;
9196       end if;
9197    end loop;
9198    ...
9199 end R;
9200 @end cartouche
9201 @end smallexample
9203 @noindent
9204 In this example, since the variable @code{Int1V} can only access objects
9205 of type @code{Int1}, and @code{Int2V} can only access objects of type
9206 @code{Int2}, there is no possibility that the assignment to
9207 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
9208 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
9209 for all iterations of the loop and avoid the extra memory reference
9210 required to dereference it each time through the loop.
9212 This kind of optimziation, called strict aliasing analysis, is
9213 triggered by specifying an optimization level of @option{-O2} or
9214 higher and allows @code{GNAT} to generate more efficient code
9215 when access values are involved.
9217 However, although this optimization is always correct in terms of
9218 the formal semantics of the Ada Reference Manual, difficulties can
9219 arise if features like @code{Unchecked_Conversion} are used to break
9220 the typing system. Consider the following complete program example:
9222 @smallexample @c ada
9223 @cartouche
9224 package p1 is
9225    type int1 is new integer;
9226    type int2 is new integer;
9227    type a1 is access int1;
9228    type a2 is access int2;
9229 end p1;
9231 with p1; use p1;
9232 package p2 is
9233    function to_a2 (Input : a1) return a2;
9234 end p2;
9236 with Unchecked_Conversion;
9237 package body p2 is
9238    function to_a2 (Input : a1) return a2 is
9239       function to_a2u is
9240         new Unchecked_Conversion (a1, a2);
9241    begin
9242       return to_a2u (Input);
9243    end to_a2;
9244 end p2;
9246 with p2; use p2;
9247 with p1; use p1;
9248 with Text_IO; use Text_IO;
9249 procedure m is
9250    v1 : a1 := new int1;
9251    v2 : a2 := to_a2 (v1);
9252 begin
9253    v1.all := 1;
9254    v2.all := 0;
9255    put_line (int1'image (v1.all));
9256 end;
9257 @end cartouche
9258 @end smallexample
9260 @noindent
9261 This program prints out 0 in @code{-O0} or @code{-O1}
9262 mode, but it prints out 1 in @code{-O2} mode. That's
9263 because in strict aliasing mode, the compiler can and
9264 does assume that the assignment to @code{v2.all} could not
9265 affect the value of @code{v1.all}, since different types
9266 are involved.
9268 This behavior is not a case of non-conformance with the standard, since
9269 the Ada RM specifies that an unchecked conversion where the resulting
9270 bit pattern is not a correct value of the target type can result in an
9271 abnormal value and attempting to reference an abnormal value makes the
9272 execution of a program erroneous.  That's the case here since the result
9273 does not point to an object of type @code{int2}.  This means that the
9274 effect is entirely unpredictable.
9276 However, although that explanation may satisfy a language
9277 lawyer, in practice an applications programmer expects an
9278 unchecked conversion involving pointers to create true
9279 aliases and the behavior of printing 1 seems plain wrong.
9280 In this case, the strict aliasing optimization is unwelcome.
9282 Indeed the compiler recognizes this possibility, and the
9283 unchecked conversion generates a warning:
9285 @smallexample
9286 p2.adb:5:07: warning: possible aliasing problem with type "a2"
9287 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
9288 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
9289 @end smallexample
9291 @noindent
9292 Unfortunately the problem is recognized when compiling the body of
9293 package @code{p2}, but the actual "bad" code is generated while
9294 compiling the body of @code{m} and this latter compilation does not see
9295 the suspicious @code{Unchecked_Conversion}.
9297 As implied by the warning message, there are approaches you can use to
9298 avoid the unwanted strict aliasing optimization in a case like this.
9300 One possibility is to simply avoid the use of @code{-O2}, but
9301 that is a bit drastic, since it throws away a number of useful
9302 optimizations that do not involve strict aliasing assumptions.
9304 A less drastic approach is to compile the program using the
9305 option @code{-fno-strict-aliasing}. Actually it is only the
9306 unit containing the dereferencing of the suspicious pointer
9307 that needs to be compiled. So in this case, if we compile
9308 unit @code{m} with this switch, then we get the expected
9309 value of zero printed. Analyzing which units might need
9310 the switch can be painful, so a more reasonable approach
9311 is to compile the entire program with options @code{-O2}
9312 and @code{-fno-strict-aliasing}. If the performance is
9313 satisfactory with this combination of options, then the
9314 advantage is that the entire issue of possible "wrong"
9315 optimization due to strict aliasing is avoided.
9317 To avoid the use of compiler switches, the configuration
9318 pragma @code{No_Strict_Aliasing} with no parameters may be
9319 used to specify that for all access types, the strict
9320 aliasing optimization should be suppressed.
9322 However, these approaches are still overkill, in that they causes
9323 all manipulations of all access values to be deoptimized. A more
9324 refined approach is to concentrate attention on the specific
9325 access type identified as problematic.
9327 First, if a careful analysis of uses of the pointer shows
9328 that there are no possible problematic references, then
9329 the warning can be suppressed by bracketing the
9330 instantiation of @code{Unchecked_Conversion} to turn
9331 the warning off:
9333 @smallexample @c ada
9334    pragma Warnings (Off);
9335    function to_a2u is
9336      new Unchecked_Conversion (a1, a2);
9337    pragma Warnings (On);
9338 @end smallexample
9340 @noindent
9341 Of course that approach is not appropriate for this particular
9342 example, since indeed there is a problematic reference. In this
9343 case we can take one of two other approaches.
9345 The first possibility is to move the instantiation of unchecked
9346 conversion to the unit in which the type is declared. In
9347 this example, we would move the instantiation of
9348 @code{Unchecked_Conversion} from the body of package
9349 @code{p2} to the spec of package @code{p1}. Now the
9350 warning disappears. That's because any use of the
9351 access type knows there is a suspicious unchecked
9352 conversion, and the strict aliasing optimization
9353 is automatically suppressed for the type.
9355 If it is not practical to move the unchecked conversion to the same unit
9356 in which the destination access type is declared (perhaps because the
9357 source type is not visible in that unit), you may use pragma
9358 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
9359 same declarative sequence as the declaration of the access type:
9361 @smallexample @c ada
9362    type a2 is access int2;
9363    pragma No_Strict_Aliasing (a2);
9364 @end smallexample
9366 @noindent
9367 Here again, the compiler now knows that the strict aliasing optimization
9368 should be suppressed for any reference to type @code{a2} and the
9369 expected behavior is obtained.
9371 Finally, note that although the compiler can generate warnings for
9372 simple cases of unchecked conversions, there are tricker and more
9373 indirect ways of creating type incorrect aliases which the compiler
9374 cannot detect. Examples are the use of address overlays and unchecked
9375 conversions involving composite types containing access types as
9376 components. In such cases, no warnings are generated, but there can
9377 still be aliasing problems. One safe coding practice is to forbid the
9378 use of address clauses for type overlaying, and to allow unchecked
9379 conversion only for primitive types. This is not really a significant
9380 restriction since any possible desired effect can be achieved by
9381 unchecked conversion of access values.
9383 @ifset vms
9384 @node Coverage Analysis
9385 @subsection Coverage Analysis
9387 @noindent
9388 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
9389 the user to determine the distribution of execution time across a program,
9390 @pxref{Profiling} for details of usage.
9391 @end ifset
9393 @node Reducing the Size of Ada Executables with gnatelim
9394 @section Reducing the Size of Ada Executables with @code{gnatelim}
9395 @findex gnatelim
9397 @noindent
9398 This section describes @command{gnatelim}, a tool which detects unused
9399 subprograms and helps the compiler to create a smaller executable for your
9400 program.
9402 @menu
9403 * About gnatelim::
9404 * Running gnatelim::
9405 * Correcting the List of Eliminate Pragmas::
9406 * Making Your Executables Smaller::
9407 * Summary of the gnatelim Usage Cycle::
9408 @end menu
9410 @node About gnatelim
9411 @subsection About @code{gnatelim}
9413 @noindent
9414 When a program shares a set of Ada
9415 packages with other programs, it may happen that this program uses
9416 only a fraction of the subprograms defined in these packages. The code
9417 created for these unused subprograms increases the size of the executable.
9419 @code{gnatelim} tracks unused subprograms in an Ada program and
9420 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
9421 subprograms that are declared but never called. By placing the list of
9422 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
9423 recompiling your program, you may decrease the size of its executable,
9424 because the compiler will not generate the code for 'eliminated' subprograms.
9425 See GNAT Reference Manual for more information about this pragma.
9427 @code{gnatelim} needs as its input data the name of the main subprogram
9428 and a bind file for a main subprogram.
9430 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
9431 the main subprogram. @code{gnatelim} can work with both Ada and C
9432 bind files; when both are present, it uses the Ada bind file.
9433 The following commands will build the program and create the bind file:
9435 @smallexample
9436 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
9437 $ gnatbind main_prog
9438 @end smallexample
9440 Note that @code{gnatelim} needs neither object nor ALI files.
9442 @node Running gnatelim
9443 @subsection Running @code{gnatelim}
9445 @noindent
9446 @code{gnatelim} has the following command-line interface:
9448 @smallexample
9449 $ gnatelim [options] name
9450 @end smallexample
9452 @noindent
9453 @code{name} should be a name of a source file that contains the main subprogram
9454 of a program (partition).
9456 @code{gnatelim} has the following switches:
9458 @table @option
9459 @c !sort!
9460 @item ^-q^/QUIET^
9461 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
9462 Quiet mode: by default @code{gnatelim} outputs to the standard error
9463 stream the number of program units left to be processed. This option turns
9464 this trace off.
9466 @item ^-v^/VERBOSE^
9467 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
9468 Verbose mode: @code{gnatelim} version information is printed as Ada
9469 comments to the standard output stream. Also, in addition to the number of
9470 program units left @code{gnatelim} will output the name of the current unit
9471 being processed.
9473 @item ^-a^/ALL^
9474 @cindex @option{^-a^/ALL^} (@command{gnatelim})
9475 Also look for subprograms from the GNAT run time that can be eliminated. Note
9476 that when @file{gnat.adc} is produced using this switch, the entire program
9477 must be recompiled with switch @option{^-a^/ALL_FILES^} to @command{gnatmake}.
9479 @item ^-I^/INCLUDE_DIRS=^@var{dir}
9480 @cindex @option{^-I^/INCLUDE_DIRS^} (@command{gnatelim})
9481 When looking for source files also look in directory @var{dir}. Specifying
9482 @option{^-I-^/INCLUDE_DIRS=-^} instructs @code{gnatelim} not to look for
9483 sources in the current directory.
9485 @item ^-b^/BIND_FILE=^@var{bind_file}
9486 @cindex @option{^-b^/BIND_FILE^} (@command{gnatelim})
9487 Specifies @var{bind_file} as the bind file to process. If not set, the name
9488 of the bind file is computed from the full expanded Ada name
9489 of a main subprogram.
9491 @item ^-C^/CONFIG_FILE=^@var{config_file}
9492 @cindex @option{^-C^/CONFIG_FILE^} (@command{gnatelim})
9493 Specifies a file @var{config_file} that contains configuration pragmas. The
9494 file must be specified with full path.
9496 @item ^--GCC^/COMPILER^=@var{compiler_name}
9497 @cindex @option{^-GCC^/COMPILER^} (@command{gnatelim})
9498 Instructs @code{gnatelim} to use specific @command{gcc} compiler instead of one
9499 available on the path.
9501 @item ^--GNATMAKE^/GNATMAKE^=@var{gnatmake_name}
9502 @cindex @option{^--GNATMAKE^/GNATMAKE^} (@command{gnatelim})
9503 Instructs @code{gnatelim} to use specific @command{gnatmake} instead of one
9504 available on the path.
9505 @end table
9507 @noindent
9508 @code{gnatelim} sends its output to the standard output stream, and all the
9509 tracing and debug information is sent to the standard error stream.
9510 In order to produce a proper GNAT configuration file
9511 @file{gnat.adc}, redirection must be used:
9513 @smallexample
9514 @ifset vms
9515 $ PIPE GNAT ELIM MAIN_PROG.ADB > GNAT.ADC
9516 @end ifset
9517 @ifclear vms
9518 $ gnatelim main_prog.adb > gnat.adc
9519 @end ifclear
9520 @end smallexample
9522 @ifclear vms
9523 @noindent
9526 @smallexample
9527 $ gnatelim main_prog.adb >> gnat.adc
9528 @end smallexample
9530 @noindent
9531 in order to append the @code{gnatelim} output to the existing contents of
9532 @file{gnat.adc}.
9533 @end ifclear
9535 @node Correcting the List of Eliminate Pragmas
9536 @subsection Correcting the List of Eliminate Pragmas
9538 @noindent
9539 In some rare cases @code{gnatelim} may try to eliminate
9540 subprograms that are actually called in the program. In this case, the
9541 compiler will generate an error message of the form:
9543 @smallexample
9544 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
9545 @end smallexample
9547 @noindent
9548 You will need to manually remove the wrong @code{Eliminate} pragmas from
9549 the @file{gnat.adc} file. You should recompile your program
9550 from scratch after that, because you need a consistent @file{gnat.adc} file
9551 during the entire compilation.
9553 @node Making Your Executables Smaller
9554 @subsection Making Your Executables Smaller
9556 @noindent
9557 In order to get a smaller executable for your program you now have to
9558 recompile the program completely with the new @file{gnat.adc} file
9559 created by @code{gnatelim} in your current directory:
9561 @smallexample
9562 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9563 @end smallexample
9565 @noindent
9566 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
9567 recompile everything
9568 with the set of pragmas @code{Eliminate} that you have obtained with
9569 @command{gnatelim}).
9571 Be aware that the set of @code{Eliminate} pragmas is specific to each
9572 program. It is not recommended to merge sets of @code{Eliminate}
9573 pragmas created for different programs in one @file{gnat.adc} file.
9575 @node Summary of the gnatelim Usage Cycle
9576 @subsection Summary of the gnatelim Usage Cycle
9578 @noindent
9579 Here is a quick summary of the steps to be taken in order to reduce
9580 the size of your executables with @code{gnatelim}. You may use
9581 other GNAT options to control the optimization level,
9582 to produce the debugging information, to set search path, etc.
9584 @enumerate
9585 @item
9586 Produce a bind file
9588 @smallexample
9589 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
9590 $ gnatbind main_prog
9591 @end smallexample
9593 @item
9594 Generate a list of @code{Eliminate} pragmas
9595 @smallexample
9596 @ifset vms
9597 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
9598 @end ifset
9599 @ifclear vms
9600 $ gnatelim main_prog >[>] gnat.adc
9601 @end ifclear
9602 @end smallexample
9604 @item
9605 Recompile the application
9607 @smallexample
9608 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
9609 @end smallexample
9611 @end enumerate
9613 @c ********************************
9614 @node Renaming Files Using gnatchop
9615 @chapter Renaming Files Using @code{gnatchop}
9616 @findex gnatchop
9618 @noindent
9619 This chapter discusses how to handle files with multiple units by using
9620 the @code{gnatchop} utility. This utility is also useful in renaming
9621 files to meet the standard GNAT default file naming conventions.
9623 @menu
9624 * Handling Files with Multiple Units::
9625 * Operating gnatchop in Compilation Mode::
9626 * Command Line for gnatchop::
9627 * Switches for gnatchop::
9628 * Examples of gnatchop Usage::
9629 @end menu
9631 @node Handling Files with Multiple Units
9632 @section Handling Files with Multiple Units
9634 @noindent
9635 The basic compilation model of GNAT requires that a file submitted to the
9636 compiler have only one unit and there be a strict correspondence
9637 between the file name and the unit name.
9639 The @code{gnatchop} utility allows both of these rules to be relaxed,
9640 allowing GNAT to process files which contain multiple compilation units
9641 and files with arbitrary file names. @code{gnatchop}
9642 reads the specified file and generates one or more output files,
9643 containing one unit per file. The unit and the file name correspond,
9644 as required by GNAT.
9646 If you want to permanently restructure a set of ``foreign'' files so that
9647 they match the GNAT rules, and do the remaining development using the
9648 GNAT structure, you can simply use @command{gnatchop} once, generate the
9649 new set of files and work with them from that point on.
9651 Alternatively, if you want to keep your files in the ``foreign'' format,
9652 perhaps to maintain compatibility with some other Ada compilation
9653 system, you can set up a procedure where you use @command{gnatchop} each
9654 time you compile, regarding the source files that it writes as temporary
9655 files that you throw away.
9657 @node Operating gnatchop in Compilation Mode
9658 @section Operating gnatchop in Compilation Mode
9660 @noindent
9661 The basic function of @code{gnatchop} is to take a file with multiple units
9662 and split it into separate files. The boundary between files is reasonably
9663 clear, except for the issue of comments and pragmas. In default mode, the
9664 rule is that any pragmas between units belong to the previous unit, except
9665 that configuration pragmas always belong to the following unit. Any comments
9666 belong to the following unit. These rules
9667 almost always result in the right choice of
9668 the split point without needing to mark it explicitly and most users will
9669 find this default to be what they want. In this default mode it is incorrect to
9670 submit a file containing only configuration pragmas, or one that ends in
9671 configuration pragmas, to @code{gnatchop}.
9673 However, using a special option to activate ``compilation mode'',
9674 @code{gnatchop}
9675 can perform another function, which is to provide exactly the semantics
9676 required by the RM for handling of configuration pragmas in a compilation.
9677 In the absence of configuration pragmas (at the main file level), this
9678 option has no effect, but it causes such configuration pragmas to be handled
9679 in a quite different manner.
9681 First, in compilation mode, if @code{gnatchop} is given a file that consists of
9682 only configuration pragmas, then this file is appended to the
9683 @file{gnat.adc} file in the current directory. This behavior provides
9684 the required behavior described in the RM for the actions to be taken
9685 on submitting such a file to the compiler, namely that these pragmas
9686 should apply to all subsequent compilations in the same compilation
9687 environment. Using GNAT, the current directory, possibly containing a
9688 @file{gnat.adc} file is the representation
9689 of a compilation environment. For more information on the
9690 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
9692 Second, in compilation mode, if @code{gnatchop}
9693 is given a file that starts with
9694 configuration pragmas, and contains one or more units, then these
9695 configuration pragmas are prepended to each of the chopped files. This
9696 behavior provides the required behavior described in the RM for the
9697 actions to be taken on compiling such a file, namely that the pragmas
9698 apply to all units in the compilation, but not to subsequently compiled
9699 units.
9701 Finally, if configuration pragmas appear between units, they are appended
9702 to the previous unit. This results in the previous unit being illegal,
9703 since the compiler does not accept configuration pragmas that follow
9704 a unit. This provides the required RM behavior that forbids configuration
9705 pragmas other than those preceding the first compilation unit of a
9706 compilation.
9708 For most purposes, @code{gnatchop} will be used in default mode. The
9709 compilation mode described above is used only if you need exactly
9710 accurate behavior with respect to compilations, and you have files
9711 that contain multiple units and configuration pragmas. In this
9712 circumstance the use of @code{gnatchop} with the compilation mode
9713 switch provides the required behavior, and is for example the mode
9714 in which GNAT processes the ACVC tests.
9716 @node Command Line for gnatchop
9717 @section Command Line for @code{gnatchop}
9719 @noindent
9720 The @code{gnatchop} command has the form:
9722 @smallexample
9723 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
9724       [@var{directory}]
9725 @end smallexample
9727 @noindent
9728 The only required argument is the file name of the file to be chopped.
9729 There are no restrictions on the form of this file name. The file itself
9730 contains one or more Ada units, in normal GNAT format, concatenated
9731 together. As shown, more than one file may be presented to be chopped.
9733 When run in default mode, @code{gnatchop} generates one output file in
9734 the current directory for each unit in each of the files.
9736 @var{directory}, if specified, gives the name of the directory to which
9737 the output files will be written. If it is not specified, all files are
9738 written to the current directory.
9740 For example, given a
9741 file called @file{hellofiles} containing
9743 @smallexample @c ada
9744 @group
9745 @cartouche
9746 procedure hello;
9748 with Text_IO; use Text_IO;
9749 procedure hello is
9750 begin
9751    Put_Line ("Hello");
9752 end hello;
9753 @end cartouche
9754 @end group
9755 @end smallexample
9757 @noindent
9758 the command
9760 @smallexample
9761 $ gnatchop ^hellofiles^HELLOFILES.^
9762 @end smallexample
9764 @noindent
9765 generates two files in the current directory, one called
9766 @file{hello.ads} containing the single line that is the procedure spec,
9767 and the other called @file{hello.adb} containing the remaining text. The
9768 original file is not affected. The generated files can be compiled in
9769 the normal manner.
9771 @noindent
9772 When gnatchop is invoked on a file that is empty or that contains only empty
9773 lines and/or comments, gnatchop will not fail, but will not produce any
9774 new sources.
9776 For example, given a
9777 file called @file{toto.txt} containing
9779 @smallexample @c ada
9780 @group
9781 @cartouche
9782 --  Just a comment
9783 @end cartouche
9784 @end group
9785 @end smallexample
9787 @noindent
9788 the command
9790 @smallexample
9791 $ gnatchop ^toto.txt^TOT.TXT^
9792 @end smallexample
9794 @noindent
9795 will not produce any new file and will result in the following warnings:
9797 @smallexample
9798 toto.txt:1:01: warning: empty file, contains no compilation units
9799 no compilation units found
9800 no source files written
9801 @end smallexample
9803 @node Switches for gnatchop
9804 @section Switches for @code{gnatchop}
9806 @noindent
9807 @command{gnatchop} recognizes the following switches:
9809 @table @option
9810 @c !sort!
9812 @item ^-c^/COMPILATION^
9813 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
9814 Causes @code{gnatchop} to operate in compilation mode, in which
9815 configuration pragmas are handled according to strict RM rules. See
9816 previous section for a full description of this mode.
9818 @ifclear vms
9819 @item -gnatxxx
9820 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
9821 used to parse the given file. Not all @code{xxx} options make sense,
9822 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
9823 process a source file that uses Latin-2 coding for identifiers.
9824 @end ifclear
9826 @item ^-h^/HELP^
9827 Causes @code{gnatchop} to generate a brief help summary to the standard
9828 output file showing usage information.
9830 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
9831 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
9832 Limit generated file names to the specified number @code{mm}
9833 of characters.
9834 This is useful if the
9835 resulting set of files is required to be interoperable with systems
9836 which limit the length of file names.
9837 @ifset vms
9838 If no value is given, or
9839 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
9840 a default of 39, suitable for OpenVMS Alpha
9841 Systems, is assumed
9842 @end ifset
9843 @ifclear vms
9844 No space is allowed between the @option{-k} and the numeric value. The numeric
9845 value may be omitted in which case a default of @option{-k8},
9846 suitable for use
9847 with DOS-like file systems, is used. If no @option{-k} switch
9848 is present then
9849 there is no limit on the length of file names.
9850 @end ifclear
9852 @item ^-p^/PRESERVE^
9853 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
9854 Causes the file ^modification^creation^ time stamp of the input file to be
9855 preserved and used for the time stamp of the output file(s). This may be
9856 useful for preserving coherency of time stamps in an environment where
9857 @code{gnatchop} is used as part of a standard build process.
9859 @item ^-q^/QUIET^
9860 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
9861 Causes output of informational messages indicating the set of generated
9862 files to be suppressed. Warnings and error messages are unaffected.
9864 @item ^-r^/REFERENCE^
9865 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
9866 @findex Source_Reference
9867 Generate @code{Source_Reference} pragmas. Use this switch if the output
9868 files are regarded as temporary and development is to be done in terms
9869 of the original unchopped file. This switch causes
9870 @code{Source_Reference} pragmas to be inserted into each of the
9871 generated files to refers back to the original file name and line number.
9872 The result is that all error messages refer back to the original
9873 unchopped file.
9874 In addition, the debugging information placed into the object file (when
9875 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
9876 specified)
9877 also refers back to this original file so that tools like profilers and
9878 debuggers will give information in terms of the original unchopped file.
9880 If the original file to be chopped itself contains
9881 a @code{Source_Reference}
9882 pragma referencing a third file, then gnatchop respects
9883 this pragma, and the generated @code{Source_Reference} pragmas
9884 in the chopped file refer to the original file, with appropriate
9885 line numbers. This is particularly useful when @code{gnatchop}
9886 is used in conjunction with @code{gnatprep} to compile files that
9887 contain preprocessing statements and multiple units.
9889 @item ^-v^/VERBOSE^
9890 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
9891 Causes @code{gnatchop} to operate in verbose mode. The version
9892 number and copyright notice are output, as well as exact copies of
9893 the gnat1 commands spawned to obtain the chop control information.
9895 @item ^-w^/OVERWRITE^
9896 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
9897 Overwrite existing file names. Normally @code{gnatchop} regards it as a
9898 fatal error if there is already a file with the same name as a
9899 file it would otherwise output, in other words if the files to be
9900 chopped contain duplicated units. This switch bypasses this
9901 check, and causes all but the last instance of such duplicated
9902 units to be skipped.
9904 @ifclear vms
9905 @item --GCC=xxxx
9906 @cindex @option{--GCC=} (@code{gnatchop})
9907 Specify the path of the GNAT parser to be used. When this switch is used,
9908 no attempt is made to add the prefix to the GNAT parser executable.
9909 @end ifclear
9910 @end table
9912 @node Examples of gnatchop Usage
9913 @section Examples of @code{gnatchop} Usage
9915 @table @code
9916 @ifset vms
9917 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
9918 @end ifset
9919 @ifclear vms
9920 @item gnatchop -w hello_s.ada prerelease/files
9921 @end ifclear
9923 Chops the source file @file{hello_s.ada}. The output files will be
9924 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
9925 overwriting any
9926 files with matching names in that directory (no files in the current
9927 directory are modified).
9929 @item gnatchop ^archive^ARCHIVE.^
9930 Chops the source file @file{^archive^ARCHIVE.^}
9931 into the current directory. One
9932 useful application of @code{gnatchop} is in sending sets of sources
9933 around, for example in email messages. The required sources are simply
9934 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
9935 command), and then
9936 @code{gnatchop} is used at the other end to reconstitute the original
9937 file names.
9939 @item gnatchop file1 file2 file3 direc
9940 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
9941 the resulting files in the directory @file{direc}. Note that if any units
9942 occur more than once anywhere within this set of files, an error message
9943 is generated, and no files are written. To override this check, use the
9944 @option{^-w^/OVERWRITE^} switch,
9945 in which case the last occurrence in the last file will
9946 be the one that is output, and earlier duplicate occurrences for a given
9947 unit will be skipped.
9948 @end table
9950 @node Configuration Pragmas
9951 @chapter Configuration Pragmas
9952 @cindex Configuration pragmas
9953 @cindex Pragmas, configuration
9955 @noindent
9956 In Ada 95, configuration pragmas include those pragmas described as
9957 such in the Ada 95 Reference Manual, as well as
9958 implementation-dependent pragmas that are configuration pragmas. See the
9959 individual descriptions of pragmas in the GNAT Reference Manual for
9960 details on these additional GNAT-specific configuration pragmas. Most
9961 notably, the pragma @code{Source_File_Name}, which allows
9962 specifying non-default names for source files, is a configuration
9963 pragma. The following is a complete list of configuration pragmas
9964 recognized by @code{GNAT}:
9966 @smallexample
9967    Ada_83
9968    Ada_95
9969    C_Pass_By_Copy
9970    Component_Alignment
9971    Detect_Blocking
9972    Discard_Names
9973    Elaboration_Checks
9974    Eliminate
9975    Extend_System
9976    Extensions_Allowed
9977    External_Name_Casing
9978    Float_Representation
9979    Initialize_Scalars
9980    License
9981    Locking_Policy
9982    Long_Float
9983    Normalize_Scalars
9984    Polling
9985    Profile
9986    Profile_Warnings
9987    Propagate_Exceptions
9988    Queuing_Policy
9989    Ravenscar
9990    Restricted_Run_Time
9991    Restrictions
9992    Restrictions_Warnings
9993    Reviewable
9994    Source_File_Name
9995    Style_Checks
9996    Suppress
9997    Task_Dispatching_Policy
9998    Universal_Data
9999    Unsuppress
10000    Use_VADS_Size
10001    Warnings
10002    Validity_Checks
10003 @end smallexample
10005 @menu
10006 * Handling of Configuration Pragmas::
10007 * The Configuration Pragmas Files::
10008 @end menu
10010 @node Handling of Configuration Pragmas
10011 @section Handling of Configuration Pragmas
10013 Configuration pragmas may either appear at the start of a compilation
10014 unit, in which case they apply only to that unit, or they may apply to
10015 all compilations performed in a given compilation environment.
10017 GNAT also provides the @code{gnatchop} utility to provide an automatic
10018 way to handle configuration pragmas following the semantics for
10019 compilations (that is, files with multiple units), described in the RM.
10020 See @ref{Operating gnatchop in Compilation Mode} for details.
10021 However, for most purposes, it will be more convenient to edit the
10022 @file{gnat.adc} file that contains configuration pragmas directly,
10023 as described in the following section.
10025 @node The Configuration Pragmas Files
10026 @section The Configuration Pragmas Files
10027 @cindex @file{gnat.adc}
10029 @noindent
10030 In GNAT a compilation environment is defined by the current
10031 directory at the time that a compile command is given. This current
10032 directory is searched for a file whose name is @file{gnat.adc}. If
10033 this file is present, it is expected to contain one or more
10034 configuration pragmas that will be applied to the current compilation.
10035 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
10036 considered.
10038 Configuration pragmas may be entered into the @file{gnat.adc} file
10039 either by running @code{gnatchop} on a source file that consists only of
10040 configuration pragmas, or more conveniently  by
10041 direct editing of the @file{gnat.adc} file, which is a standard format
10042 source file.
10044 In addition to @file{gnat.adc}, one additional file containing configuration
10045 pragmas may be applied to the current compilation using the switch
10046 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
10047 contains only configuration pragmas. These configuration pragmas are
10048 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
10049 is present and switch @option{-gnatA} is not used).
10051 It is allowed to specify several switches @option{-gnatec}, however only
10052 the last one on the command line will be taken into account.
10054 If you are using project file, a separate mechanism is provided using
10055 project attributes, see @ref{Specifying Configuration Pragmas} for more
10056 details.
10058 @ifset vms
10059 Of special interest to GNAT OpenVMS Alpha is the following
10060 configuration pragma:
10062 @smallexample @c ada
10063 @cartouche
10064 pragma Extend_System (Aux_DEC);
10065 @end cartouche
10066 @end smallexample
10068 @noindent
10069 In the presence of this pragma, GNAT adds to the definition of the
10070 predefined package SYSTEM all the additional types and subprograms that are
10071 defined in DEC Ada. See @ref{Compatibility with DEC Ada} for details.
10072 @end ifset
10074 @node Handling Arbitrary File Naming Conventions Using gnatname
10075 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
10076 @cindex Arbitrary File Naming Conventions
10078 @menu
10079 * Arbitrary File Naming Conventions::
10080 * Running gnatname::
10081 * Switches for gnatname::
10082 * Examples of gnatname Usage::
10083 @end menu
10085 @node Arbitrary File Naming Conventions
10086 @section Arbitrary File Naming Conventions
10088 @noindent
10089 The GNAT compiler must be able to know the source file name of a compilation
10090 unit.  When using the standard GNAT default file naming conventions
10091 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
10092 does not need additional information.
10094 @noindent
10095 When the source file names do not follow the standard GNAT default file naming
10096 conventions, the GNAT compiler must be given additional information through
10097 a configuration pragmas file (@pxref{Configuration Pragmas})
10098 or a project file.
10099 When the non standard file naming conventions are well-defined,
10100 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
10101 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
10102 if the file naming conventions are irregular or arbitrary, a number
10103 of pragma @code{Source_File_Name} for individual compilation units
10104 must be defined.
10105 To help maintain the correspondence between compilation unit names and
10106 source file names within the compiler,
10107 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
10108 set of files.
10110 @node Running gnatname
10111 @section Running @code{gnatname}
10113 @noindent
10114 The usual form of the @code{gnatname} command is
10116 @smallexample
10117 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
10118 @end smallexample
10120 @noindent
10121 All of the arguments are optional. If invoked without any argument,
10122 @code{gnatname} will display its usage.
10124 @noindent
10125 When used with at least one naming pattern, @code{gnatname} will attempt to
10126 find all the compilation units in files that follow at least one of the
10127 naming patterns. To find these compilation units,
10128 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
10129 regular files.
10131 @noindent
10132 One or several Naming Patterns may be given as arguments to @code{gnatname}.
10133 Each Naming Pattern is enclosed between double quotes.
10134 A Naming Pattern is a regular expression similar to the wildcard patterns
10135 used in file names by the Unix shells or the DOS prompt.
10137 @noindent
10138 Examples of Naming Patterns are
10140 @smallexample
10141    "*.[12].ada"
10142    "*.ad[sb]*"
10143    "body_*"    "spec_*"
10144 @end smallexample
10146 @noindent
10147 For a more complete description of the syntax of Naming Patterns,
10148 see the second kind of regular expressions described in @file{g-regexp.ads}
10149 (the ``Glob'' regular expressions).
10151 @noindent
10152 When invoked with no switches, @code{gnatname} will create a configuration
10153 pragmas file @file{gnat.adc} in the current working directory, with pragmas
10154 @code{Source_File_Name} for each file that contains a valid Ada unit.
10156 @node Switches for gnatname
10157 @section Switches for @code{gnatname}
10159 @noindent
10160 Switches for @code{gnatname} must precede any specified Naming Pattern.
10162 @noindent
10163 You may specify any of the following switches to @code{gnatname}:
10165 @table @option
10166 @c !sort!
10168 @item ^-c^/CONFIG_FILE=^@file{file}
10169 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
10170 Create a configuration pragmas file @file{file} (instead of the default
10171 @file{gnat.adc}).
10172 @ifclear vms
10173 There may be zero, one or more space between @option{-c} and
10174 @file{file}.
10175 @end ifclear
10176 @file{file} may include directory information. @file{file} must be
10177 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
10178 When a switch @option{^-c^/CONFIG_FILE^} is
10179 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
10181 @item ^-d^/SOURCE_DIRS=^@file{dir}
10182 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
10183 Look for source files in directory @file{dir}. There may be zero, one or more
10184 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
10185 When a switch @option{^-d^/SOURCE_DIRS^}
10186 is specified, the current working directory will not be searched for source
10187 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
10188 or @option{^-D^/DIR_FILES^} switch.
10189 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
10190 If @file{dir} is a relative path, it is relative to the directory of
10191 the configuration pragmas file specified with switch
10192 @option{^-c^/CONFIG_FILE^},
10193 or to the directory of the project file specified with switch
10194 @option{^-P^/PROJECT_FILE^} or,
10195 if neither switch @option{^-c^/CONFIG_FILE^}
10196 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
10197 current working directory. The directory
10198 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
10200 @item ^-D^/DIRS_FILE=^@file{file}
10201 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
10202 Look for source files in all directories listed in text file @file{file}.
10203 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
10204 and @file{file}.
10205 @file{file} must be an existing, readable text file.
10206 Each non empty line in @file{file} must be a directory.
10207 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
10208 switches @option{^-d^/SOURCE_DIRS^} as there are non empty lines in
10209 @file{file}.
10211 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
10212 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
10213 Foreign patterns. Using this switch, it is possible to add sources of languages
10214 other than Ada to the list of sources of a project file.
10215 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
10216 For example,
10217 @smallexample
10218 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
10219 @end smallexample
10220 @noindent
10221 will look for Ada units in all files with the @file{.ada} extension,
10222 and will add to the list of file for project @file{prj.gpr} the C files
10223 with extension ".^c^C^".
10225 @item ^-h^/HELP^
10226 @cindex @option{^-h^/HELP^} (@code{gnatname})
10227 Output usage (help) information. The output is written to @file{stdout}.
10229 @item ^-P^/PROJECT_FILE=^@file{proj}
10230 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
10231 Create or update project file @file{proj}. There may be zero, one or more space
10232 between @option{-P} and @file{proj}. @file{proj} may include directory
10233 information. @file{proj} must be writable.
10234 There may be only one switch @option{^-P^/PROJECT_FILE^}.
10235 When a switch @option{^-P^/PROJECT_FILE^} is specified,
10236 no switch @option{^-c^/CONFIG_FILE^} may be specified.
10238 @item ^-v^/VERBOSE^
10239 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
10240 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
10241 This includes name of the file written, the name of the directories to search
10242 and, for each file in those directories whose name matches at least one of
10243 the Naming Patterns, an indication of whether the file contains a unit,
10244 and if so the name of the unit.
10246 @item ^-v -v^/VERBOSE /VERBOSE^
10247 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
10248 Very Verbose mode. In addition to the output produced in verbose mode,
10249 for each file in the searched directories whose name matches none of
10250 the Naming Patterns, an indication is given that there is no match.
10252 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
10253 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
10254 Excluded patterns. Using this switch, it is possible to exclude some files
10255 that would match the name patterns. For example,
10256 @smallexample
10257 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
10258 @end smallexample
10259 @noindent
10260 will look for Ada units in all files with the @file{.ada} extension,
10261 except those whose names end with @file{_nt.ada}.
10263 @end table
10265 @node Examples of gnatname Usage
10266 @section Examples of @code{gnatname} Usage
10268 @ifset vms
10269 @smallexample
10270 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
10271 @end smallexample
10272 @end ifset
10274 @ifclear vms
10275 @smallexample
10276 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
10277 @end smallexample
10278 @end ifclear
10280 @noindent
10281 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
10282 and be writable. In addition, the directory
10283 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
10284 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
10286 @ifclear vms
10287 Note the optional spaces after @option{-c} and @option{-d}.
10288 @end ifclear
10290 @smallexample
10291 @ifclear vms
10292 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
10293   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
10294 @end ifclear
10295 @ifset vms
10296 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
10297   /EXCLUDED_PATTERN=*_nt_body.ada
10298   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
10299   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
10300 @end ifset
10301 @end smallexample
10303 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
10304 even in conjunction with one or several switches
10305 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
10306 are used in this example.
10308 @c *****************************************
10309 @c * G N A T  P r o j e c t  M a n a g e r *
10310 @c *****************************************
10311 @node GNAT Project Manager
10312 @chapter GNAT Project Manager
10314 @menu
10315 * Introduction::
10316 * Examples of Project Files::
10317 * Project File Syntax::
10318 * Objects and Sources in Project Files::
10319 * Importing Projects::
10320 * Project Extension::
10321 * Project Hierarchy Extension::
10322 * External References in Project Files::
10323 * Packages in Project Files::
10324 * Variables from Imported Projects::
10325 * Naming Schemes::
10326 * Library Projects::
10327 * Using Third-Party Libraries through Projects::
10328 * Stand-alone Library Projects::
10329 * Switches Related to Project Files::
10330 * Tools Supporting Project Files::
10331 * An Extended Example::
10332 * Project File Complete Syntax::
10333 @end menu
10335 @c ****************
10336 @c * Introduction *
10337 @c ****************
10339 @node Introduction
10340 @section Introduction
10342 @noindent
10343 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
10344 you to manage complex builds involving a number of source files, directories,
10345 and compilation options for different system configurations. In particular,
10346 project files allow you to specify:
10347 @itemize @bullet
10348 @item
10349 The directory or set of directories containing the source files, and/or the
10350 names of the specific source files themselves
10351 @item
10352 The directory in which the compiler's output
10353 (@file{ALI} files, object files, tree files) is to be placed
10354 @item
10355 The directory in which the executable programs is to be placed
10356 @item
10357 ^Switch^Switch^ settings for any of the project-enabled tools
10358 (@command{gnatmake}, compiler, binder, linker, @code{gnatls}, @code{gnatxref},
10359 @code{gnatfind}); you can apply these settings either globally or to individual
10360 compilation units.
10361 @item
10362 The source files containing the main subprogram(s) to be built
10363 @item
10364 The source programming language(s) (currently Ada and/or C)
10365 @item
10366 Source file naming conventions; you can specify these either globally or for
10367 individual compilation units
10368 @end itemize
10370 @menu
10371 * Project Files::
10372 @end menu
10374 @node Project Files
10375 @subsection Project Files
10377 @noindent
10378 Project files are written in a syntax close to that of Ada, using  familiar
10379 notions such as packages, context clauses, declarations, default values,
10380 assignments, and inheritance. Finally, project files can be built
10381 hierarchically from other project files, simplifying complex system
10382 integration and project reuse.
10384 A @dfn{project} is a specific set of values for various compilation properties.
10385 The settings for a given project are described by means of
10386 a @dfn{project file}, which is a text file written in an Ada-like syntax.
10387 Property values in project files are either strings or lists of strings.
10388 Properties that are not explicitly set receive default values.  A project
10389 file may interrogate the values of @dfn{external variables} (user-defined
10390 command-line switches or environment variables), and it may specify property
10391 settings conditionally, based on the value of such variables.
10393 In simple cases, a project's source files depend only on other source files
10394 in the same project, or on the predefined libraries.  (@emph{Dependence} is
10395 used in
10396 the Ada technical sense; as in one Ada unit @code{with}ing another.)  However,
10397 the Project Manager also allows more sophisticated arrangements,
10398 where the source files in one project depend on source files in other
10399 projects:
10400 @itemize @bullet
10401 @item
10402 One project can @emph{import} other projects containing needed source files.
10403 @item
10404 You can organize GNAT projects in a hierarchy: a @emph{child} project
10405 can extend a @emph{parent} project, inheriting the parent's source files and
10406 optionally overriding any of them with alternative versions
10407 @end itemize
10409 @noindent
10410 More generally, the Project Manager lets you structure large development
10411 efforts into hierarchical subsystems, where build decisions are delegated
10412 to the subsystem level, and thus different compilation environments
10413 (^switch^switch^ settings) used for different subsystems.
10415 The Project Manager is invoked through the
10416 @option{^-P^/PROJECT_FILE=^@emph{projectfile}}
10417 switch to @command{gnatmake} or to the @command{^gnat^GNAT^} front driver.
10418 @ifclear vms
10419 There may be zero, one or more spaces between @option{-P} and
10420 @option{@emph{projectfile}}.
10421 @end ifclear
10422 If you want to define (on the command line) an external variable that is
10423 queried by the project file, you must use the
10424 @option{^-X^/EXTERNAT_REFERENCE=^@emph{vbl}=@emph{value}} switch.
10425 The Project Manager parses and interprets the project file, and drives the
10426 invoked tool based on the project settings.
10428 The Project Manager supports a wide range of development strategies,
10429 for systems of all sizes.  Here are some typical practices that are
10430 easily handled:
10431 @itemize @bullet
10432 @item
10433 Using a common set of source files, but generating object files in different
10434 directories via different ^switch^switch^ settings
10435 @item
10436 Using a mostly-shared set of source files, but with different versions of
10437 some unit or units
10438 @end itemize
10440 @noindent
10441 The destination of an executable can be controlled inside a project file
10442 using the @option{^-o^-o^}
10443 ^switch^switch^.
10444 In the absence of such a ^switch^switch^ either inside
10445 the project file or on the command line, any executable files generated by
10446 @command{gnatmake} are placed in the directory @code{Exec_Dir} specified
10447 in the project file. If no @code{Exec_Dir} is specified, they will be placed
10448 in the object directory of the project.
10450 You can use project files to achieve some of the effects of a source
10451 versioning system (for example, defining separate projects for
10452 the different sets of sources that comprise different releases) but the
10453 Project Manager is independent of any source configuration management tools
10454 that might be used by the developers.
10456 The next section introduces the main features of GNAT's project facility
10457 through a sequence of examples; subsequent sections will present the syntax
10458 and semantics in more detail. A more formal description of the project
10459 facility appears in the GNAT Reference Manual.
10461 @c *****************************
10462 @c * Examples of Project Files *
10463 @c *****************************
10465 @node Examples of Project Files
10466 @section Examples of Project Files
10467 @noindent
10468 This section illustrates some of the typical uses of project files and
10469 explains their basic structure and behavior.
10471 @menu
10472 * Common Sources with Different ^Switches^Switches^ and Directories::
10473 * Using External Variables::
10474 * Importing Other Projects::
10475 * Extending a Project::
10476 @end menu
10478 @node Common Sources with Different ^Switches^Switches^ and Directories
10479 @subsection Common Sources with Different ^Switches^Switches^ and Directories
10481 @menu
10482 * Source Files::
10483 * Specifying the Object Directory::
10484 * Specifying the Exec Directory::
10485 * Project File Packages::
10486 * Specifying ^Switch^Switch^ Settings::
10487 * Main Subprograms::
10488 * Executable File Names::
10489 * Source File Naming Conventions::
10490 * Source Language(s)::
10491 @end menu
10493 @noindent
10494 Suppose that the Ada source files @file{pack.ads}, @file{pack.adb}, and
10495 @file{proc.adb} are in the @file{/common} directory.  The file
10496 @file{proc.adb} contains an Ada main subprogram @code{Proc} that @code{with}s
10497 package @code{Pack}.  We want to compile these source files under two sets
10498 of ^switches^switches^:
10499 @itemize @bullet
10500 @item
10501 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
10502 and the @option{^-gnata^-gnata^},
10503 @option{^-gnato^-gnato^},
10504 and @option{^-gnatE^-gnatE^} switches to the
10505 compiler; the compiler's output is to appear in @file{/common/debug}
10506 @item
10507 When preparing a release version, we want to pass the @option{^-O2^O2^} switch
10508 to the compiler; the compiler's output is to appear in @file{/common/release}
10509 @end itemize
10511 @noindent
10512 The GNAT project files shown below, respectively @file{debug.gpr} and
10513 @file{release.gpr} in the @file{/common} directory, achieve these effects.
10515 Schematically:
10516 @smallexample
10517 @group
10518 ^/common^[COMMON]^
10519   debug.gpr
10520   release.gpr
10521   pack.ads
10522   pack.adb
10523   proc.adb
10524 @end group
10525 @group
10526 ^/common/debug^[COMMON.DEBUG]^
10527   proc.ali, proc.o
10528   pack.ali, pack.o
10529 @end group
10530 @group
10531 ^/common/release^[COMMON.RELEASE]^
10532   proc.ali, proc.o
10533   pack.ali, pack.o
10534 @end group
10535 @end smallexample
10536 Here are the corresponding project files:
10538 @smallexample @c projectfile
10539 @group
10540 project Debug is
10541   for Object_Dir use "debug";
10542   for Main use ("proc");
10544   package Builder is
10545     for ^Default_Switches^Default_Switches^ ("Ada")
10546         use ("^-g^-g^");
10547     for Executable ("proc.adb") use "proc1";
10548   end Builder;
10549 @end group
10551 @group
10552   package Compiler is
10553     for ^Default_Switches^Default_Switches^ ("Ada")
10554        use ("-fstack-check",
10555             "^-gnata^-gnata^",
10556             "^-gnato^-gnato^",
10557             "^-gnatE^-gnatE^");
10558   end Compiler;
10559 end Debug;
10560 @end group
10561 @end smallexample
10563 @smallexample @c projectfile
10564 @group
10565 project Release is
10566   for Object_Dir use "release";
10567   for Exec_Dir use ".";
10568   for Main use ("proc");
10570   package Compiler is
10571     for ^Default_Switches^Default_Switches^ ("Ada")
10572         use ("^-O2^-O2^");
10573   end Compiler;
10574 end Release;
10575 @end group
10576 @end smallexample
10578 @noindent
10579 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
10580 insensitive), and analogously the project defined by @file{release.gpr} is
10581 @code{"Release"}.  For consistency the file should have the same name as the
10582 project, and the project file's extension should be @code{"gpr"}. These
10583 conventions are not required, but a warning is issued if they are not followed.
10585 If the current directory is @file{^/temp^[TEMP]^}, then the command
10586 @smallexample
10587 gnatmake ^-P/common/debug.gpr^/PROJECT_FILE=[COMMON]DEBUG^
10588 @end smallexample
10590 @noindent
10591 generates object and ALI files in @file{^/common/debug^[COMMON.DEBUG]^},
10592 as well as the @code{^proc1^PROC1.EXE^} executable,
10593 using the ^switch^switch^ settings defined in the project file.
10595 Likewise, the command
10596 @smallexample
10597 gnatmake ^-P/common/release.gpr^/PROJECT_FILE=[COMMON]RELEASE^
10598 @end smallexample
10600 @noindent
10601 generates object and ALI files in @file{^/common/release^[COMMON.RELEASE]^},
10602 and the @code{^proc^PROC.EXE^}
10603 executable in @file{^/common^[COMMON]^},
10604 using the ^switch^switch^ settings from the project file.
10606 @node Source Files
10607 @unnumberedsubsubsec Source Files
10609 @noindent
10610 If a project file does not explicitly specify a set of source directories or
10611 a set of source files, then by default the project's source files are the
10612 Ada source files in the project file directory.  Thus @file{pack.ads},
10613 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
10615 @node Specifying the Object Directory
10616 @unnumberedsubsubsec Specifying the Object Directory
10618 @noindent
10619 Several project properties are modeled by Ada-style @emph{attributes};
10620 a property is defined by supplying the equivalent of an Ada attribute
10621 definition clause in the project file.
10622 A project's object directory is another such a property; the corresponding
10623 attribute is @code{Object_Dir}, and its value is also a string expression,
10624 specified either as absolute or relative. In the later case,
10625 it is relative to the project file directory. Thus the compiler's
10626 output is directed to @file{^/common/debug^[COMMON.DEBUG]^}
10627 (for the @code{Debug} project)
10628 and to @file{^/common/release^[COMMON.RELEASE]^}
10629 (for the @code{Release} project).
10630 If @code{Object_Dir} is not specified, then the default is the project file
10631 directory itself.
10633 @node Specifying the Exec Directory
10634 @unnumberedsubsubsec Specifying the Exec Directory
10636 @noindent
10637 A project's exec directory is another property; the corresponding
10638 attribute is @code{Exec_Dir}, and its value is also a string expression,
10639 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
10640 then the default is the object directory (which may also be the project file
10641 directory if attribute @code{Object_Dir} is not specified). Thus the executable
10642 is placed in @file{^/common/debug^[COMMON.DEBUG]^}
10643 for the @code{Debug} project (attribute @code{Exec_Dir} not specified)
10644 and in @file{^/common^[COMMON]^} for the @code{Release} project.
10646 @node Project File Packages
10647 @unnumberedsubsubsec Project File Packages
10649 @noindent
10650 A GNAT tool that is integrated with the Project Manager is modeled by a
10651 corresponding package in the project file. In the example above,
10652 The @code{Debug} project defines the packages @code{Builder}
10653 (for @command{gnatmake}) and @code{Compiler};
10654 the @code{Release} project defines only the @code{Compiler} package.
10656 The Ada-like package syntax is not to be taken literally.  Although packages in
10657 project files bear a surface resemblance to packages in Ada source code, the
10658 notation is simply a way to convey a grouping of properties for a named
10659 entity.  Indeed, the package names permitted in project files are restricted
10660 to a predefined set, corresponding to the project-aware tools, and the contents
10661 of packages are limited to a small set of constructs.
10662 The packages in the example above contain attribute definitions.
10664 @node Specifying ^Switch^Switch^ Settings
10665 @unnumberedsubsubsec Specifying ^Switch^Switch^ Settings
10667 @noindent
10668 ^Switch^Switch^ settings for a project-aware tool can be specified through
10669 attributes in the package that corresponds to the tool.
10670 The example above illustrates one of the relevant attributes,
10671 @code{^Default_Switches^Default_Switches^}, which is defined in packages
10672 in both project files.
10673 Unlike simple attributes like @code{Source_Dirs},
10674 @code{^Default_Switches^Default_Switches^} is
10675 known as an @emph{associative array}.  When you define this attribute, you must
10676 supply an ``index'' (a literal string), and the effect of the attribute
10677 definition is to set the value of the array at the specified index.
10678 For the @code{^Default_Switches^Default_Switches^} attribute,
10679 the index is a programming language (in our case, Ada),
10680 and the value specified (after @code{use}) must be a list
10681 of string expressions.
10683 The attributes permitted in project files are restricted to a predefined set.
10684 Some may appear at project level, others in packages.
10685 For any attribute that is an associative array, the index must always be a
10686 literal string, but the restrictions on this string (e.g., a file name or a
10687 language name) depend on the individual attribute.
10688 Also depending on the attribute, its specified value will need to be either a
10689 string or a string list.
10691 In the @code{Debug} project, we set the switches for two tools,
10692 @command{gnatmake} and the compiler, and thus we include the two corresponding
10693 packages; each package defines the @code{^Default_Switches^Default_Switches^}
10694 attribute with index @code{"Ada"}.
10695 Note that the package corresponding to
10696 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
10697 similar, but only includes the @code{Compiler} package.
10699 In project @code{Debug} above, the ^switches^switches^ starting with
10700 @option{-gnat} that are specified in package @code{Compiler}
10701 could have been placed in package @code{Builder}, since @command{gnatmake}
10702 transmits all such ^switches^switches^ to the compiler.
10704 @node Main Subprograms
10705 @unnumberedsubsubsec Main Subprograms
10707 @noindent
10708 One of the specifiable properties of a project is a list of files that contain
10709 main subprograms.  This property is captured in the @code{Main} attribute,
10710 whose value is a list of strings.  If a project defines the @code{Main}
10711 attribute, it is not necessary to identify the main subprogram(s) when
10712 invoking @command{gnatmake} (@pxref{gnatmake and Project Files}).
10714 @node Executable File Names
10715 @unnumberedsubsubsec Executable File Names
10717 @noindent
10718 By default, the executable file name corresponding to a main source is
10719 deduced from the main source file name. Through the attributes
10720 @code{Executable} and @code{Executable_Suffix} of package @code{Builder},
10721 it is possible to change this default.
10722 In project @code{Debug} above, the executable file name
10723 for main source @file{^proc.adb^PROC.ADB^} is
10724 @file{^proc1^PROC1.EXE^}.
10725 Attribute @code{Executable_Suffix}, when specified, may change the suffix
10726 of the the executable files, when no attribute @code{Executable} applies:
10727 its value replace the platform-specific executable suffix.
10728 Attributes @code{Executable} and @code{Executable_Suffix} are the only ways to
10729 specify a non default executable file name when several mains are built at once
10730 in a single @command{gnatmake} command.
10732 @node Source File Naming Conventions
10733 @unnumberedsubsubsec Source File Naming Conventions
10735 @noindent
10736 Since the project files above do not specify any source file naming
10737 conventions, the GNAT defaults are used.  The mechanism for defining source
10738 file naming conventions -- a package named @code{Naming} --
10739 is described below (@pxref{Naming Schemes}).
10741 @node Source Language(s)
10742 @unnumberedsubsubsec Source Language(s)
10744 @noindent
10745 Since the project files do not specify a @code{Languages} attribute, by
10746 default the GNAT tools assume that the language of the project file is Ada.
10747 More generally, a project can comprise source files
10748 in Ada, C, and/or other languages.
10750 @node Using External Variables
10751 @subsection Using External Variables
10753 @noindent
10754 Instead of supplying different project files for debug and release, we can
10755 define a single project file that queries an external variable (set either
10756 on the command line or via an ^environment variable^logical name^) in order to
10757 conditionally define the appropriate settings.  Again, assume that the
10758 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
10759 located in directory @file{^/common^[COMMON]^}.  The following project file,
10760 @file{build.gpr}, queries the external variable named @code{STYLE} and
10761 defines an object directory and ^switch^switch^ settings based on whether
10762 the value is @code{"deb"} (debug) or @code{"rel"} (release), and where
10763 the default is @code{"deb"}.
10765 @smallexample @c projectfile
10766 @group
10767 project Build is
10768   for Main use ("proc");
10770   type Style_Type is ("deb", "rel");
10771   Style : Style_Type := external ("STYLE", "deb");
10773   case Style is
10774     when "deb" =>
10775       for Object_Dir use "debug";
10777     when "rel" =>
10778       for Object_Dir use "release";
10779       for Exec_Dir use ".";
10780   end case;
10781 @end group
10783 @group
10784   package Builder is
10786     case Style is
10787       when "deb" =>
10788         for ^Default_Switches^Default_Switches^ ("Ada")
10789             use ("^-g^-g^");
10790         for Executable ("proc") use "proc1";
10791       when others =>
10792         null;
10793     end case;
10795   end Builder;
10796 @end group
10798 @group
10799   package Compiler is
10801     case Style is
10802       when "deb" =>
10803         for ^Default_Switches^Default_Switches^ ("Ada")
10804             use ("^-gnata^-gnata^",
10805                  "^-gnato^-gnato^",
10806                  "^-gnatE^-gnatE^");
10808       when "rel" =>
10809         for ^Default_Switches^Default_Switches^ ("Ada")
10810             use ("^-O2^-O2^");
10811     end case;
10813   end Compiler;
10815 end Build;
10816 @end group
10817 @end smallexample
10819 @noindent
10820 @code{Style_Type} is an example of a @emph{string type}, which is the project
10821 file analog of an Ada enumeration type but whose components are string literals
10822 rather than identifiers.  @code{Style} is declared as a variable of this type.
10824 The form @code{external("STYLE", "deb")} is known as an
10825 @emph{external reference}; its first argument is the name of an
10826 @emph{external variable}, and the second argument is a default value to be
10827 used if the external variable doesn't exist.  You can define an external
10828 variable on the command line via the @option{^-X^/EXTERNAL_REFERENCE^} switch,
10829 or you can use ^an environment variable^a logical name^
10830 as an external variable.
10832 Each @code{case} construct is expanded by the Project Manager based on the
10833 value of @code{Style}. Thus the command
10834 @ifclear vms
10835 @smallexample
10836 gnatmake -P/common/build.gpr -XSTYLE=deb
10837 @end smallexample
10838 @end ifclear
10840 @ifset vms
10841 @smallexample
10842 gnatmake /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=deb
10843 @end smallexample
10844 @end ifset
10846 @noindent
10847 is equivalent to the @command{gnatmake} invocation using the project file
10848 @file{debug.gpr} in the earlier example.  So is the command
10849 @smallexample
10850 gnatmake ^-P/common/build.gpr^/PROJECT_FILE=[COMMON]BUILD.GPR^
10851 @end smallexample
10853 @noindent
10854 since @code{"deb"} is the default for @code{STYLE}.
10856 Analogously,
10858 @ifclear vms
10859 @smallexample
10860 gnatmake -P/common/build.gpr -XSTYLE=rel
10861 @end smallexample
10862 @end ifclear
10864 @ifset vms
10865 @smallexample
10866 GNAT MAKE /PROJECT_FILE=[COMMON]BUILD.GPR /EXTERNAL_REFERENCE=STYLE=rel
10867 @end smallexample
10868 @end ifset
10870 @noindent
10871 is equivalent to the @command{gnatmake} invocation using the project file
10872 @file{release.gpr} in the earlier example.
10874 @node Importing Other Projects
10875 @subsection Importing Other Projects
10877 @noindent
10878 A compilation unit in a source file in one project may depend on compilation
10879 units in source files in other projects.  To compile this unit under
10880 control of a project file, the
10881 dependent project must @emph{import} the projects containing the needed source
10882 files.
10883 This effect is obtained using syntax similar to an Ada @code{with} clause,
10884 but where @code{with}ed entities are strings that denote project files.
10886 As an example, suppose that the two projects @code{GUI_Proj} and
10887 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
10888 @file{comm_proj.gpr} in directories @file{^/gui^[GUI]^}
10889 and @file{^/comm^[COMM]^}, respectively.
10890 Suppose that the source files for @code{GUI_Proj} are
10891 @file{gui.ads} and @file{gui.adb}, and that the source files for
10892 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, where each set of
10893 files is located in its respective project file directory.  Schematically:
10895 @smallexample
10896 @group
10897 ^/gui^[GUI]^
10898   gui_proj.gpr
10899   gui.ads
10900   gui.adb
10901 @end group
10903 @group
10904 ^/comm^[COMM]^
10905   comm_proj.gpr
10906   comm.ads
10907   comm.adb
10908 @end group
10909 @end smallexample
10911 @noindent
10912 We want to develop an application in directory @file{^/app^[APP]^} that
10913 @code{with} the packages @code{GUI} and @code{Comm}, using the properties of
10914 the corresponding project files (e.g. the ^switch^switch^ settings
10915 and object directory).
10916 Skeletal code for a main procedure might be something like the following:
10918 @smallexample @c ada
10919 @group
10920 with GUI, Comm;
10921 procedure App_Main is
10922    ...
10923 begin
10924    ...
10925 end App_Main;
10926 @end group
10927 @end smallexample
10929 @noindent
10930 Here is a project file, @file{app_proj.gpr}, that achieves the desired
10931 effect:
10933 @smallexample @c projectfile
10934 @group
10935 with "/gui/gui_proj", "/comm/comm_proj";
10936 project App_Proj is
10937    for Main use ("app_main");
10938 end App_Proj;
10939 @end group
10940 @end smallexample
10942 @noindent
10943 Building an executable is achieved through the command:
10944 @smallexample
10945 gnatmake ^-P/app/app_proj^/PROJECT_FILE=[APP]APP_PROJ^
10946 @end smallexample
10947 @noindent
10948 which will generate the @code{^app_main^APP_MAIN.EXE^} executable
10949 in the directory where @file{app_proj.gpr} resides.
10951 If an imported project file uses the standard extension (@code{^gpr^GPR^}) then
10952 (as illustrated above) the @code{with} clause can omit the extension.
10954 Our example specified an absolute path for each imported project file.
10955 Alternatively, the directory name of an imported object can be omitted
10956 if either
10957 @itemize @bullet
10958 @item
10959 The imported project file is in the same directory as the importing project
10960 file, or
10961 @item
10962 You have defined ^an environment variable^a logical name^
10963 that includes the directory containing
10964 the needed project file. The syntax of @code{ADA_PROJECT_PATH} is the same as
10965 the syntax of @code{ADA_INCLUDE_PATH} and @code{ADA_OBJECTS_PATH}: a list of
10966 directory names separated by colons (semicolons on Windows).
10967 @end itemize
10969 @noindent
10970 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{^/gui^[GUI]^} and
10971 @file{^/comm^[COMM]^}, then our project file @file{app_proj.gpr} can be written
10972 as follows:
10974 @smallexample @c projectfile
10975 @group
10976 with "gui_proj", "comm_proj";
10977 project App_Proj is
10978    for Main use ("app_main");
10979 end App_Proj;
10980 @end group
10981 @end smallexample
10983 @noindent
10984 Importing other projects can create ambiguities.
10985 For example, the same unit might be present in different imported projects, or
10986 it might be present in both the importing project and in an imported project.
10987 Both of these conditions are errors.  Note that in the current version of
10988 the Project Manager, it is illegal to have an ambiguous unit even if the
10989 unit is never referenced by the importing project.  This restriction may be
10990 relaxed in a future release.
10992 @node Extending a Project
10993 @subsection Extending a Project
10995 @noindent
10996 In large software systems it is common to have multiple
10997 implementations of a common interface; in Ada terms, multiple versions of a
10998 package body for the same specification.  For example, one implementation
10999 might be safe for use in tasking programs, while another might only be used
11000 in sequential applications.  This can be modeled in GNAT using the concept
11001 of @emph{project extension}.  If one project (the ``child'') @emph{extends}
11002 another project (the ``parent'') then by default all source files of the
11003 parent project are inherited by the child, but the child project can
11004 override any of the parent's source files with new versions, and can also
11005 add new files.  This facility is the project analog of a type extension in
11006 Object-Oriented Programming.  Project hierarchies are permitted (a child
11007 project may be the parent of yet another project), and a project that
11008 inherits one project can also import other projects.
11010 As an example, suppose that directory @file{^/seq^[SEQ]^} contains the project
11011 file @file{seq_proj.gpr} as well as the source files @file{pack.ads},
11012 @file{pack.adb}, and @file{proc.adb}:
11014 @smallexample
11015 @group
11016 ^/seq^[SEQ]^
11017   pack.ads
11018   pack.adb
11019   proc.adb
11020   seq_proj.gpr
11021 @end group
11022 @end smallexample
11024 @noindent
11025 Note that the project file can simply be empty (that is, no attribute or
11026 package is defined):
11028 @smallexample @c projectfile
11029 @group
11030 project Seq_Proj is
11031 end Seq_Proj;
11032 @end group
11033 @end smallexample
11035 @noindent
11036 implying that its source files are all the Ada source files in the project
11037 directory.
11039 Suppose we want to supply an alternate version of @file{pack.adb}, in
11040 directory @file{^/tasking^[TASKING]^}, but use the existing versions of
11041 @file{pack.ads} and @file{proc.adb}.  We can define a project
11042 @code{Tasking_Proj} that inherits @code{Seq_Proj}:
11044 @smallexample
11045 @group
11046 ^/tasking^[TASKING]^
11047   pack.adb
11048   tasking_proj.gpr
11049 @end group
11051 @group
11052 project Tasking_Proj extends "/seq/seq_proj" is
11053 end Tasking_Proj;
11054 @end group
11055 @end smallexample
11057 @noindent
11058 The version of @file{pack.adb} used in a build depends on which project file
11059 is specified.
11061 Note that we could have obtained the desired behavior using project import
11062 rather than project inheritance; a @code{base} project would contain the
11063 sources for @file{pack.ads} and @file{proc.adb}, a sequential project would
11064 import @code{base} and add @file{pack.adb}, and likewise a tasking project
11065 would import @code{base} and add a different version of @file{pack.adb}.  The
11066 choice depends on whether other sources in the original project need to be
11067 overridden.  If they do, then project extension is necessary, otherwise,
11068 importing is sufficient.
11070 @noindent
11071 In a project file that extends another project file, it is possible to
11072 indicate that an inherited source is not part of the sources of the extending
11073 project. This is necessary sometimes when a package spec has been overloaded
11074 and no longer requires a body: in this case, it is necessary to indicate that
11075 the inherited body is not part of the sources of the project, otherwise there
11076 will be a compilation error when compiling the spec.
11078 For that purpose, the attribute @code{Locally_Removed_Files} is used.
11079 Its value is a string list: a list of file names.
11081 @smallexample @c @projectfile
11082 project B extends "a" is
11083    for Source_Files use ("pkg.ads");
11084    --  New spec of Pkg does not need a completion
11085    for Locally_Removed_Files use ("pkg.adb");
11086 end B;
11087 @end smallexample
11089 Attribute @code{Locally_Removed_Files} may also be used to check if a source
11090 is still needed: if it is possible to build using @command{gnatmake} when such
11091 a source is put in attribute @code{Locally_Removed_Files} of a project P, then
11092 it is possible to remove the source completely from a system that includes
11093 project P.
11095 @c ***********************
11096 @c * Project File Syntax *
11097 @c ***********************
11099 @node Project File Syntax
11100 @section Project File Syntax
11102 @menu
11103 * Basic Syntax::
11104 * Packages::
11105 * Expressions::
11106 * String Types::
11107 * Variables::
11108 * Attributes::
11109 * Associative Array Attributes::
11110 * case Constructions::
11111 @end menu
11113 @noindent
11114 This section describes the structure of project files.
11116 A project may be an @emph{independent project}, entirely defined by a single
11117 project file. Any Ada source file in an independent project depends only
11118 on the predefined library and other Ada source files in the same project.
11120 @noindent
11121 A project may also @dfn{depend on} other projects, in either or both of
11122 the following ways:
11123 @itemize @bullet
11124 @item It may import any number of projects
11125 @item It may extend at most one other project
11126 @end itemize
11128 @noindent
11129 The dependence relation is a directed acyclic graph (the subgraph reflecting
11130 the ``extends'' relation is a tree).
11132 A project's @dfn{immediate sources} are the source files directly defined by
11133 that project, either implicitly by residing in the project file's directory,
11134 or explicitly through any of the source-related attributes described below.
11135 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
11136 of @var{proj} together with the immediate sources (unless overridden) of any
11137 project on which @var{proj} depends (either directly or indirectly).
11139 @node Basic Syntax
11140 @subsection Basic Syntax
11142 @noindent
11143 As seen in the earlier examples, project files have an Ada-like syntax.
11144 The minimal project file is:
11145 @smallexample @c projectfile
11146 @group
11147 project Empty is
11149 end Empty;
11150 @end group
11151 @end smallexample
11153 @noindent
11154 The identifier @code{Empty} is the name of the project.
11155 This project name must be present after the reserved
11156 word @code{end} at the end of the project file, followed by a semi-colon.
11158 Any name in a project file, such as the project name or a variable name,
11159 has the same syntax as an Ada identifier.
11161 The reserved words of project files are the Ada reserved words plus
11162 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
11163 reserved words currently used in project file syntax are:
11165 @itemize @bullet
11166 @item
11167 @code{case}
11168 @item
11169 @code{end}
11170 @item
11171 @code{for}
11172 @item
11173 @code{is}
11174 @item
11175 @code{others}
11176 @item
11177 @code{package}
11178 @item
11179 @code{renames}
11180 @item
11181 @code{type}
11182 @item
11183 @code{use}
11184 @item
11185 @code{when}
11186 @item
11187 @code{with}
11188 @end itemize
11190 @noindent
11191 Comments in project files have the same syntax as in Ada, two consecutives
11192 hyphens through the end of the line.
11194 @node Packages
11195 @subsection Packages
11197 @noindent
11198 A project file may contain @emph{packages}. The name of a package must be one
11199 of the identifiers from the following list. A package
11200 with a given name may only appear once in a project file. Package names are
11201 case insensitive. The following package names are legal:
11203 @itemize @bullet
11204 @item
11205 @code{Naming}
11206 @item
11207 @code{Builder}
11208 @item
11209 @code{Compiler}
11210 @item
11211 @code{Binder}
11212 @item
11213 @code{Linker}
11214 @item
11215 @code{Finder}
11216 @item
11217 @code{Cross_Reference}
11218 @item
11219 @code{Eliminate}
11220 @item
11221 @code{Pretty_Printer}
11222 @item
11223 @code{Metrics}
11224 @item
11225 @code{gnatls}
11226 @item
11227 @code{gnatstub}
11228 @item
11229 @code{IDE}
11230 @item
11231 @code{Language_Processing}
11232 @end itemize
11234 @noindent
11235 In its simplest form, a package may be empty:
11237 @smallexample @c projectfile
11238 @group
11239 project Simple is
11240   package Builder is
11241   end Builder;
11242 end Simple;
11243 @end group
11244 @end smallexample
11246 @noindent
11247 A package may contain @emph{attribute declarations},
11248 @emph{variable declarations} and @emph{case constructions}, as will be
11249 described below.
11251 When there is ambiguity between a project name and a package name,
11252 the name always designates the project. To avoid possible confusion, it is
11253 always a good idea to avoid naming a project with one of the
11254 names allowed for packages or any name that starts with @code{gnat}.
11256 @node Expressions
11257 @subsection Expressions
11259 @noindent
11260 An @emph{expression} is either a @emph{string expression} or a
11261 @emph{string list expression}.
11263 A @emph{string expression} is either a @emph{simple string expression} or a
11264 @emph{compound string expression}.
11266 A @emph{simple string expression} is one of the following:
11267 @itemize @bullet
11268 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
11269 @item A string-valued variable reference (@pxref{Variables})
11270 @item A string-valued attribute reference (@pxref{Attributes})
11271 @item An external reference (@pxref{External References in Project Files})
11272 @end itemize
11274 @noindent
11275 A @emph{compound string expression} is a concatenation of string expressions,
11276 using the operator @code{"&"}
11277 @smallexample
11278        Path & "/" & File_Name & ".ads"
11279 @end smallexample
11281 @noindent
11282 A @emph{string list expression} is either a
11283 @emph{simple string list expression} or a
11284 @emph{compound string list expression}.
11286 A @emph{simple string list expression} is one of the following:
11287 @itemize @bullet
11288 @item A parenthesized list of zero or more string expressions,
11289 separated by commas
11290 @smallexample
11291    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
11292    Empty_List := ();
11293 @end smallexample
11294 @item A string list-valued variable reference
11295 @item A string list-valued attribute reference
11296 @end itemize
11298 @noindent
11299 A @emph{compound string list expression} is the concatenation (using
11300 @code{"&"}) of a simple string list expression and an expression.  Note that
11301 each term in a compound string list expression, except the first, may be
11302 either a string expression or a string list expression.
11304 @smallexample @c projectfile
11305 @group
11306    File_Name_List := () & File_Name; --  One string in this list
11307    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
11308    --  Two strings
11309    Big_List := File_Name_List & Extended_File_Name_List;
11310    --  Concatenation of two string lists: three strings
11311    Illegal_List := "gnat.adc" & Extended_File_Name_List;
11312    --  Illegal: must start with a string list
11313 @end group
11314 @end smallexample
11316 @node String Types
11317 @subsection String Types
11319 @noindent
11320 A @emph{string type declaration} introduces a discrete set of string literals.
11321 If a string variable is declared to have this type, its value
11322 is restricted to the given set of literals.
11324 Here is an example of a string type declaration:
11326 @smallexample @c projectfile
11327    type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
11328 @end smallexample
11330 @noindent
11331 Variables of a string type are called @emph{typed variables}; all other
11332 variables are called @emph{untyped variables}. Typed variables are
11333 particularly useful in @code{case} constructions, to support conditional
11334 attribute declarations.
11335 (@pxref{case Constructions}).
11337 The string literals in the list are case sensitive and must all be different.
11338 They may include any graphic characters allowed in Ada, including spaces.
11340 A string type may only be declared at the project level, not inside a package.
11342 A string type may be referenced by its name if it has been declared in the same
11343 project file, or by an expanded name whose prefix is the name of the project
11344 in which it is declared.
11346 @node Variables
11347 @subsection Variables
11349 @noindent
11350 A variable may be declared at the project file level, or within a package.
11351 Here are some examples of variable declarations:
11353 @smallexample @c projectfile
11354 @group
11355    This_OS : OS := external ("OS"); --  a typed variable declaration
11356    That_OS := "GNU/Linux";          --  an untyped variable declaration
11357 @end group
11358 @end smallexample
11360 @noindent
11361 The syntax of a @emph{typed variable declaration} is identical to the Ada
11362 syntax for an object declaration. By contrast, the syntax of an untyped
11363 variable declaration is identical to an Ada assignment statement. In fact,
11364 variable declarations in project files have some of the characteristics of
11365 an assignment, in that successive declarations for the same variable are
11366 allowed. Untyped variable declarations do establish the expected kind of the
11367 variable (string or string list), and successive declarations for it must
11368 respect the initial kind.
11370 @noindent
11371 A string variable declaration (typed or untyped) declares a variable
11372 whose value is a string. This variable may be used as a string expression.
11373 @smallexample @c projectfile
11374    File_Name       := "readme.txt";
11375    Saved_File_Name := File_Name & ".saved";
11376 @end smallexample
11378 @noindent
11379 A string list variable declaration declares a variable whose value is a list
11380 of strings. The list may contain any number (zero or more) of strings.
11382 @smallexample @c projectfile
11383    Empty_List := ();
11384    List_With_One_Element := ("^-gnaty^-gnaty^");
11385    List_With_Two_Elements := List_With_One_Element & "^-gnatg^-gnatg^";
11386    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
11387                  "pack2.ada", "util_.ada", "util.ada");
11388 @end smallexample
11390 @noindent
11391 The same typed variable may not be declared more than once at project level,
11392 and it may not be declared more than once in any package; it is in effect
11393 a constant.
11395 The same untyped variable may be declared several times. Declarations are
11396 elaborated in the order in which they appear, so  the new value replaces
11397 the old one, and any subsequent reference to the variable uses the new value.
11398 However, as noted above, if a variable has been declared as a string, all
11399 subsequent
11400 declarations must give it a string value. Similarly, if a variable has
11401 been declared as a string list, all subsequent declarations
11402 must give it a string list value.
11404 A @emph{variable reference} may take several forms:
11406 @itemize @bullet
11407 @item The simple variable name, for a variable in the current package (if any)
11408 or in the current project
11409 @item An expanded name, whose prefix is a context name.
11410 @end itemize
11412 @noindent
11413 A @emph{context} may be one of the following:
11415 @itemize @bullet
11416 @item The name of an existing package in the current project
11417 @item The name of an imported project of the current project
11418 @item The name of an ancestor project (i.e., a project extended by the current
11419 project, either directly or indirectly)
11420 @item An expanded name whose prefix is an imported/parent project name, and
11421 whose selector is a package name in that project.
11422 @end itemize
11424 @noindent
11425 A variable reference may be used in an expression.
11427 @node Attributes
11428 @subsection Attributes
11430 @noindent
11431 A project (and its packages) may have @emph{attributes} that define
11432 the project's properties.  Some attributes have values that are strings;
11433 others have values that are string lists.
11435 There are two categories of attributes: @emph{simple attributes}
11436 and @emph{associative arrays} (@pxref{Associative Array Attributes}).
11438 Legal project attribute names, and attribute names for each legal package are
11439 listed below. Attributes names are case-insensitive.
11441 The following attributes are defined on projects (all are simple attributes):
11443 @multitable @columnfractions .4 .3
11444 @item @emph{Attribute Name}
11445 @tab @emph{Value}
11446 @item @code{Source_Files}
11447 @tab string list
11448 @item @code{Source_Dirs}
11449 @tab string list
11450 @item @code{Source_List_File}
11451 @tab string
11452 @item @code{Object_Dir}
11453 @tab string
11454 @item @code{Exec_Dir}
11455 @tab string
11456 @item @code{Locally_Removed_Files}
11457 @tab string list
11458 @item @code{Main}
11459 @tab string list
11460 @item @code{Languages}
11461 @tab string list
11462 @item @code{Main_Language}
11463 @tab string
11464 @item @code{Library_Dir}
11465 @tab string
11466 @item @code{Library_Name}
11467 @tab string
11468 @item @code{Library_Kind}
11469 @tab string
11470 @item @code{Library_Version}
11471 @tab string
11472 @item @code{Library_Interface}
11473 @tab string
11474 @item @code{Library_Auto_Init}
11475 @tab string
11476 @item @code{Library_Options}
11477 @tab string list
11478 @item @code{Library_GCC}
11479 @tab string
11480 @end multitable
11482 @noindent
11483 The following attributes are defined for package  @code{Naming}
11484 (@pxref{Naming Schemes}):
11486 @multitable @columnfractions .4 .2 .2 .2
11487 @item Attribute Name @tab Category @tab Index @tab Value
11488 @item @code{Spec_Suffix}
11489 @tab associative array
11490 @tab language name
11491 @tab string
11492 @item @code{Body_Suffix}
11493 @tab associative array
11494 @tab language name
11495 @tab string
11496 @item @code{Separate_Suffix}
11497 @tab simple attribute
11498 @tab n/a
11499 @tab string
11500 @item @code{Casing}
11501 @tab simple attribute
11502 @tab n/a
11503 @tab string
11504 @item @code{Dot_Replacement}
11505 @tab simple attribute
11506 @tab n/a
11507 @tab string
11508 @item @code{Spec}
11509 @tab associative array
11510 @tab Ada unit name
11511 @tab string
11512 @item @code{Body}
11513 @tab associative array
11514 @tab Ada unit name
11515 @tab string
11516 @item @code{Specification_Exceptions}
11517 @tab associative array
11518 @tab language name
11519 @tab string list
11520 @item @code{Implementation_Exceptions}
11521 @tab associative array
11522 @tab language name
11523 @tab string list
11524 @end multitable
11526 @noindent
11527 The following attributes are defined for packages @code{Builder},
11528 @code{Compiler}, @code{Binder},
11529 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
11530 (@pxref{^Switches^Switches^ and Project Files}).
11532 @multitable @columnfractions .4 .2 .2 .2
11533 @item Attribute Name @tab Category @tab Index @tab Value
11534 @item @code{^Default_Switches^Default_Switches^}
11535 @tab associative array
11536 @tab language name
11537 @tab string list
11538 @item @code{^Switches^Switches^}
11539 @tab associative array
11540 @tab file name
11541 @tab string list
11542 @end multitable
11544 @noindent
11545 In addition, package @code{Compiler} has a single string attribute
11546 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
11547 string attribute @code{Global_Configuration_Pragmas}.
11549 @noindent
11550 Each simple attribute has a default value: the empty string (for string-valued
11551 attributes) and the empty list (for string list-valued attributes).
11553 An attribute declaration defines a new value for an attribute.
11555 Examples of simple attribute declarations:
11557 @smallexample @c projectfile
11558    for Object_Dir use "objects";
11559    for Source_Dirs use ("units", "test/drivers");
11560 @end smallexample
11562 @noindent
11563 The syntax of a @dfn{simple attribute declaration} is similar to that of an
11564 attribute definition clause in Ada.
11566 Attributes references may be appear in expressions.
11567 The general form for such a reference is @code{<entity>'<attribute>}:
11568 Associative array attributes are functions. Associative
11569 array attribute references must have an argument that is a string literal.
11571 Examples are:
11573 @smallexample @c projectfile
11574   project'Object_Dir
11575   Naming'Dot_Replacement
11576   Imported_Project'Source_Dirs
11577   Imported_Project.Naming'Casing
11578   Builder'^Default_Switches^Default_Switches^("Ada")
11579 @end smallexample
11581 @noindent
11582 The prefix of an attribute may be:
11583 @itemize @bullet
11584 @item @code{project} for an attribute of the current project
11585 @item The name of an existing package of the current project
11586 @item The name of an imported project
11587 @item The name of a parent project that is extended by the current project
11588 @item An expanded name whose prefix is imported/parent project name,
11589       and whose selector is a package name
11590 @end itemize
11592 @noindent
11593 Example:
11594 @smallexample @c projectfile
11595 @group
11596    project Prj is
11597      for Source_Dirs use project'Source_Dirs & "units";
11598      for Source_Dirs use project'Source_Dirs & "test/drivers"
11599    end Prj;
11600 @end group
11601 @end smallexample
11603 @noindent
11604 In the first attribute declaration, initially the attribute @code{Source_Dirs}
11605 has the default value: an empty string list. After this declaration,
11606 @code{Source_Dirs} is a string list of one element: @code{"units"}.
11607 After the second attribute declaration @code{Source_Dirs} is a string list of
11608 two elements: @code{"units"} and @code{"test/drivers"}.
11610 Note: this example is for illustration only. In practice,
11611 the project file would contain only one attribute declaration:
11613 @smallexample @c projectfile
11614    for Source_Dirs use ("units", "test/drivers");
11615 @end smallexample
11617 @node Associative Array Attributes
11618 @subsection Associative Array Attributes
11620 @noindent
11621 Some attributes are defined as @emph{associative arrays}. An associative
11622 array may be regarded as a function that takes a string as a parameter
11623 and delivers a string or string list value as its result.
11625 Here are some examples of single associative array attribute associations:
11627 @smallexample @c projectfile
11628    for Body ("main") use "Main.ada";
11629    for ^Switches^Switches^ ("main.ada")
11630        use ("^-v^-v^",
11631             "^-gnatv^-gnatv^");
11632    for ^Switches^Switches^ ("main.ada")
11633             use Builder'^Switches^Switches^ ("main.ada")
11634               & "^-g^-g^";
11635 @end smallexample
11637 @noindent
11638 Like untyped variables and simple attributes, associative array attributes
11639 may be declared several times. Each declaration supplies a new value for the
11640 attribute, and replaces the previous setting.
11642 @noindent
11643 An associative array attribute may be declared as a full associative array
11644 declaration, with the value of the same attribute in an imported or extended
11645 project.
11647 @smallexample @c projectfile
11648    package Builder is
11649       for Default_Switches use Default.Builder'Default_Switches;
11650    end Builder;
11651 @end smallexample
11653 @noindent
11654 In this example, @code{Default} must be either an project imported by the
11655 current project, or the project that the current project extends. If the
11656 attribute is in a package (in this case, in package @code{Builder}), the same
11657 package needs to be specified.
11659 @noindent
11660 A full associative array declaration replaces any other declaration for the
11661 attribute, including other full associative array declaration. Single
11662 associative array associations may be declare after a full associative
11663 declaration, modifying the value for a single association of the attribute.
11665 @node case Constructions
11666 @subsection @code{case} Constructions
11668 @noindent
11669 A @code{case} construction is used in a project file to effect conditional
11670 behavior.
11671 Here is a typical example:
11673 @smallexample @c projectfile
11674 @group
11675 project MyProj is
11676    type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
11678    OS : OS_Type := external ("OS", "GNU/Linux");
11679 @end group
11681 @group
11682    package Compiler is
11683      case OS is
11684        when "GNU/Linux" | "Unix" =>
11685          for ^Default_Switches^Default_Switches^ ("Ada")
11686              use ("^-gnath^-gnath^");
11687        when "NT" =>
11688          for ^Default_Switches^Default_Switches^ ("Ada")
11689              use ("^-gnatP^-gnatP^");
11690        when others =>
11691      end case;
11692    end Compiler;
11693 end MyProj;
11694 @end group
11695 @end smallexample
11697 @noindent
11698 The syntax of a @code{case} construction is based on the Ada case statement
11699 (although there is no @code{null} construction for empty alternatives).
11701 The case expression must a typed string variable.
11702 Each alternative comprises the reserved word @code{when}, either a list of
11703 literal strings separated by the @code{"|"} character or the reserved word
11704 @code{others},  and the @code{"=>"} token.
11705 Each literal string must belong to the string type that is the type of the
11706 case variable.
11707 An @code{others} alternative, if present, must occur last.
11709 After each @code{=>}, there are zero or more constructions.  The only
11710 constructions allowed in a case construction are other case constructions and
11711 attribute declarations. String type declarations, variable declarations and
11712 package declarations are not allowed.
11714 The value of the case variable is often given by an external reference
11715 (@pxref{External References in Project Files}).
11717 @c ****************************************
11718 @c * Objects and Sources in Project Files *
11719 @c ****************************************
11721 @node Objects and Sources in Project Files
11722 @section Objects and Sources in Project Files
11724 @menu
11725 * Object Directory::
11726 * Exec Directory::
11727 * Source Directories::
11728 * Source File Names::
11729 @end menu
11731 @noindent
11732 Each project has exactly one object directory and one or more source
11733 directories. The source directories must contain at least one source file,
11734 unless  the project file explicitly specifies that no source files are present
11735 (@pxref{Source File Names}).
11737 @node Object Directory
11738 @subsection Object Directory
11740 @noindent
11741 The object directory for a project is the directory containing the compiler's
11742 output (such as @file{ALI} files and object files) for the project's immediate
11743 sources.
11745 The object directory is given by the value of the attribute @code{Object_Dir}
11746 in the project file.
11748 @smallexample @c projectfile
11749    for Object_Dir use "objects";
11750 @end smallexample
11752 @noindent
11753 The attribute @var{Object_Dir} has a string value, the path name of the object
11754 directory. The path name may be absolute or relative to the directory of the
11755 project file. This directory must already exist, and be readable and writable.
11757 By default, when the attribute @code{Object_Dir} is not given an explicit value
11758 or when its value is the empty string, the object directory is the same as the
11759 directory containing the project file.
11761 @node Exec Directory
11762 @subsection Exec Directory
11764 @noindent
11765 The exec directory for a project is the directory containing the executables
11766 for the project's main subprograms.
11768 The exec directory is given by the value of the attribute @code{Exec_Dir}
11769 in the project file.
11771 @smallexample @c projectfile
11772    for Exec_Dir use "executables";
11773 @end smallexample
11775 @noindent
11776 The attribute @var{Exec_Dir} has a string value, the path name of the exec
11777 directory. The path name may be absolute or relative to the directory of the
11778 project file. This directory must already exist, and be writable.
11780 By default, when the attribute @code{Exec_Dir} is not given an explicit value
11781 or when its value is the empty string, the exec directory is the same as the
11782 object directory of the project file.
11784 @node Source Directories
11785 @subsection Source Directories
11787 @noindent
11788 The source directories of a project are specified by the project file
11789 attribute @code{Source_Dirs}.
11791 This attribute's value is a string list. If the attribute is not given an
11792 explicit value, then there is only one source directory, the one where the
11793 project file resides.
11795 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
11796 as in
11798 @smallexample @c projectfile
11799     for Source_Dirs use ();
11800 @end smallexample
11802 @noindent
11803 indicates that the project contains no source files.
11805 Otherwise, each string in the string list designates one or more
11806 source directories.
11808 @smallexample @c projectfile
11809    for Source_Dirs use ("sources", "test/drivers");
11810 @end smallexample
11812 @noindent
11813 If a string in the list ends with @code{"/**"},  then the directory whose path
11814 name precedes the two asterisks, as well as all its subdirectories
11815 (recursively), are source directories.
11817 @smallexample @c projectfile
11818    for Source_Dirs use ("/system/sources/**");
11819 @end smallexample
11821 @noindent
11822 Here the directory @code{/system/sources} and all of its subdirectories
11823 (recursively) are source directories.
11825 To specify that the source directories are the directory of the project file
11826 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
11827 @smallexample @c projectfile
11828    for Source_Dirs use ("./**");
11829 @end smallexample
11831 @noindent
11832 Each of the source directories must exist and be readable.
11834 @node Source File Names
11835 @subsection Source File Names
11837 @noindent
11838 In a project that contains source files, their names may be specified by the
11839 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
11840 (a string). Source file names never include any directory information.
11842 If the attribute @code{Source_Files} is given an explicit value, then each
11843 element of the list is a source file name.
11845 @smallexample @c projectfile
11846    for Source_Files use ("main.adb");
11847    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
11848 @end smallexample
11850 @noindent
11851 If the attribute @code{Source_Files} is not given an explicit value,
11852 but the attribute @code{Source_List_File} is given a string value,
11853 then the source file names are contained in the text file whose path name
11854 (absolute or relative to the directory of the project file) is the
11855 value of the attribute @code{Source_List_File}.
11857 Each line in the file that is not empty or is not a comment
11858 contains a source file name.
11860 @smallexample @c projectfile
11861    for Source_List_File use "source_list.txt";
11862 @end smallexample
11864 @noindent
11865 By default, if neither the attribute @code{Source_Files} nor the attribute
11866 @code{Source_List_File} is given an explicit value, then each file in the
11867 source directories that conforms to the project's naming scheme
11868 (@pxref{Naming Schemes}) is an immediate source of the project.
11870 A warning is issued if both attributes @code{Source_Files} and
11871 @code{Source_List_File} are given explicit values. In this case, the attribute
11872 @code{Source_Files} prevails.
11874 Each source file name must be the name of one existing source file
11875 in one of the source directories.
11877 A @code{Source_Files} attribute whose value is an empty list
11878 indicates that there are no source files in the project.
11880 If the order of the source directories is known statically, that is if
11881 @code{"/**"} is not used in the string list @code{Source_Dirs}, then there may
11882 be several files with the same source file name. In this case, only the file
11883 in the first directory is considered as an immediate source of the project
11884 file. If the order of the source directories is not known statically, it is
11885 an error to have several files with the same source file name.
11887 Projects can be specified to have no Ada source
11888 files: the value of (@code{Source_Dirs} or @code{Source_Files} may be an empty
11889 list, or the @code{"Ada"} may be absent from @code{Languages}:
11891 @smallexample @c projectfile
11892    for Source_Dirs use ();
11893    for Source_Files use ();
11894    for Languages use ("C", "C++");
11895 @end smallexample
11897 @noindent
11898 Otherwise, a project must contain at least one immediate source.
11900 Projects with no source files are useful as template packages
11901 (@pxref{Packages in Project Files}) for other projects; in particular to
11902 define a package @code{Naming} (@pxref{Naming Schemes}).
11904 @c ****************************
11905 @c * Importing Projects *
11906 @c ****************************
11908 @node  Importing Projects
11909 @section Importing Projects
11911 @noindent
11912 An immediate source of a project P may depend on source files that
11913 are neither immediate sources of P nor in the predefined library.
11914 To get this effect, P must @emph{import} the projects that contain the needed
11915 source files.
11917 @smallexample @c projectfile
11918 @group
11919   with "project1", "utilities.gpr";
11920   with "/namings/apex.gpr";
11921   project Main is
11922     ...
11923 @end group
11924 @end smallexample
11926 @noindent
11927 As can be seen in this example, the syntax for importing projects is similar
11928 to the syntax for importing compilation units in Ada. However, project files
11929 use literal strings instead of names, and the @code{with} clause identifies
11930 project files rather than packages.
11932 Each literal string is the file name or path name (absolute or relative) of a
11933 project file. If a string is simply a file name, with no path, then its
11934 location is determined by the @emph{project path}:
11936 @itemize @bullet
11937 @item
11938 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} exists,
11939 then the project path includes all the directories in this
11940 ^environment variable^logical name^, plus the directory of the project file.
11942 @item
11943 If the ^environment variable^logical name^ @env{ADA_PROJECT_PATH} does not
11944 exist, then the project path contains only one directory, namely the one where
11945 the project file is located.
11946 @end itemize
11948 @noindent
11949 If a relative pathname is used, as in
11951 @smallexample @c projectfile
11952   with "tests/proj";
11953 @end smallexample
11955 @noindent
11956 then the path is relative to the directory where the importing project file is
11957 located. Any symbolic link will be fully resolved in the directory
11958 of the importing project file before the imported project file is examined.
11960 If the @code{with}'ed project file name does not have an extension,
11961 the default is @file{^.gpr^.GPR^}. If a file with this extension is not found,
11962 then the file name as specified in the @code{with} clause (no extension) will
11963 be used. In the above example, if a file @code{project1.gpr} is found, then it
11964 will be used; otherwise, if a file @code{^project1^PROJECT1^} exists
11965 then it will be used; if neither file exists, this is an error.
11967 A warning is issued if the name of the project file does not match the
11968 name of the project; this check is case insensitive.
11970 Any source file that is an immediate source of the imported project can be
11971 used by the immediate sources of the importing project, transitively. Thus
11972 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
11973 sources of @code{A} may depend on the immediate sources of @code{C}, even if
11974 @code{A} does not import @code{C} explicitly. However, this is not recommended,
11975 because if and when @code{B} ceases to import @code{C}, some sources in
11976 @code{A} will no longer compile.
11978 A side effect of this capability is that normally cyclic dependencies are not
11979 permitted: if @code{A} imports @code{B} (directly or indirectly) then @code{B}
11980 is not allowed to import @code{A}. However, there are cases when cyclic
11981 dependencies would be beneficial. For these cases, another form of import
11982 between projects exists, the @code{limited with}: a project @code{A} that
11983 imports a project @code{B} with a straigh @code{with} may also be imported,
11984 directly or indirectly, by @code{B} on the condition that imports from @code{B}
11985 to @code{A} include at least one @code{limited with}.
11987 @smallexample @c 0projectfile
11988 with "../b/b.gpr";
11989 with "../c/c.gpr";
11990 project A is
11991 end A;
11993 limited with "../a/a.gpr";
11994 project B is
11995 end B;
11997 with "../d/d.gpr";
11998 project C is
11999 end C;
12001 limited with "../a/a.gpr";
12002 project D is
12003 end D;
12004 @end smallexample
12006 @noindent
12007 In the above legal example, there are two project cycles:
12008 @itemize @bullet
12009 @item A-> B-> A
12010 @item A -> C -> D -> A
12011 @end itemize
12013 @noindent
12014 In each of these cycle there is one @code{limited with}: import of @code{A}
12015 from @code{B} and import of @code{A} from @code{D}.
12017 The difference between straight @code{with} and @code{limited with} is that
12018 the name of a project imported with a @code{limited with} cannot be used in the
12019 project that imports it. In particular, its packages cannot be renamed and
12020 its variables cannot be referred to.
12022 An exception to the above rules for @code{limited with} is that for the main
12023 project specified to @command{gnatmake} or to the @command{GNAT} driver a
12024 @code{limited with} is equivalent to a straight @code{with}. For example,
12025 in the example above, projects @code{B} and @code{D} could not be main
12026 projects for @command{gnatmake} or to the @command{GNAT} driver, because they
12027 each have a @code{limited with} that is the only one in a cycle of importing
12028 projects.
12030 @c *********************
12031 @c * Project Extension *
12032 @c *********************
12034 @node Project Extension
12035 @section Project Extension
12037 @noindent
12038 During development of a large system, it is sometimes necessary to use
12039 modified versions of some of the source files, without changing the original
12040 sources. This can be achieved through the @emph{project extension} facility.
12042 @smallexample @c projectfile
12043    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
12044 @end smallexample
12046 @noindent
12047 A project extension declaration introduces an extending project
12048 (the @emph{child}) and a project being extended (the @emph{parent}).
12050 By default, a child project inherits all the sources of its parent.
12051 However, inherited sources can be overridden: a unit in a parent is hidden
12052 by a unit of the same name in the child.
12054 Inherited sources are considered to be sources (but not immediate sources)
12055 of the child project; see @ref{Project File Syntax}.
12057 An inherited source file retains any switches specified in the parent project.
12059 For example if the project @code{Utilities} contains the specification and the
12060 body of an Ada package @code{Util_IO}, then the project
12061 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
12062 The original body of @code{Util_IO} will not be considered in program builds.
12063 However, the package specification will still be found in the project
12064 @code{Utilities}.
12066 A child project can have only one parent but it may import any number of other
12067 projects.
12069 A project is not allowed to import directly or indirectly at the same time a
12070 child project and any of its ancestors.
12072 @c *******************************
12073 @c * Project Hierarchy Extension *
12074 @c *******************************
12076 @node Project Hierarchy Extension
12077 @section Project Hierarchy Extension
12079 @noindent
12080 When extending a large system spanning multiple projects, it is often
12081 inconvenient to extend every project in the hierarchy that is impacted by a
12082 small change introduced. In such cases, it is possible to create a virtual
12083 extension of entire hierarchy using @code{extends all} relationship.
12085 When the project is extended using @code{extends all} inheritance, all projects
12086 that are imported by it, both directly and indirectly, are considered virtually
12087 extended. That is, the Project Manager creates "virtual projects"
12088 that extend every project in the hierarchy; all these virtual projects have
12089 no sources of their own and have as object directory the object directory of
12090 the root of "extending all" project.
12092 It is possible to explicitly extend one or more projects in the hierarchy
12093 in order to modify the sources. These extending projects must be imported by
12094 the "extending all" project, which will replace the corresponding virtual
12095 projects with the explicit ones.
12097 When building such a project hierarchy extension, the Project Manager will
12098 ensure that both modified sources and sources in virtual extending projects
12099 that depend on them, are recompiled.
12101 By means of example, consider the following hierarchy of projects.
12103 @enumerate
12104 @item
12105 project A, containing package P1
12106 @item
12107 project B importing A and containing package P2 which depends on P1
12108 @item
12109 project C importing B and containing package P3 which depends on P2
12110 @end enumerate
12112 @noindent
12113 We want to modify packages P1 and P3.
12115 This project hierarchy will need to be extended as follows:
12117 @enumerate
12118 @item
12119 Create project A1 that extends A, placing modified P1 there:
12121 @smallexample @c 0projectfile
12122 project A1 extends "(...)/A" is
12123 end A1;
12124 @end smallexample
12126 @item
12127 Create project C1 that "extends all" C and imports A1, placing modified
12128 P3 there:
12130 @smallexample @c 0projectfile
12131 with "(...)/A1";
12132 project C1 extends all "(...)/C" is
12133 end C1;
12134 @end smallexample
12135 @end enumerate
12137 When you build project C1, your entire modified project space will be
12138 recompiled, including the virtual project B1 that has been impacted by the
12139 "extending all" inheritance of project C.
12141 Note that if a Library Project in the hierarchy is virtually extended,
12142 the virtual project that extends the Library Project is not a Library Project.
12144 @c ****************************************
12145 @c * External References in Project Files *
12146 @c ****************************************
12148 @node  External References in Project Files
12149 @section External References in Project Files
12151 @noindent
12152 A project file may contain references to external variables; such references
12153 are called @emph{external references}.
12155 An external variable is either defined as part of the environment (an
12156 environment variable in Unix, for example) or else specified on the command
12157 line via the @option{^-X^/EXTERNAL_REFERENCE=^@emph{vbl}=@emph{value}} switch.
12158 If both, then the command line value is used.
12160 The value of an external reference is obtained by means of the built-in
12161 function @code{external}, which returns a string value.
12162 This function has two forms:
12163 @itemize @bullet
12164 @item @code{external (external_variable_name)}
12165 @item @code{external (external_variable_name, default_value)}
12166 @end itemize
12168 @noindent
12169 Each parameter must be a string literal.  For example:
12171 @smallexample @c projectfile
12172    external ("USER")
12173    external ("OS", "GNU/Linux")
12174 @end smallexample
12176 @noindent
12177 In the form with one parameter, the function returns the value of
12178 the external variable given as parameter. If this name is not present in the
12179 environment, the function returns an empty string.
12181 In the form with two string parameters, the second argument is
12182 the value returned when the variable given as the first argument is not
12183 present in the environment. In the example above, if @code{"OS"} is not
12184 the name of ^an environment variable^a logical name^ and is not passed on
12185 the command line, then the returned value is @code{"GNU/Linux"}.
12187 An external reference may be part of a string expression or of a string
12188 list expression, and can therefore appear in a variable declaration or
12189 an attribute declaration.
12191 @smallexample @c projectfile
12192 @group
12193    type Mode_Type is ("Debug", "Release");
12194    Mode : Mode_Type := external ("MODE");
12195    case Mode is
12196      when "Debug" =>
12197         ...
12198 @end group
12199 @end smallexample
12201 @c *****************************
12202 @c * Packages in Project Files *
12203 @c *****************************
12205 @node  Packages in Project Files
12206 @section Packages in Project Files
12208 @noindent
12209 A @emph{package} defines the settings for project-aware tools within a
12210 project.
12211 For each such tool one can declare a package; the names for these
12212 packages are preset (@pxref{Packages}).
12213 A package may contain variable declarations, attribute declarations, and case
12214 constructions.
12216 @smallexample @c projectfile
12217 @group
12218    project Proj is
12219       package Builder is  -- used by gnatmake
12220          for ^Default_Switches^Default_Switches^ ("Ada")
12221              use ("^-v^-v^",
12222                   "^-g^-g^");
12223       end Builder;
12224    end Proj;
12225 @end group
12226 @end smallexample
12228 @noindent
12229 The syntax of package declarations mimics that of package in Ada.
12231 Most of the packages have an attribute
12232 @code{^Default_Switches^Default_Switches^}.
12233 This attribute is an associative array, and its value is a string list.
12234 The index of the associative array is the name of a programming language (case
12235 insensitive). This attribute indicates the ^switch^switch^
12236 or ^switches^switches^ to be used
12237 with the corresponding tool.
12239 Some packages also have another attribute, @code{^Switches^Switches^},
12240 an associative array whose value is a string list.
12241 The index is the name of a source file.
12242 This attribute indicates the ^switch^switch^
12243 or ^switches^switches^ to be used by the corresponding
12244 tool when dealing with this specific file.
12246 Further information on these ^switch^switch^-related attributes is found in
12247 @ref{^Switches^Switches^ and Project Files}.
12249 A package may be declared as a @emph{renaming} of another package; e.g., from
12250 the project file for an imported project.
12252 @smallexample @c projectfile
12253 @group
12254   with "/global/apex.gpr";
12255   project Example is
12256     package Naming renames Apex.Naming;
12257     ...
12258   end Example;
12259 @end group
12260 @end smallexample
12262 @noindent
12263 Packages that are renamed in other project files often come from project files
12264 that have no sources: they are just used as templates. Any modification in the
12265 template will be reflected automatically in all the project files that rename
12266 a package from the template.
12268 In addition to the tool-oriented packages, you can also declare a package
12269 named @code{Naming} to establish specialized source file naming conventions
12270 (@pxref{Naming Schemes}).
12272 @c ************************************
12273 @c * Variables from Imported Projects *
12274 @c ************************************
12276 @node Variables from Imported Projects
12277 @section Variables from Imported Projects
12279 @noindent
12280 An attribute or variable defined in an imported or parent project can
12281 be used in expressions in the importing / extending project.
12282 Such an attribute or variable is denoted by an expanded name whose prefix
12283 is either the name of the project or the expanded name of a package within
12284 a project.
12286 @smallexample @c projectfile
12287 @group
12288   with "imported";
12289   project Main extends "base" is
12290      Var1 := Imported.Var;
12291      Var2 := Base.Var & ".new";
12292 @end group
12294 @group
12295      package Builder is
12296         for ^Default_Switches^Default_Switches^ ("Ada")
12297             use Imported.Builder.Ada_^Switches^Switches^ &
12298                 "^-gnatg^-gnatg^" &
12299                 "^-v^-v^";
12300      end Builder;
12301 @end group
12303 @group
12304      package Compiler is
12305         for ^Default_Switches^Default_Switches^ ("Ada")
12306             use Base.Compiler.Ada_^Switches^Switches^;
12307      end Compiler;
12308   end Main;
12309 @end group
12310 @end smallexample
12312 @noindent
12313 In this example:
12315 @itemize @bullet
12316 @item
12317 The value of @code{Var1} is a copy of the variable @code{Var} defined
12318 in the project file @file{"imported.gpr"}
12319 @item
12320 the value of @code{Var2} is a copy of the value of variable @code{Var}
12321 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
12322 @item
12323 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12324 @code{Builder} is a string list that includes in its value a copy of the value
12325 of @code{Ada_^Switches^Switches^} defined in the @code{Builder} package
12326 in project file @file{imported.gpr} plus two new elements:
12327 @option{"^-gnatg^-gnatg^"}
12328 and @option{"^-v^-v^"};
12329 @item
12330 attribute @code{^Default_Switches^Default_Switches^ ("Ada")} in package
12331 @code{Compiler} is a copy of the variable @code{Ada_^Switches^Switches^}
12332 defined in the @code{Compiler} package in project file @file{base.gpr},
12333 the project being extended.
12334 @end itemize
12336 @c ******************
12337 @c * Naming Schemes *
12338 @c ******************
12340 @node  Naming Schemes
12341 @section Naming Schemes
12343 @noindent
12344 Sometimes an Ada software system is ported from a foreign compilation
12345 environment to GNAT, and the file names do not use the default GNAT
12346 conventions. Instead of changing all the file names (which for a variety
12347 of reasons might not be possible), you can define the relevant file
12348 naming scheme in the @code{Naming} package in your project file.
12350 @noindent
12351 Note that the use of pragmas described in
12352 @ref{Alternative File Naming Schemes} by mean of a configuration
12353 pragmas file is not supported when using project files. You must use
12354 the features described in this paragraph. You can however use specify
12355 other configuration pragmas (@pxref{Specifying Configuration Pragmas}).
12357 @ifclear vms
12358 For example, the following
12359 package models the Apex file naming rules:
12361 @smallexample @c projectfile
12362 @group
12363   package Naming is
12364     for Casing               use "lowercase";
12365     for Dot_Replacement      use ".";
12366     for Spec_Suffix ("Ada")  use ".1.ada";
12367     for Body_Suffix ("Ada")  use ".2.ada";
12368   end Naming;
12369 @end group
12370 @end smallexample
12371 @end ifclear
12373 @ifset vms
12374 For example, the following package models the DEC Ada file naming rules:
12376 @smallexample @c projectfile
12377 @group
12378   package Naming is
12379     for Casing               use "lowercase";
12380     for Dot_Replacement      use "__";
12381     for Spec_Suffix ("Ada")  use "_.^ada^ada^";
12382     for Body_Suffix ("Ada")  use ".^ada^ada^";
12383   end Naming;
12384 @end group
12385 @end smallexample
12387 @noindent
12388 (Note that @code{Casing} is @code{"lowercase"} because GNAT gets the file
12389 names in lower case)
12390 @end ifset
12392 @noindent
12393 You can define the following attributes in package @code{Naming}:
12395 @table @code
12397 @item @var{Casing}
12398 This must be a string with one of the three values @code{"lowercase"},
12399 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
12401 @noindent
12402 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
12404 @item @var{Dot_Replacement}
12405 This must be a string whose value satisfies the following conditions:
12407 @itemize @bullet
12408 @item It must not be empty
12409 @item It cannot start or end with an alphanumeric character
12410 @item It cannot be a single underscore
12411 @item It cannot start with an underscore followed by an alphanumeric
12412 @item It cannot contain a dot @code{'.'} except if the entire string
12413 is @code{"."}
12414 @end itemize
12416 @noindent
12417 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
12419 @item @var{Spec_Suffix}
12420 This is an associative array (indexed by the programming language name, case
12421 insensitive) whose value is a string that must satisfy the following
12422 conditions:
12424 @itemize @bullet
12425 @item It must not be empty
12426 @item It must include at least one dot
12427 @end itemize
12428 @noindent
12429 If @code{Spec_Suffix ("Ada")} is not specified, then the default is
12430 @code{"^.ads^.ADS^"}.
12432 @item @var{Body_Suffix}
12433 This is an associative array (indexed by the programming language name, case
12434 insensitive) whose value is a string that must satisfy the following
12435 conditions:
12437 @itemize @bullet
12438 @item It must not be empty
12439 @item It must include at least one dot
12440 @item It cannot end with the same string as @code{Spec_Suffix ("Ada")}
12441 @end itemize
12442 @noindent
12443 If @code{Body_Suffix ("Ada")} is not specified, then the default is
12444 @code{"^.adb^.ADB^"}.
12446 @item @var{Separate_Suffix}
12447 This must be a string whose value satisfies the same conditions as
12448 @code{Body_Suffix}.
12450 @noindent
12451 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
12452 value as @code{Body_Suffix ("Ada")}.
12454 @item @var{Spec}
12455 @noindent
12456 You can use the associative array attribute @code{Spec}  to define
12457 the source file name for an individual Ada compilation unit's spec. The array
12458 index must be a string literal that identifies the Ada unit (case insensitive).
12459 The value of this attribute must be a string that identifies the file that
12460 contains this unit's spec (case sensitive or insensitive depending on the
12461 operating system).
12463 @smallexample @c projectfile
12464    for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
12465 @end smallexample
12467 @item @var{Body}
12469 You can use the associative array attribute @code{Body} to
12470 define the source file name for an individual Ada compilation unit's body
12471 (possibly a subunit).  The array index must be a string literal that identifies
12472 the Ada unit (case insensitive).  The value of this attribute must be a string
12473 that identifies the file that contains this unit's body or subunit (case
12474 sensitive or insensitive depending on the operating system).
12476 @smallexample @c projectfile
12477    for Body ("MyPack.MyChild") use "mypack.mychild.body";
12478 @end smallexample
12479 @end table
12481 @c ********************
12482 @c * Library Projects *
12483 @c ********************
12485 @node Library Projects
12486 @section Library Projects
12488 @noindent
12489 @emph{Library projects} are projects whose object code is placed in a library.
12490 (Note that this facility is not yet supported on all platforms)
12492 To create a library project, you need to define in its project file
12493 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
12494 Additionally, you may define the library-related attributes
12495 @code{Library_Kind}, @code{Library_Version}, @code{Library_Interface},
12496 @code{Library_Auto_Init}, @code{Library_Options} and @code{Library_GCC}.
12498 The @code{Library_Name} attribute has a string value. There is no restriction
12499 on the name of a library. It is the responsability of the developer to
12500 choose a name that will be accepted by the platform. It is recommanded to
12501 choose names that could be Ada identifiers; such names are almost guaranteed
12502 to be acceptable on all platforms.
12504 The @code{Library_Dir} attribute has a string value that designates the path
12505 (absolute or relative) of the directory where the library will reside.
12506 It must designate an existing directory, and this directory must be
12507 different from the project's object directory. It also needs to be writable.
12508 The directory should only be used for one library; the reason is that all
12509 files contained in this directory may be deleted by the Project Manager.
12511 If both @code{Library_Name} and @code{Library_Dir} are specified and
12512 are legal, then the project file defines a library project.  The optional
12513 library-related attributes are checked only for such project files.
12515 The @code{Library_Kind} attribute has a string value that must be one of the
12516 following (case insensitive): @code{"static"}, @code{"dynamic"} or
12517 @code{"relocatable"} (which is a synonym for @code{"dynamic"}). If this
12518 attribute is not specified, the library is a static library, that is
12519 an archive of object files that can be potentially linked into an
12520 static executable. Otherwise, the library may be dynamic or
12521 relocatable, that is a library that is loaded only at the start of execution.
12523 If you need to build both a static and a dynamic library, you should use two
12524 different object directories, since in some cases some extra code needs to
12525 be generated for the latter. For such cases, it is recommended to either use
12526 two different project files, or a single one which uses external variables
12527 to indicate what kind of library should be build.
12529 The @code{Library_Version} attribute has a string value whose interpretation
12530 is platform dependent. It has no effect on VMS and Windows. On Unix, it is
12531 used only for dynamic/relocatable libraries as the internal name of the
12532 library (the @code{"soname"}). If the library file name (built from the
12533 @code{Library_Name}) is different from the @code{Library_Version}, then the
12534 library file will be a symbolic link to the actual file whose name will be
12535 @code{Library_Version}.
12537 Example (on Unix):
12539 @smallexample @c projectfile
12540 @group
12541 project Plib is
12543    Version := "1";
12545    for Library_Dir use "lib_dir";
12546    for Library_Name use "dummy";
12547    for Library_Kind use "relocatable";
12548    for Library_Version use "libdummy.so." & Version;
12550 end Plib;
12551 @end group
12552 @end smallexample
12554 @noindent
12555 Directory @file{lib_dir} will contain the internal library file whose name
12556 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
12557 @file{libdummy.so.1}.
12559 When @command{gnatmake} detects that a project file
12560 is a library project file, it will check all immediate sources of the project
12561 and rebuild the library if any of the sources have been recompiled.
12563 Standard project files can import library project files. In such cases,
12564 the libraries will only be rebuild if some of its sources are recompiled
12565 because they are in the closure of some other source in an importing project.
12566 Sources of the library project files that are not in such a closure will
12567 not be checked, unless the full library is checked, because one of its sources
12568 needs to be recompiled.
12570 For instance, assume the project file @code{A} imports the library project file
12571 @code{L}. The immediate sources of A are @file{a1.adb}, @file{a2.ads} and
12572 @file{a2.adb}. The immediate sources of L are @file{l1.ads}, @file{l1.adb},
12573 @file{l2.ads}, @file{l2.adb}.
12575 If @file{l1.adb} has been modified, then the library associated with @code{L}
12576 will be rebuild when compiling all the immediate sources of @code{A} only
12577 if @file{a1.ads}, @file{a2.ads} or @file{a2.adb} includes a statement
12578 @code{"with L1;"}.
12580 To be sure that all the sources in the library associated with @code{L} are
12581 up to date, and that all the sources of parject @code{A} are also up to date,
12582 the following two commands needs to be used:
12584 @smallexample
12585 gnatmake -Pl.gpr
12586 gnatmake -Pa.gpr
12587 @end smallexample
12589 When a library is built or rebuilt, an attempt is made first to delete all
12590 files in the library directory.
12591 All @file{ALI} files will also be copied from the object directory to the
12592 library directory. To build executables, @command{gnatmake} will use the
12593 library rather than the individual object files.
12595 @c **********************************************
12596 @c * Using Third-Party Libraries through Projects
12597 @c **********************************************
12598 @node Using Third-Party Libraries through Projects
12599 @section Using Third-Party Libraries through Projects
12601 Whether you are exporting your own library to make it available to
12602 clients, or you are using a library provided by a third party, it is
12603 convenient to have project files that automatically set the correct
12604 command line switches for the compiler and linker.
12606 Such project files are very similar to the library project files;
12607 @xref{Library Projects}. The only difference is that you set the
12608 @code{Source_Dirs} and @code{Object_Dir} attribute so that they point to the
12609 directories where, respectively, the sources and the read-only ALI files have
12610 been installed.
12612 If you need to interface with a set of libraries, as opposed to a
12613 single one, you need to create one library project for each of the
12614 libraries. In addition, a top-level project that imports all these
12615 library projects should be provided, so that the user of your library
12616 has a single @code{with} clause to add to his own projects.
12618 For instance, let's assume you are providing two static libraries
12619 @file{liba.a} and @file{libb.a}. The user needs to link with
12620 both of these libraries. Each of these is associated with its
12621 own set of header files. Let's assume furthermore that all the
12622 header files for the two libraries have been installed in the same
12623 directory @file{headers}. The @file{ALI} files are found in the same
12624 @file{headers} directory.
12626 In this case, you should provide the following three projects:
12628 @smallexample @c projectfile
12629 @group
12630 with "liba", "libb";
12631 project My_Library is
12632   for Source_Dirs use ("headers");
12633   for Object_Dir  use "headers";
12634 end My_Library;
12635 @end group
12637 @group
12638 project Liba is
12639    for Source_Dirs use ();
12640    for Library_Dir use "lib";
12641    for Library_Name use "a";
12642    for Library_Kind use "static";
12643 end Liba;
12644 @end group
12646 @group
12647 project Libb is
12648    for Source_Dirs use ();
12649    for Library_Dir use "lib";
12650    for Library_Name use "b";
12651    for Library_Kind use "static";
12652 end Libb;
12653 @end group
12654 @end smallexample
12656 @c *******************************
12657 @c * Stand-alone Library Projects *
12658 @c *******************************
12660 @node Stand-alone Library Projects
12661 @section Stand-alone Library Projects
12663 @noindent
12664 A Stand-alone Library is a library that contains the necessary code to
12665 elaborate the Ada units that are included in the library. A Stand-alone
12666 Library is suitable to be used in an executable when the main is not
12667 in Ada. However, Stand-alone Libraries may also be used with an Ada main
12668 subprogram.
12670 A Stand-alone Library Project is a Library Project where the library is
12671 a Stand-alone Library.
12673 To be a Stand-alone Library Project, in addition to the two attributes
12674 that make a project a Library Project (@code{Library_Name} and
12675 @code{Library_Dir}, see @ref{Library Projects}), the attribute
12676 @code{Library_Interface} must be defined.
12678 @smallexample @c projectfile
12679 @group
12680    for Library_Dir use "lib_dir";
12681    for Library_Name use "dummy";
12682    for Library_Interface use ("int1", "int1.child");
12683 @end group
12684 @end smallexample
12686 Attribute @code{Library_Interface} has a non empty string list value,
12687 each string in the list designating a unit contained in an immediate source
12688 of the project file.
12690 When a Stand-alone Library is built, first the binder is invoked to build
12691 a package whose name depends on the library name
12692 (^b~dummy.ads/b^B$DUMMY.ADS/B^ in the example above).
12693 This binder-generated package includes initialization and
12694 finalization procedures whose
12695 names depend on the library name (dummyinit and dummyfinal in the example
12696 above). The object corresponding to this package is included in the library.
12698 A dynamic or relocatable Stand-alone Library is automatically initialized
12699 if automatic initialization of Stand-alone Libraries is supported on the
12700 platform and if attribute @code{Library_Auto_Init} is not specified or
12701 is specified with the value "true". A static Stand-alone Library is never
12702 automatically initialized.
12704 Single string attribute @code{Library_Auto_Init} may be specified with only
12705 two possible values: "false" or "true" (case-insensitive). Specifying
12706 "false" for attribute @code{Library_Auto_Init} will prevent automatic
12707 initialization of dynamic or relocatable libraries.
12709 When a non automatically initialized Stand-alone Library is used
12710 in an executable, its initialization procedure must be called before
12711 any service of the library is used.
12712 When the main subprogram is in Ada, it may mean that the initialization
12713 procedure has to be called during elaboration of another package.
12715 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
12716 (those that are listed in attribute @code{Library_Interface}) are copied to
12717 the Library Directory. As a consequence, only the Interface Units may be
12718 imported from Ada units outside of the library. If other units are imported,
12719 the binding phase will fail.
12721 When a Stand-Alone Library is bound, the switches that are specified in
12722 the attribute @code{Default_Switches ("Ada")} in package @code{Binder} are
12723 used in the call to @command{gnatbind}.
12725 The string list attribute @code{Library_Options} may be used to specified
12726 additional switches to the call to @command{gcc} to link the library.
12728 The attribute @code{Library_Src_Dir}, may be specified for a
12729 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
12730 single string value. Its value must be the path (absolute or relative to the
12731 project directory) of an existing directory. This directory cannot be the
12732 object directory or one of the source directories, but it can be the same as
12733 the library directory. The sources of the Interface
12734 Units of the library, necessary to an Ada client of the library, will be
12735 copied to the designated directory, called Interface Copy directory.
12736 These sources includes the specs of the Interface Units, but they may also
12737 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
12738 are used, or when there is a generic units in the spec. Before the sources
12739 are copied to the Interface Copy directory, an attempt is made to delete all
12740 files in the Interface Copy directory.
12742 @c *************************************
12743 @c * Switches Related to Project Files *
12744 @c *************************************
12745 @node Switches Related to Project Files
12746 @section Switches Related to Project Files
12748 @noindent
12749 The following switches are used by GNAT tools that support project files:
12751 @table @option
12753 @item ^-P^/PROJECT_FILE=^@var{project}
12754 @cindex @option{^-P^/PROJECT_FILE^} (any tool supporting project files)
12755 Indicates the name of a project file. This project file will be parsed with
12756 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12757 if any, and using the external references indicated
12758 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12759 @ifclear vms
12760 There may zero, one or more spaces between @option{-P} and @var{project}.
12761 @end ifclear
12763 @noindent
12764 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12766 @noindent
12767 Since the Project Manager parses the project file only after all the switches
12768 on the command line are checked, the order of the switches
12769 @option{^-P^/PROJECT_FILE^},
12770 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12771 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12773 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12774 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any tool supporting project files)
12775 Indicates that external variable @var{name} has the value @var{value}.
12776 The Project Manager will use this value for occurrences of
12777 @code{external(name)} when parsing the project file.
12779 @ifclear vms
12780 @noindent
12781 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12782 put between quotes.
12783 @smallexample
12784   -XOS=NT
12785   -X"user=John Doe"
12786 @end smallexample
12787 @end ifclear
12789 @noindent
12790 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12791 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12792 @var{name}, only the last one is used.
12794 @noindent
12795 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12796 takes precedence over the value of the same name in the environment.
12798 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12799 @cindex @code{^-vP^/MESSAGES_PROJECT_FILE^} (any tool supporting project files)
12800 @c Previous line uses code vs option command, to stay less than 80 chars
12801 Indicates the verbosity of the parsing of GNAT project files.
12803 @ifclear vms
12804 @option{-vP0} means Default;
12805 @option{-vP1} means Medium;
12806 @option{-vP2} means High.
12807 @end ifclear
12809 @ifset vms
12810 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12811 HIGH.
12812 @end ifset
12814 @noindent
12815 The default is ^Default^DEFAULT^: no output for syntactically correct
12816 project files.
12817 @noindent
12818 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12819 only the last one is used.
12821 @end table
12823 @c **********************************
12824 @c * Tools Supporting Project Files *
12825 @c **********************************
12827 @node  Tools Supporting Project Files
12828 @section Tools Supporting Project Files
12830 @menu
12831 * gnatmake and Project Files::
12832 * The GNAT Driver and Project Files::
12833 @ifclear vms
12834 * Glide and Project Files::
12835 @end ifclear
12836 @end menu
12838 @node gnatmake and Project Files
12839 @subsection gnatmake and Project Files
12841 @noindent
12842 This section covers several topics related to @command{gnatmake} and
12843 project files: defining ^switches^switches^ for @command{gnatmake}
12844 and for the tools that it invokes; specifying configuration pragmas;
12845 the use of the @code{Main} attribute; building and rebuilding library project
12846 files.
12848 @menu
12849 * ^Switches^Switches^ and Project Files::
12850 * Specifying Configuration Pragmas::
12851 * Project Files and Main Subprograms::
12852 * Library Project Files::
12853 @end menu
12855 @node ^Switches^Switches^ and Project Files
12856 @subsubsection ^Switches^Switches^ and Project Files
12858 @ifset vms
12859 It is not currently possible to specify VMS style qualifiers in the project
12860 files; only Unix style ^switches^switches^ may be specified.
12861 @end ifset
12863 @noindent
12864 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12865 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12866 attribute, a @code{^Switches^Switches^} attribute, or both;
12867 as their names imply, these ^switch^switch^-related
12868 attributes affect the ^switches^switches^ that are used for each of these GNAT
12869 components when
12870 @command{gnatmake} is invoked.  As will be explained below, these
12871 component-specific ^switches^switches^ precede
12872 the ^switches^switches^ provided on the @command{gnatmake} command line.
12874 The @code{^Default_Switches^Default_Switches^} attribute is an associative
12875 array indexed by language name (case insensitive) whose value is a string list.
12876 For example:
12878 @smallexample @c projectfile
12879 @group
12880 package Compiler is
12881   for ^Default_Switches^Default_Switches^ ("Ada")
12882       use ("^-gnaty^-gnaty^",
12883            "^-v^-v^");
12884 end Compiler;
12885 @end group
12886 @end smallexample
12888 @noindent
12889 The @code{^Switches^Switches^} attribute is also an associative array,
12890 indexed by a file name (which may or may not be case sensitive, depending
12891 on the operating system) whose value is a string list.  For example:
12893 @smallexample @c projectfile
12894 @group
12895 package Builder is
12896    for ^Switches^Switches^ ("main1.adb")
12897        use ("^-O2^-O2^");
12898    for ^Switches^Switches^ ("main2.adb")
12899        use ("^-g^-g^");
12900 end Builder;
12901 @end group
12902 @end smallexample
12904 @noindent
12905 For the @code{Builder} package, the file names must designate source files
12906 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12907 file names must designate @file{ALI} or source files for main subprograms.
12908 In each case just the file name without an explicit extension is acceptable.
12910 For each tool used in a program build (@command{gnatmake}, the compiler, the
12911 binder, and the linker), the corresponding package @dfn{contributes} a set of
12912 ^switches^switches^ for each file on which the tool is invoked, based on the
12913 ^switch^switch^-related attributes defined in the package.
12914 In particular, the ^switches^switches^
12915 that each of these packages contributes for a given file @var{f} comprise:
12917 @itemize @bullet
12918 @item
12919 the value of attribute @code{^Switches^Switches^ (@var{f})},
12920 if it is specified in the package for the given file,
12921 @item
12922 otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12923 if it is specified in the package.
12924 @end itemize
12926 @noindent
12927 If neither of these attributes is defined in the package, then the package does
12928 not contribute any ^switches^switches^ for the given file.
12930 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12931 two sets, in the following order: those contributed for the file
12932 by the @code{Builder} package;
12933 and the switches passed on the command line.
12935 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12936 the ^switches^switches^ passed to the tool comprise three sets,
12937 in the following order:
12939 @enumerate
12940 @item
12941 the applicable ^switches^switches^ contributed for the file
12942 by the @code{Builder} package in the project file supplied on the command line;
12944 @item
12945 those contributed for the file by the package (in the relevant project file --
12946 see below) corresponding to the tool; and
12948 @item
12949 the applicable switches passed on the command line.
12950 @end enumerate
12952 @noindent
12953 The term @emph{applicable ^switches^switches^} reflects the fact that
12954 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12955 tools, depending on the individual ^switch^switch^.
12957 @command{gnatmake} may invoke the compiler on source files from different
12958 projects. The Project Manager will use the appropriate project file to
12959 determine the @code{Compiler} package for each source file being compiled.
12960 Likewise for the @code{Binder} and @code{Linker} packages.
12962 As an example, consider the following package in a project file:
12964 @smallexample @c projectfile
12965 @group
12966 project Proj1 is
12967    package Compiler is
12968       for ^Default_Switches^Default_Switches^ ("Ada")
12969           use ("^-g^-g^");
12970       for ^Switches^Switches^ ("a.adb")
12971           use ("^-O1^-O1^");
12972       for ^Switches^Switches^ ("b.adb")
12973           use ("^-O2^-O2^",
12974                "^-gnaty^-gnaty^");
12975    end Compiler;
12976 end Proj1;
12977 @end group
12978 @end smallexample
12980 @noindent
12981 If @command{gnatmake} is invoked with this project file, and it needs to
12982 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12983 @file{a.adb} will be compiled with the ^switch^switch^
12984 @option{^-O1^-O1^},
12985 @file{b.adb} with ^switches^switches^
12986 @option{^-O2^-O2^}
12987 and @option{^-gnaty^-gnaty^},
12988 and @file{c.adb} with @option{^-g^-g^}.
12990 The following example illustrates the ordering of the ^switches^switches^
12991 contributed by different packages:
12993 @smallexample @c projectfile
12994 @group
12995 project Proj2 is
12996    package Builder is
12997       for ^Switches^Switches^ ("main.adb")
12998           use ("^-g^-g^",
12999                "^-O1^-)1^",
13000                "^-f^-f^");
13001    end Builder;
13002 @end group
13004 @group
13005    package Compiler is
13006       for ^Switches^Switches^ ("main.adb")
13007           use ("^-O2^-O2^");
13008    end Compiler;
13009 end Proj2;
13010 @end group
13011 @end smallexample
13013 @noindent
13014 If you issue the command:
13016 @smallexample
13017     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
13018 @end smallexample
13020 @noindent
13021 then the compiler will be invoked on @file{main.adb} with the following
13022 sequence of ^switches^switches^
13024 @smallexample
13025    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
13026 @end smallexample
13028 with the last @option{^-O^-O^}
13029 ^switch^switch^ having precedence over the earlier ones;
13030 several other ^switches^switches^
13031 (such as @option{^-c^-c^}) are added implicitly.
13033 The ^switches^switches^
13034 @option{^-g^-g^}
13035 and @option{^-O1^-O1^} are contributed by package
13036 @code{Builder},  @option{^-O2^-O2^} is contributed
13037 by the package @code{Compiler}
13038 and @option{^-O0^-O0^} comes from the command line.
13040 The @option{^-g^-g^}
13041 ^switch^switch^ will also be passed in the invocation of
13042 @command{Gnatlink.}
13044 A final example illustrates switch contributions from packages in different
13045 project files:
13047 @smallexample @c projectfile
13048 @group
13049 project Proj3 is
13050    for Source_Files use ("pack.ads", "pack.adb");
13051    package Compiler is
13052       for ^Default_Switches^Default_Switches^ ("Ada")
13053           use ("^-gnata^-gnata^");
13054    end Compiler;
13055 end Proj3;
13056 @end group
13058 @group
13059 with "Proj3";
13060 project Proj4 is
13061    for Source_Files use ("foo_main.adb", "bar_main.adb");
13062    package Builder is
13063       for ^Switches^Switches^ ("foo_main.adb")
13064           use ("^-s^-s^",
13065                "^-g^-g^");
13066    end Builder;
13067 end Proj4;
13068 @end group
13070 @group
13071 -- Ada source file:
13072 with Pack;
13073 procedure Foo_Main is
13074    ...
13075 end Foo_Main;
13076 @end group
13077 @end smallexample
13079 If the command is
13080 @smallexample
13081 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
13082 @end smallexample
13084 @noindent
13085 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
13086 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
13087 @option{^-gnato^-gnato^} (passed on the command line).
13088 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
13089 are @option{^-g^-g^} from @code{Proj4.Builder},
13090 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
13091 and @option{^-gnato^-gnato^} from the command line.
13093 @noindent
13094 When using @command{gnatmake} with project files, some ^switches^switches^ or
13095 arguments may be expressed as relative paths. As the working directory where
13096 compilation occurs may change, these relative paths are converted to absolute
13097 paths. For the ^switches^switches^ found in a project file, the relative paths
13098 are relative to the project file directory, for the switches on the command
13099 line, they are relative to the directory where @command{gnatmake} is invoked.
13100 The ^switches^switches^ for which this occurs are:
13101 ^-I^-I^,
13102 ^-A^-A^,
13103 ^-L^-L^,
13104 ^-aO^-aO^,
13105 ^-aL^-aL^,
13106 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13107 ^switch^switch^
13108 ^-o^-o^, object files specified in package @code{Linker} or after
13109 -largs on the command line). The exception to this rule is the ^switch^switch^
13110 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13112 @node Specifying Configuration Pragmas
13113 @subsubsection Specifying Configuration Pragmas
13115 When using @command{gnatmake} with project files, if there exists a file
13116 @file{gnat.adc} that contains configuration pragmas, this file will be
13117 ignored.
13119 Configuration pragmas can be defined by means of the following attributes in
13120 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13121 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13123 Both these attributes are single string attributes. Their values is the path
13124 name of a file containing configuration pragmas. If a path name is relative,
13125 then it is relative to the project directory of the project file where the
13126 attribute is defined.
13128 When compiling a source, the configuration pragmas used are, in order,
13129 those listed in the file designated by attribute
13130 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13131 project file, if it is specified, and those listed in the file designated by
13132 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13133 the project file of the source, if it exists.
13135 @node Project Files and Main Subprograms
13136 @subsubsection Project Files and Main Subprograms
13138 @noindent
13139 When using a project file, you can invoke @command{gnatmake}
13140 with one or several main subprograms, by specifying their source files on the
13141 command line.
13143 @smallexample
13144     gnatmake ^-P^/PROJECT_FILE=^prj main1 main2 main3
13145 @end smallexample
13147 @noindent
13148 Each of these needs to be a source file of the same project, except
13149 when the switch ^-u^/UNIQUE^ is used.
13151 @noindent
13152 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13153 same project, one of the project in the tree rooted at the project specified
13154 on the command line. The package @code{Builder} of this common project, the
13155 "main project" is the one that is considered by @command{gnatmake}.
13157 @noindent
13158 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13159 imported directly or indirectly by the project specified on the command line.
13160 Note that if such a source file is not part of the project specified on the
13161 command line, the ^switches^switches^ found in package @code{Builder} of the
13162 project specified on the command line, if any, that are transmitted
13163 to the compiler will still be used, not those found in the project file of
13164 the source file.
13166 @noindent
13167 When using a project file, you can also invoke @command{gnatmake} without
13168 explicitly specifying any main, and the effect depends on whether you have
13169 defined the @code{Main} attribute.  This attribute has a string list value,
13170 where each element in the list is the name of a source file (the file
13171 extension is optional) that contains a unit that can be a main subprogram.
13173 If the @code{Main} attribute is defined in a project file as a non-empty
13174 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13175 line, then invoking @command{gnatmake} with this project file but without any
13176 main on the command line is equivalent to invoking @command{gnatmake} with all
13177 the file names in the @code{Main} attribute on the command line.
13179 Example:
13180 @smallexample @c projectfile
13181 @group
13182    project Prj is
13183       for Main use ("main1", "main2", "main3");
13184    end Prj;
13185 @end group
13186 @end smallexample
13188 @noindent
13189 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13190 is equivalent to
13191 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1 main2 main3"}.
13193 When the project attribute @code{Main} is not specified, or is specified
13194 as an empty string list, or when the switch @option{-u} is used on the command
13195 line, then invoking @command{gnatmake} with no main on the command line will
13196 result in all immediate sources of the project file being checked, and
13197 potentially recompiled. Depending on the presence of the switch @option{-u},
13198 sources from other project files on which the immediate sources of the main
13199 project file depend are also checked and potentially recompiled. In other
13200 words, the @option{-u} switch is applied to all of the immediate sources of the
13201 main project file.
13203 When no main is specified on the command line and attribute @code{Main} exists
13204 and includes several mains, or when several mains are specified on the
13205 command line, the default ^switches^switches^ in package @code{Builder} will
13206 be used for all mains, even if there are specific ^switches^switches^
13207 specified for one or several mains.
13209 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13210 the specific ^switches^switches^ for each main, if they are specified.
13212 @node Library Project Files
13213 @subsubsection Library Project Files
13215 @noindent
13216 When @command{gnatmake} is invoked with a main project file that is a library
13217 project file, it is not allowed to specify one or more mains on the command
13218 line.
13220 @noindent
13221 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13222 ^-l^/ACTION=LINK^ have special meanings.
13224 @itemize @bullet
13225 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13226 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13227 library.
13229 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13230 to @command{gnatmake} that the binder generated file should be compiled
13231 (in the case of a stand-alone library) and that the library should be built.
13233 @end itemize
13235 @node The GNAT Driver and Project Files
13236 @subsection The GNAT Driver and Project Files
13238 @noindent
13239 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13240 are project-aware:
13241 @command{^gnatbind^gnatbind^},
13242 @command{^gnatfind^gnatfind^},
13243 @command{^gnatlink^gnatlink^},
13244 @command{^gnatls^gnatls^},
13245 @command{^gnatelim^gnatelim^},
13246 @command{^gnatpp^gnatpp^},
13247 @command{^gnatmetric^gnatmetric^},
13248 @command{^gnatstub^gnatstub^},
13249 and @command{^gnatxref^gnatxref^}. However, none of these tools can be invoked
13250 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13251 They must be invoked through the @command{gnat} driver.
13253 The @command{gnat} driver is a front-end that accepts a number of commands and
13254 call the corresponding tool. It has been designed initially for VMS to convert
13255 VMS style qualifiers to Unix style switches, but it is now available to all
13256 the GNAT supported platforms.
13258 On non VMS platforms, the @command{gnat} driver accepts the following commands
13259 (case insensitive):
13261 @itemize @bullet
13262 @item
13263 BIND to invoke @command{^gnatbind^gnatbind^}
13264 @item
13265 CHOP to invoke @command{^gnatchop^gnatchop^}
13266 @item
13267 CLEAN to invoke @command{^gnatclean^gnatclean^}
13268 @item
13269 COMP or COMPILE to invoke the compiler
13270 @item
13271 ELIM to invoke @command{^gnatelim^gnatelim^}
13272 @item
13273 FIND to invoke @command{^gnatfind^gnatfind^}
13274 @item
13275 KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13276 @item
13277 LINK to invoke @command{^gnatlink^gnatlink^}
13278 @item
13279 LS or LIST to invoke @command{^gnatls^gnatls^}
13280 @item
13281 MAKE to invoke @command{^gnatmake^gnatmake^}
13282 @item
13283 NAME to invoke @command{^gnatname^gnatname^}
13284 @item
13285 PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13286 @item
13287 PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13288 @item
13289 METRIC to invoke @command{^gnatmetric^gnatmetric^}
13290 @item
13291 STUB to invoke @command{^gnatstub^gnatstub^}
13292 @item
13293 XREF to invoke @command{^gnatxref^gnatxref^}
13294 @end itemize
13296 @noindent
13297 (note that the compiler is invoked using the command
13298 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13300 @noindent
13301 On non VMS platforms, between @command{gnat} and the command, two
13302 special switches may be used:
13304 @itemize @bullet
13305 @item
13306 @command{-v} to display the invocation of the tool.
13307 @item
13308 @command{-dn} to prevent the @command{gnat} driver from removing
13309 the temporary files it has created. These temporary files are
13310 configuration files and temporary file list files.
13311 @end itemize
13313 @noindent
13314 The command may be followed by switches and arguments for the invoked
13315 tool.
13317 @smallexample
13318   gnat bind -C main.ali
13319   gnat ls -a main
13320   gnat chop foo.txt
13321 @end smallexample
13323 @noindent
13324 Switches may also be put in text files, one switch per line, and the text
13325 files may be specified with their path name preceded by '@@'.
13327 @smallexample
13328    gnat bind @@args.txt main.ali
13329 @end smallexample
13331 @noindent
13332 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
13333 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
13334 (@option{^-P^/PROJECT_FILE^},
13335 @option{^-X^/EXTERNAL_REFERENCE^} and
13336 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13337 the switches of the invoking tool.
13339 @noindent
13340 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13341 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13342 the immediate sources of the specified project file.
13344 @noindent
13345 When GNAT METRIC is used with a project file, but with no source
13346 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13347 with all the immediate sources of the specified project file and with
13348 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13349 of the project.
13351 @noindent
13352 For each of the following commands, there is optionally a corresponding
13353 package in the main project.
13355 @itemize @bullet
13356 @item
13357 package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13359 @item
13360 package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13362 @item
13363 package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13365 @item
13366 package @code{Eliminate} for command ELIM (invoking
13367 @code{^gnatelim^gnatelim^})
13369 @item
13370 package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13372 @item
13373 package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13375 @item
13376 package @code{Metrics} for command METRIC
13377 (invoking @code{^gnatmetric^gnatmetric^})
13379 @item
13380 package @code{Pretty_Printer} for command PP or PRETTY
13381 (invoking @code{^gnatpp^gnatpp^})
13383 @item
13384 package @code{Gnatstub} for command STUB
13385 (invoking @code{^gnatstub^gnatstub^})
13387 @item
13388 package @code{Cross_Reference} for command XREF (invoking
13389 @code{^gnatxref^gnatxref^})
13391 @end itemize
13393 @noindent
13394 Package @code{Gnatls} has a unique attribute @code{^Switches^Switches^},
13395 a simple variable with a string list value. It contains ^switches^switches^
13396 for the invocation of @code{^gnatls^gnatls^}.
13398 @smallexample @c projectfile
13399 @group
13400 project Proj1 is
13401    package gnatls is
13402       for ^Switches^Switches^
13403           use ("^-a^-a^",
13404                "^-v^-v^");
13405    end gnatls;
13406 end Proj1;
13407 @end group
13408 @end smallexample
13410 @noindent
13411 All other packages have two attribute @code{^Switches^Switches^} and
13412 @code{^Default_Switches^Default_Switches^}.
13414 @noindent
13415 @code{^Switches^Switches^} is an associated array attribute, indexed by the
13416 source file name, that has a string list value: the ^switches^switches^ to be
13417 used when the tool corresponding to the package is invoked for the specific
13418 source file.
13420 @noindent
13421 @code{^Default_Switches^Default_Switches^} is an associative array attribute,
13422 indexed by  the programming language that has a string list value.
13423 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13424 ^switches^switches^ for the invocation of the tool corresponding
13425 to the package, except if a specific @code{^Switches^Switches^} attribute
13426 is specified for the source file.
13428 @smallexample @c projectfile
13429 @group
13430 project Proj is
13432    for Source_Dirs use ("./**");
13434    package gnatls is
13435       for ^Switches^Switches^ use
13436           ("^-a^-a^",
13437            "^-v^-v^");
13438    end gnatls;
13439 @end group
13440 @group
13442    package Compiler is
13443       for ^Default_Switches^Default_Switches^ ("Ada")
13444           use ("^-gnatv^-gnatv^",
13445                "^-gnatwa^-gnatwa^");
13446    end Binder;
13447 @end group
13448 @group
13450    package Binder is
13451       for ^Default_Switches^Default_Switches^ ("Ada")
13452           use ("^-C^-C^",
13453                "^-e^-e^");
13454    end Binder;
13455 @end group
13456 @group
13458    package Linker is
13459       for ^Default_Switches^Default_Switches^ ("Ada")
13460           use ("^-C^-C^");
13461       for ^Switches^Switches^ ("main.adb")
13462           use ("^-C^-C^",
13463                "^-v^-v^",
13464                "^-v^-v^");
13465    end Linker;
13466 @end group
13467 @group
13469    package Finder is
13470       for ^Default_Switches^Default_Switches^ ("Ada")
13471            use ("^-a^-a^",
13472                 "^-f^-f^");
13473    end Finder;
13474 @end group
13475 @group
13477    package Cross_Reference is
13478       for ^Default_Switches^Default_Switches^ ("Ada")
13479           use ("^-a^-a^",
13480                "^-f^-f^",
13481                "^-d^-d^",
13482                "^-u^-u^");
13483    end Cross_Reference;
13484 end Proj;
13485 @end group
13486 @end smallexample
13488 @noindent
13489 With the above project file, commands such as
13491 @smallexample
13492    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13493    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13494    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13495    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13496    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13497 @end smallexample
13499 @noindent
13500 will set up the environment properly and invoke the tool with the switches
13501 found in the package corresponding to the tool:
13502 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13503 except @code{^Switches^Switches^ ("main.adb")}
13504 for @code{^gnatlink^gnatlink^}.
13506 @ifclear vms
13507 @node Glide and Project Files
13508 @subsection Glide and Project Files
13510 @noindent
13511 Glide will automatically recognize the @file{.gpr} extension for
13512 project files, and will
13513 convert them to its own internal format automatically. However, it
13514 doesn't provide a syntax-oriented editor for modifying these
13515 files.
13516 The project file will be loaded as text when you select the menu item
13517 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
13518 You can edit this text and save the @file{gpr} file;
13519 when you next select this project file in Glide it
13520 will be automatically reloaded.
13521 @end ifclear
13523 @c **********************
13524 @node An Extended Example
13525 @section An Extended Example
13527 @noindent
13528 Suppose that we have two programs, @var{prog1} and @var{prog2},
13529 whose sources are in corresponding directories. We would like
13530 to build them with a single @command{gnatmake} command, and we want to place
13531 their object files into @file{build} subdirectories of the source directories.
13532 Furthermore, we want to have to have two separate subdirectories
13533 in @file{build}  -- @file{release} and @file{debug} -- which will contain
13534 the object files compiled with different set of compilation flags.
13536 In other words, we have the following structure:
13538 @smallexample
13539 @group
13540    main
13541      |- prog1
13542      |    |- build
13543      |         | debug
13544      |         | release
13545      |- prog2
13546           |- build
13547                | debug
13548                | release
13549 @end group
13550 @end smallexample
13552 @noindent
13553 Here are the project files that we must place in a directory @file{main}
13554 to maintain this structure:
13556 @enumerate
13558 @item We create a @code{Common} project with a package @code{Compiler} that
13559 specifies the compilation ^switches^switches^:
13561 @smallexample
13562 File "common.gpr":
13563 @group
13564 @b{project} Common @b{is}
13566    @b{for} Source_Dirs @b{use} (); -- No source files
13567 @end group
13569 @group
13570    @b{type} Build_Type @b{is} ("release", "debug");
13571    Build : Build_Type := External ("BUILD", "debug");
13572 @end group
13573 @group
13574    @b{package} Compiler @b{is}
13575       @b{case} Build @b{is}
13576          @b{when} "release" =>
13577            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13578                    @b{use} ("^-O2^-O2^");
13579          @b{when} "debug"   =>
13580            @b{for} ^Default_Switches^Default_Switches^ ("Ada")
13581                    @b{use} ("^-g^-g^");
13582       @b{end case};
13583    @b{end} Compiler;
13585 @b{end} Common;
13586 @end group
13587 @end smallexample
13589 @item We create separate projects for the two programs:
13591 @smallexample
13592 @group
13593 File "prog1.gpr":
13595 @b{with} "common";
13596 @b{project} Prog1 @b{is}
13598     @b{for} Source_Dirs @b{use} ("prog1");
13599     @b{for} Object_Dir  @b{use} "prog1/build/" & Common.Build;
13601     @b{package} Compiler @b{renames} Common.Compiler;
13603 @b{end} Prog1;
13604 @end group
13605 @end smallexample
13607 @smallexample
13608 @group
13609 File "prog2.gpr":
13611 @b{with} "common";
13612 @b{project} Prog2 @b{is}
13614     @b{for} Source_Dirs @b{use} ("prog2");
13615     @b{for} Object_Dir  @b{use} "prog2/build/" & Common.Build;
13617     @b{package} Compiler @b{renames} Common.Compiler;
13619 @end group
13620 @b{end} Prog2;
13621 @end smallexample
13623 @item We create a wrapping project @code{Main}:
13625 @smallexample
13626 @group
13627 File "main.gpr":
13629 @b{with} "common";
13630 @b{with} "prog1";
13631 @b{with} "prog2";
13632 @b{project} Main @b{is}
13634    @b{package} Compiler @b{renames} Common.Compiler;
13636 @b{end} Main;
13637 @end group
13638 @end smallexample
13640 @item Finally we need to create a dummy procedure that @code{with}s (either
13641 explicitly or implicitly) all the sources of our two programs.
13643 @end enumerate
13645 @noindent
13646 Now we can build the programs using the command
13648 @smallexample
13649    gnatmake ^-P^/PROJECT_FILE=^main dummy
13650 @end smallexample
13652 @noindent
13653 for the Debug mode, or
13655 @ifclear vms
13656 @smallexample
13657    gnatmake -Pmain -XBUILD=release
13658 @end smallexample
13659 @end ifclear
13661 @ifset vms
13662 @smallexample
13663    GNAT MAKE /PROJECT_FILE=main /EXTERNAL_REFERENCE=BUILD=release
13664 @end smallexample
13665 @end ifset
13667 @noindent
13668 for the Release mode.
13670 @c ********************************
13671 @c * Project File Complete Syntax *
13672 @c ********************************
13674 @node Project File Complete Syntax
13675 @section Project File Complete Syntax
13677 @smallexample
13678 project ::=
13679   context_clause project_declaration
13681 context_clause ::=
13682   @{with_clause@}
13684 with_clause ::=
13685   @b{with} path_name @{ , path_name @} ;
13687 path_name ::=
13688    string_literal
13690 project_declaration ::=
13691   simple_project_declaration | project_extension
13693 simple_project_declaration ::=
13694   @b{project} <project_>simple_name @b{is}
13695     @{declarative_item@}
13696   @b{end} <project_>simple_name;
13698 project_extension ::=
13699   @b{project} <project_>simple_name  @b{extends} path_name @b{is}
13700     @{declarative_item@}
13701   @b{end} <project_>simple_name;
13703 declarative_item ::=
13704   package_declaration |
13705   typed_string_declaration |
13706   other_declarative_item
13708 package_declaration ::=
13709   package_specification | package_renaming
13711 package_specification ::=
13712   @b{package} package_identifier @b{is}
13713     @{simple_declarative_item@}
13714   @b{end} package_identifier ;
13716 package_identifier ::=
13717   @code{Naming} | @code{Builder} | @code{Compiler} | @code{Binder} |
13718   @code{Linker} | @code{Finder}  | @code{Cross_Reference} |
13719   @code{^gnatls^gnatls^} | @code{IDE}     | @code{Pretty_Printer}
13721 package_renaming ::==
13722   @b{package} package_identifier @b{renames}
13723        <project_>simple_name.package_identifier ;
13725 typed_string_declaration ::=
13726   @b{type} <typed_string_>_simple_name @b{is}
13727    ( string_literal @{, string_literal@} );
13729 other_declarative_item ::=
13730   attribute_declaration |
13731   typed_variable_declaration |
13732   variable_declaration |
13733   case_construction
13735 attribute_declaration ::=
13736   full_associative_array_declaration |
13737   @b{for} attribute_designator @b{use} expression ;
13739 full_associative_array_declaration ::=
13740   @b{for} <associative_array_attribute_>simple_name @b{use}
13741   <project_>simple_name [ . <package_>simple_Name ] ' <attribute_>simple_name ;
13743 attribute_designator ::=
13744   <simple_attribute_>simple_name |
13745   <associative_array_attribute_>simple_name ( string_literal )
13747 typed_variable_declaration ::=
13748   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
13750 variable_declaration ::=
13751   <variable_>simple_name := expression;
13753 expression ::=
13754   term @{& term@}
13756 term ::=
13757   literal_string |
13758   string_list |
13759   <variable_>name |
13760   external_value |
13761   attribute_reference
13763 string_literal ::=
13764   (same as Ada)
13766 string_list ::=
13767   ( <string_>expression @{ , <string_>expression @} )
13769 external_value ::=
13770   @b{external} ( string_literal [, string_literal] )
13772 attribute_reference ::=
13773   attribute_prefix ' <simple_attribute_>simple_name [ ( literal_string ) ]
13775 attribute_prefix ::=
13776   @b{project} |
13777   <project_>simple_name | package_identifier |
13778   <project_>simple_name . package_identifier
13780 case_construction ::=
13781   @b{case} <typed_variable_>name @b{is}
13782     @{case_item@}
13783   @b{end case} ;
13785 case_item ::=
13786   @b{when} discrete_choice_list =>
13787       @{case_construction | attribute_declaration@}
13789 discrete_choice_list ::=
13790   string_literal @{| string_literal@} |
13791   @b{others}
13793 name ::=
13794   simple_name @{. simple_name@}
13796 simple_name ::=
13797   identifier (same as Ada)
13799 @end smallexample
13801 @node The Cross-Referencing Tools gnatxref and gnatfind
13802 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13803 @findex gnatxref
13804 @findex gnatfind
13806 @noindent
13807 The compiler generates cross-referencing information (unless
13808 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13809 This information indicates where in the source each entity is declared and
13810 referenced. Note that entities in package Standard are not included, but
13811 entities in all other predefined units are included in the output.
13813 Before using any of these two tools, you need to compile successfully your
13814 application, so that GNAT gets a chance to generate the cross-referencing
13815 information.
13817 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13818 information to provide the user with the capability to easily locate the
13819 declaration and references to an entity. These tools are quite similar,
13820 the difference being that @code{gnatfind} is intended for locating
13821 definitions and/or references to a specified entity or entities, whereas
13822 @code{gnatxref} is oriented to generating a full report of all
13823 cross-references.
13825 To use these tools, you must not compile your application using the
13826 @option{-gnatx} switch on the @command{gnatmake} command line
13827 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13828 information will not be generated.
13830 @menu
13831 * gnatxref Switches::
13832 * gnatfind Switches::
13833 * Project Files for gnatxref and gnatfind::
13834 * Regular Expressions in gnatfind and gnatxref::
13835 * Examples of gnatxref Usage::
13836 * Examples of gnatfind Usage::
13837 @end menu
13839 @node gnatxref Switches
13840 @section @code{gnatxref} Switches
13842 @noindent
13843 The command invocation for @code{gnatxref} is:
13844 @smallexample
13845 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13846 @end smallexample
13848 @noindent
13849 where
13851 @table @code
13852 @item sourcefile1, sourcefile2
13853 identifies the source files for which a report is to be generated. The
13854 ``with''ed units will be processed too. You must provide at least one file.
13856 These file names are considered to be regular expressions, so for instance
13857 specifying @file{source*.adb} is the same as giving every file in the current
13858 directory whose name starts with @file{source} and whose extension is
13859 @file{adb}.
13861 You shouldn't specify any directory name, just base names. @command{gnatxref}
13862 and @command{gnatfind} will be able to locate these files by themselves using
13863 the source path. If you specify directories, no result is produced.
13865 @end table
13867 @noindent
13868 The switches can be :
13869 @table @option
13870 @c !sort!
13871 @item ^-a^/ALL_FILES^
13872 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13873 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13874 the read-only files found in the library search path. Otherwise, these files
13875 will be ignored. This option can be used to protect Gnat sources or your own
13876 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13877 much faster, and their output much smaller. Read-only here refers to access
13878 or permissions status in the file system for the current user.
13880 @item -aIDIR
13881 @cindex @option{-aIDIR} (@command{gnatxref})
13882 When looking for source files also look in directory DIR. The order in which
13883 source file search is undertaken is the same as for @command{gnatmake}.
13885 @item -aODIR
13886 @cindex @option{-aODIR} (@command{gnatxref})
13887 When searching for library and object files, look in directory
13888 DIR. The order in which library files are searched is the same as for
13889 @command{gnatmake}.
13891 @item -nostdinc
13892 @cindex @option{-nostdinc} (@command{gnatxref})
13893 Do not look for sources in the system default directory.
13895 @item -nostdlib
13896 @cindex @option{-nostdlib} (@command{gnatxref})
13897 Do not look for library files in the system default directory.
13899 @item --RTS=@var{rts-path}
13900 @cindex @option{--RTS} (@command{gnatxref})
13901 Specifies the default location of the runtime library. Same meaning as the
13902 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13904 @item ^-d^/DERIVED_TYPES^
13905 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13906 If this switch is set @code{gnatxref} will output the parent type
13907 reference for each matching derived types.
13909 @item ^-f^/FULL_PATHNAME^
13910 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13911 If this switch is set, the output file names will be preceded by their
13912 directory (if the file was found in the search path). If this switch is
13913 not set, the directory will not be printed.
13915 @item ^-g^/IGNORE_LOCALS^
13916 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13917 If this switch is set, information is output only for library-level
13918 entities, ignoring local entities. The use of this switch may accelerate
13919 @code{gnatfind} and @code{gnatxref}.
13921 @item -IDIR
13922 @cindex @option{-IDIR} (@command{gnatxref})
13923 Equivalent to @samp{-aODIR -aIDIR}.
13925 @item -pFILE
13926 @cindex @option{-pFILE} (@command{gnatxref})
13927 Specify a project file to use @xref{Project Files}. These project files are
13928 the @file{.adp} files used by Glide. If you need to use the @file{.gpr}
13929 project files, you should use gnatxref through the GNAT driver
13930 (@command{gnat xref -Pproject}).
13932 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13933 project file in the current directory.
13935 If a project file is either specified or found by the tools, then the content
13936 of the source directory and object directory lines are added as if they
13937 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13938 and @samp{^-aO^OBJECT_SEARCH^}.
13939 @item ^-u^/UNUSED^
13940 Output only unused symbols. This may be really useful if you give your
13941 main compilation unit on the command line, as @code{gnatxref} will then
13942 display every unused entity and 'with'ed package.
13944 @ifclear vms
13945 @item -v
13946 Instead of producing the default output, @code{gnatxref} will generate a
13947 @file{tags} file that can be used by vi. For examples how to use this
13948 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13949 to the standard output, thus you will have to redirect it to a file.
13950 @end ifclear
13952 @end table
13954 @noindent
13955 All these switches may be in any order on the command line, and may even
13956 appear after the file names. They need not be separated by spaces, thus
13957 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13958 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13960 @node gnatfind Switches
13961 @section @code{gnatfind} Switches
13963 @noindent
13964 The command line for @code{gnatfind} is:
13966 @smallexample
13967 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13968       [file1 file2 ...]
13969 @end smallexample
13971 @noindent
13972 where
13974 @table @code
13975 @item pattern
13976 An entity will be output only if it matches the regular expression found
13977 in @samp{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13979 Omitting the pattern is equivalent to specifying @samp{*}, which
13980 will match any entity. Note that if you do not provide a pattern, you
13981 have to provide both a sourcefile and a line.
13983 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13984 for matching purposes. At the current time there is no support for
13985 8-bit codes other than Latin-1, or for wide characters in identifiers.
13987 @item sourcefile
13988 @code{gnatfind} will look for references, bodies or declarations
13989 of symbols referenced in @file{sourcefile}, at line @samp{line}
13990 and column @samp{column}. See @ref{Examples of gnatfind Usage}
13991 for syntax examples.
13993 @item line
13994 is a decimal integer identifying the line number containing
13995 the reference to the entity (or entities) to be located.
13997 @item column
13998 is a decimal integer identifying the exact location on the
13999 line of the first character of the identifier for the
14000 entity reference. Columns are numbered from 1.
14002 @item file1 file2 ...
14003 The search will be restricted to these source files. If none are given, then
14004 the search will be done for every library file in the search path.
14005 These file must appear only after the pattern or sourcefile.
14007 These file names are considered to be regular expressions, so for instance
14008 specifying 'source*.adb' is the same as giving every file in the current
14009 directory whose name starts with 'source' and whose extension is 'adb'.
14011 The location of the spec of the entity will always be displayed, even if it
14012 isn't in one of file1, file2,... The occurrences of the entity in the
14013 separate units of the ones given on the command line will also be displayed.
14015 Note that if you specify at least one file in this part, @code{gnatfind} may
14016 sometimes not be able to find the body of the subprograms...
14018 @end table
14020 @noindent
14021 At least one of 'sourcefile' or 'pattern' has to be present on
14022 the command line.
14024 The following switches are available:
14025 @table @option
14026 @c !sort!
14028 @item ^-a^/ALL_FILES^
14029 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
14030 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
14031 the read-only files found in the library search path. Otherwise, these files
14032 will be ignored. This option can be used to protect Gnat sources or your own
14033 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
14034 much faster, and their output much smaller. Read-only here refers to access
14035 or permission status in the file system for the current user.
14037 @item -aIDIR
14038 @cindex @option{-aIDIR} (@command{gnatfind})
14039 When looking for source files also look in directory DIR. The order in which
14040 source file search is undertaken is the same as for @command{gnatmake}.
14042 @item -aODIR
14043 @cindex @option{-aODIR} (@command{gnatfind})
14044 When searching for library and object files, look in directory
14045 DIR. The order in which library files are searched is the same as for
14046 @command{gnatmake}.
14048 @item -nostdinc
14049 @cindex @option{-nostdinc} (@command{gnatfind})
14050 Do not look for sources in the system default directory.
14052 @item -nostdlib
14053 @cindex @option{-nostdlib} (@command{gnatfind})
14054 Do not look for library files in the system default directory.
14056 @item --RTS=@var{rts-path}
14057 @cindex @option{--RTS} (@command{gnatfind})
14058 Specifies the default location of the runtime library. Same meaning as the
14059 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
14061 @item ^-d^/DERIVED_TYPE_INFORMATION^
14062 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
14063 If this switch is set, then @code{gnatfind} will output the parent type
14064 reference for each matching derived types.
14066 @item ^-e^/EXPRESSIONS^
14067 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
14068 By default, @code{gnatfind} accept the simple regular expression set for
14069 @samp{pattern}. If this switch is set, then the pattern will be
14070 considered as full Unix-style regular expression.
14072 @item ^-f^/FULL_PATHNAME^
14073 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
14074 If this switch is set, the output file names will be preceded by their
14075 directory (if the file was found in the search path). If this switch is
14076 not set, the directory will not be printed.
14078 @item ^-g^/IGNORE_LOCALS^
14079 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
14080 If this switch is set, information is output only for library-level
14081 entities, ignoring local entities. The use of this switch may accelerate
14082 @code{gnatfind} and @code{gnatxref}.
14084 @item -IDIR
14085 @cindex @option{-IDIR} (@command{gnatfind})
14086 Equivalent to @samp{-aODIR -aIDIR}.
14088 @item -pFILE
14089 @cindex @option{-pFILE} (@command{gnatfind})
14090 Specify a project file (@pxref{Project Files}) to use.
14091 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
14092 project file in the current directory.
14094 If a project file is either specified or found by the tools, then the content
14095 of the source directory and object directory lines are added as if they
14096 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
14097 @samp{^-aO^/OBJECT_SEARCH^}.
14099 @item ^-r^/REFERENCES^
14100 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
14101 By default, @code{gnatfind} will output only the information about the
14102 declaration, body or type completion of the entities. If this switch is
14103 set, the @code{gnatfind} will locate every reference to the entities in
14104 the files specified on the command line (or in every file in the search
14105 path if no file is given on the command line).
14107 @item ^-s^/PRINT_LINES^
14108 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
14109 If this switch is set, then @code{gnatfind} will output the content
14110 of the Ada source file lines were the entity was found.
14112 @item ^-t^/TYPE_HIERARCHY^
14113 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
14114 If this switch is set, then @code{gnatfind} will output the type hierarchy for
14115 the specified type. It act like -d option but recursively from parent
14116 type to parent type. When this switch is set it is not possible to
14117 specify more than one file.
14119 @end table
14121 @noindent
14122 All these switches may be in any order on the command line, and may even
14123 appear after the file names. They need not be separated by spaces, thus
14124 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
14125 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
14127 As stated previously, gnatfind will search in every directory in the
14128 search path. You can force it to look only in the current directory if
14129 you specify @code{*} at the end of the command line.
14131 @node Project Files for gnatxref and gnatfind
14132 @section Project Files for @command{gnatxref} and @command{gnatfind}
14134 @noindent
14135 Project files allow a programmer to specify how to compile its
14136 application, where to find sources, etc.  These files are used
14137 @ifclear vms
14138 primarily by the Glide Ada mode, but they can also be used
14139 @end ifclear
14140 by the two tools
14141 @code{gnatxref} and @code{gnatfind}.
14143 A project file name must end with @file{.gpr}. If a single one is
14144 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
14145 extract the information from it. If multiple project files are found, none of
14146 them is read, and you have to use the @samp{-p} switch to specify the one
14147 you want to use.
14149 The following lines can be included, even though most of them have default
14150 values which can be used in most cases.
14151 The lines can be entered in any order in the file.
14152 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
14153 each line. If you have multiple instances, only the last one is taken into
14154 account.
14156 @table @code
14157 @item src_dir=DIR
14158 [default: @code{"^./^[]^"}]
14159 specifies a directory where to look for source files. Multiple @code{src_dir}
14160 lines can be specified and they will be searched in the order they
14161 are specified.
14163 @item obj_dir=DIR
14164 [default: @code{"^./^[]^"}]
14165 specifies a directory where to look for object and library files. Multiple
14166 @code{obj_dir} lines can be specified, and they will be searched in the order
14167 they are specified
14169 @item comp_opt=SWITCHES
14170 [default: @code{""}]
14171 creates a variable which can be referred to subsequently by using
14172 the @code{$@{comp_opt@}} notation. This is intended to store the default
14173 switches given to @command{gnatmake} and @command{gcc}.
14175 @item bind_opt=SWITCHES
14176 [default: @code{""}]
14177 creates a variable which can be referred to subsequently by using
14178 the @samp{$@{bind_opt@}} notation. This is intended to store the default
14179 switches given to @command{gnatbind}.
14181 @item link_opt=SWITCHES
14182 [default: @code{""}]
14183 creates a variable which can be referred to subsequently by using
14184 the @samp{$@{link_opt@}} notation. This is intended to store the default
14185 switches given to @command{gnatlink}.
14187 @item main=EXECUTABLE
14188 [default: @code{""}]
14189 specifies the name of the executable for the application. This variable can
14190 be referred to in the following lines by using the @samp{$@{main@}} notation.
14192 @ifset vms
14193 @item comp_cmd=COMMAND
14194 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
14195 @end ifset
14196 @ifclear vms
14197 @item comp_cmd=COMMAND
14198 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
14199 @end ifclear
14200 specifies the command used to compile a single file in the application.
14202 @ifset vms
14203 @item make_cmd=COMMAND
14204 [default: @code{"GNAT MAKE $@{main@}
14205 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
14206 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
14207 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
14208 @end ifset
14209 @ifclear vms
14210 @item make_cmd=COMMAND
14211 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
14212  -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
14213  -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
14214 @end ifclear
14215 specifies the command used to recompile the whole application.
14217 @item run_cmd=COMMAND
14218 [default: @code{"$@{main@}"}]
14219 specifies the command used to run the application.
14221 @item debug_cmd=COMMAND
14222 [default: @code{"gdb $@{main@}"}]
14223 specifies the command used to debug the application
14225 @end table
14227 @noindent
14228 @command{gnatxref} and @command{gnatfind} only take into account the
14229 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
14231 @node Regular Expressions in gnatfind and gnatxref
14232 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
14234 @noindent
14235 As specified in the section about @command{gnatfind}, the pattern can be a
14236 regular expression. Actually, there are to set of regular expressions
14237 which are recognized by the program :
14239 @table @code
14240 @item globbing patterns
14241 These are the most usual regular expression. They are the same that you
14242 generally used in a Unix shell command line, or in a DOS session.
14244 Here is a more formal grammar :
14245 @smallexample
14246 @group
14247 @iftex
14248 @leftskip=.5cm
14249 @end iftex
14250 regexp ::= term
14251 term   ::= elmt            -- matches elmt
14252 term   ::= elmt elmt       -- concatenation (elmt then elmt)
14253 term   ::= *               -- any string of 0 or more characters
14254 term   ::= ?               -- matches any character
14255 term   ::= [char @{char@}] -- matches any character listed
14256 term   ::= [char - char]   -- matches any character in range
14257 @end group
14258 @end smallexample
14260 @item full regular expression
14261 The second set of regular expressions is much more powerful. This is the
14262 type of regular expressions recognized by utilities such a @file{grep}.
14264 The following is the form of a regular expression, expressed in Ada
14265 reference manual style BNF is as follows
14267 @smallexample
14268 @iftex
14269 @leftskip=.5cm
14270 @end iftex
14271 @group
14272 regexp ::= term @{| term@} -- alternation (term or term ...)
14274 term ::= item @{item@}     -- concatenation (item then item)
14276 item ::= elmt              -- match elmt
14277 item ::= elmt *            -- zero or more elmt's
14278 item ::= elmt +            -- one or more elmt's
14279 item ::= elmt ?            -- matches elmt or nothing
14280 @end group
14281 @group
14282 elmt ::= nschar            -- matches given character
14283 elmt ::= [nschar @{nschar@}]   -- matches any character listed
14284 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
14285 elmt ::= [char - char]     -- matches chars in given range
14286 elmt ::= \ char            -- matches given character
14287 elmt ::= .                 -- matches any single character
14288 elmt ::= ( regexp )        -- parens used for grouping
14290 char ::= any character, including special characters
14291 nschar ::= any character except ()[].*+?^^^
14292 @end group
14293 @end smallexample
14295 Following are a few examples :
14297 @table @samp
14298 @item abcde|fghi
14299 will match any of the two strings 'abcde' and 'fghi'.
14301 @item abc*d
14302 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
14304 @item [a-z]+
14305 will match any string which has only lowercase characters in it (and at
14306 least one character
14308 @end table
14309 @end table
14311 @node Examples of gnatxref Usage
14312 @section Examples of @code{gnatxref} Usage
14314 @subsection General Usage
14316 @noindent
14317 For the following examples, we will consider the following units :
14319 @smallexample @c ada
14320 @group
14321 @cartouche
14322 main.ads:
14323 1: with Bar;
14324 2: package Main is
14325 3:     procedure Foo (B : in Integer);
14326 4:     C : Integer;
14327 5: private
14328 6:     D : Integer;
14329 7: end Main;
14331 main.adb:
14332 1: package body Main is
14333 2:     procedure Foo (B : in Integer) is
14334 3:     begin
14335 4:        C := B;
14336 5:        D := B;
14337 6:        Bar.Print (B);
14338 7:        Bar.Print (C);
14339 8:     end Foo;
14340 9: end Main;
14342 bar.ads:
14343 1: package Bar is
14344 2:     procedure Print (B : Integer);
14345 3: end bar;
14346 @end cartouche
14347 @end group
14348 @end smallexample
14350 @table @code
14352 @noindent
14353 The first thing to do is to recompile your application (for instance, in
14354 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14355 the cross-referencing information.
14356 You can then issue any of the following commands:
14358 @item gnatxref main.adb
14359 @code{gnatxref} generates cross-reference information for main.adb
14360 and every unit 'with'ed by main.adb.
14362 The output would be:
14363 @smallexample
14364 @iftex
14365 @leftskip=0cm
14366 @end iftex
14367 B                                                      Type: Integer
14368   Decl: bar.ads           2:22
14369 B                                                      Type: Integer
14370   Decl: main.ads          3:20
14371   Body: main.adb          2:20
14372   Ref:  main.adb          4:13     5:13     6:19
14373 Bar                                                    Type: Unit
14374   Decl: bar.ads           1:9
14375   Ref:  main.adb          6:8      7:8
14376        main.ads           1:6
14377 C                                                      Type: Integer
14378   Decl: main.ads          4:5
14379   Modi: main.adb          4:8
14380   Ref:  main.adb          7:19
14381 D                                                      Type: Integer
14382   Decl: main.ads          6:5
14383   Modi: main.adb          5:8
14384 Foo                                                    Type: Unit
14385   Decl: main.ads          3:15
14386   Body: main.adb          2:15
14387 Main                                                    Type: Unit
14388   Decl: main.ads          2:9
14389   Body: main.adb          1:14
14390 Print                                                   Type: Unit
14391   Decl: bar.ads           2:15
14392   Ref:  main.adb          6:12     7:12
14393 @end smallexample
14395 @noindent
14396 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14397 its body is in main.adb, line 1, column 14 and is not referenced any where.
14399 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14400 it referenced in main.adb, line 6 column 12 and line 7 column 12.
14402 @item gnatxref package1.adb package2.ads
14403 @code{gnatxref} will generates cross-reference information for
14404 package1.adb, package2.ads and any other package 'with'ed by any
14405 of these.
14407 @end table
14409 @ifclear vms
14410 @subsection Using gnatxref with vi
14412 @code{gnatxref} can generate a tags file output, which can be used
14413 directly from @file{vi}. Note that the standard version of @file{vi}
14414 will not work properly with overloaded symbols. Consider using another
14415 free implementation of @file{vi}, such as @file{vim}.
14417 @smallexample
14418 $ gnatxref -v gnatfind.adb > tags
14419 @end smallexample
14421 @noindent
14422 will generate the tags file for @code{gnatfind} itself (if the sources
14423 are in the search path!).
14425 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
14426 (replacing @i{entity} by whatever you are looking for), and vi will
14427 display a new file with the corresponding declaration of entity.
14428 @end ifclear
14430 @node Examples of gnatfind Usage
14431 @section Examples of @code{gnatfind} Usage
14433 @table @code
14435 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14436 Find declarations for all entities xyz referenced at least once in
14437 main.adb. The references are search in every library file in the search
14438 path.
14440 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14441 switch is set)
14443 The output will look like:
14444 @smallexample
14445 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14446 ^directory/^[directory]^main.adb:24:10: xyz <= body
14447 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14448 @end smallexample
14450 @noindent
14451 that is to say, one of the entities xyz found in main.adb is declared at
14452 line 12 of main.ads (and its body is in main.adb), and another one is
14453 declared at line 45 of foo.ads
14455 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14456 This is the same command as the previous one, instead @code{gnatfind} will
14457 display the content of the Ada source file lines.
14459 The output will look like:
14461 @smallexample
14462 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14463    procedure xyz;
14464 ^directory/^[directory]^main.adb:24:10: xyz <= body
14465    procedure xyz is
14466 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14467    xyz : Integer;
14468 @end smallexample
14470 @noindent
14471 This can make it easier to find exactly the location your are looking
14472 for.
14474 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14475 Find references to all entities containing an x that are
14476 referenced on line 123 of main.ads.
14477 The references will be searched only in main.ads and foo.adb.
14479 @item gnatfind main.ads:123
14480 Find declarations and bodies for all entities that are referenced on
14481 line 123 of main.ads.
14483 This is the same as @code{gnatfind "*":main.adb:123}.
14485 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14486 Find the declaration for the entity referenced at column 45 in
14487 line 123 of file main.adb in directory mydir. Note that it
14488 is usual to omit the identifier name when the column is given,
14489 since the column position identifies a unique reference.
14491 The column has to be the beginning of the identifier, and should not
14492 point to any character in the middle of the identifier.
14494 @end table
14496 @c *********************************
14497 @node The GNAT Pretty-Printer gnatpp
14498 @chapter The GNAT Pretty-Printer @command{gnatpp}
14499 @findex gnatpp
14500 @cindex Pretty-Printer
14502 @noindent
14503 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14504 for source reformatting / pretty-printing.
14505 It takes an Ada source file as input and generates a reformatted
14506 version as output.
14507 You can specify various style directives via switches; e.g.,
14508 identifier case conventions, rules of indentation, and comment layout.
14510 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
14511 tree for the input source and thus requires the input to be syntactically and
14512 semantically legal.
14513 If this condition is not met, @command{gnatpp} will terminate with an
14514 error message; no output file will be generated.
14516 If the compilation unit
14517 contained in the input source depends semantically upon units located
14518 outside the current directory, you have to provide the source search path
14519 when invoking @command{gnatpp}, if these units are contained in files with
14520 names that do not follow the GNAT file naming rules, you have to provide
14521 the configuration file describing the corresponding naming scheme;
14522 see the description of the @command{gnatpp}
14523 switches below. Another possibility is to use a project file and to
14524 call @command{gnatpp} through the @command{gnat} driver
14526 The @command{gnatpp} command has the form
14528 @smallexample
14529 $ gnatpp [@var{switches}] @var{filename}
14530 @end smallexample
14532 @noindent
14533 where
14534 @itemize @bullet
14535 @item
14536 @var{switches} is an optional sequence of switches defining such properties as
14537 the formatting rules, the source search path, and the destination for the
14538 output source file
14540 @item
14541 @var{filename} is the name (including the extension) of the source file to
14542 reformat; ``wildcards'' or several file names on the same gnatpp command are
14543 allowed.  The file name may contain path information; it does not have to
14544 follow the GNAT file naming rules
14545 @end itemize
14547 @menu
14548 * Switches for gnatpp::
14549 * Formatting Rules::
14550 @end menu
14552 @node Switches for gnatpp
14553 @section Switches for @command{gnatpp}
14555 @noindent
14556 The following subsections describe the various switches accepted by
14557 @command{gnatpp}, organized by category.
14559 @ifclear vms
14560 You specify a switch by supplying a name and generally also a value.
14561 In many cases the values for a switch with a given name are incompatible with
14562 each other
14563 (for example the switch that controls the casing of a reserved word may have
14564 exactly one value: upper case, lower case, or
14565 mixed case) and thus exactly one such switch can be in effect for an
14566 invocation of @command{gnatpp}.
14567 If more than one is supplied, the last one is used.
14568 However, some values for the same switch are mutually compatible.
14569 You may supply several such switches to @command{gnatpp}, but then
14570 each must be specified in full, with both the name and the value.
14571 Abbreviated forms (the name appearing once, followed by each value) are
14572 not permitted.
14573 For example, to set
14574 the alignment of the assignment delimiter both in declarations and in
14575 assignment statements, you must write @option{-A2A3}
14576 (or @option{-A2 -A3}), but not @option{-A23}.
14577 @end ifclear
14579 @ifset vms
14580 In many cases the set of options for a given qualifier are incompatible with
14581 each other (for example the qualifier that controls the casing of a reserved
14582 word may have exactly one option, which specifies either upper case, lower
14583 case, or mixed case), and thus exactly one such option can be in effect for
14584 an invocation of @command{gnatpp}.
14585 If more than one is supplied, the last one is used.
14586 However, some qualifiers have options that are mutually compatible,
14587 and then you may then supply several such options when invoking
14588 @command{gnatpp}.
14589 @end ifset
14591 In most cases, it is obvious whether or not the
14592 ^values for a switch with a given name^options for a given qualifier^
14593 are compatible with each other.
14594 When the semantics might not be evident, the summaries below explicitly
14595 indicate the effect.
14597 @menu
14598 * Alignment Control::
14599 * Casing Control::
14600 * Construct Layout Control::
14601 * General Text Layout Control::
14602 * Other Formatting Options::
14603 * Setting the Source Search Path::
14604 * Output File Control::
14605 * Other gnatpp Switches::
14606 @end menu
14608 @node Alignment Control
14609 @subsection Alignment Control
14610 @cindex Alignment control in @command{gnatpp}
14612 @noindent
14613 Programs can be easier to read if certain constructs are vertically aligned.
14614 By default all alignments are set ON.
14615 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14616 OFF, and then use one or more of the other
14617 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14618 to activate alignment for specific constructs.
14620 @table @option
14621 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14623 @ifset vms
14624 @item /ALIGN=ON
14625 Set all alignments to ON
14626 @end ifset
14628 @item ^-A0^/ALIGN=OFF^
14629 Set all alignments to OFF
14631 @item ^-A1^/ALIGN=COLONS^
14632 Align @code{:} in declarations
14634 @item ^-A2^/ALIGN=DECLARATIONS^
14635 Align @code{:=} in initializations in declarations
14637 @item ^-A3^/ALIGN=STATEMENTS^
14638 Align @code{:=} in assignment statements
14640 @item ^-A4^/ALIGN=ARROWS^
14641 Align @code{=>} in associations
14643 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
14644 Align @code{at} keywords in the component clauses in record representation clauses
14645 @end table
14647 @noindent
14648 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14649 is allowed.
14651 @node Casing Control
14652 @subsection Casing Control
14653 @cindex Casing control in @command{gnatpp}
14655 @noindent
14656 @command{gnatpp} allows you to specify the casing for reserved words,
14657 pragma names, attribute designators and identifiers.
14658 For identifiers you may define a
14659 general rule for name casing but also override this rule
14660 via a set of dictionary files.
14662 Three types of casing are supported: lower case, upper case, and mixed case.
14663 Lower and upper case are self-explanatory (but since some letters in
14664 Latin1 and other GNAT-supported character sets
14665 exist only in lower-case form, an upper case conversion will have no
14666 effect on them.)
14667 ``Mixed case'' means that the first letter, and also each letter immediately
14668 following an underscore, are converted to their uppercase forms;
14669 all the other letters are converted to their lowercase forms.
14671 @table @option
14672 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14673 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14674 Attribute designators are lower case
14676 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14677 Attribute designators are upper case
14679 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14680 Attribute designators are mixed case (this is the default)
14682 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14683 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14684 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14685 lower case (this is the default)
14687 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14688 Keywords are upper case
14690 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14691 @item ^-nD^/NAME_CASING=AS_DECLARED^
14692 Name casing for defining occurrences are as they appear in the source file
14693 (this is the default)
14695 @item ^-nU^/NAME_CASING=UPPER_CASE^
14696 Names are in upper case
14698 @item ^-nL^/NAME_CASING=LOWER_CASE^
14699 Names are in lower case
14701 @item ^-nM^/NAME_CASING=MIXED_CASE^
14702 Names are in mixed case
14704 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14705 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14706 Pragma names are lower case
14708 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14709 Pragma names are upper case
14711 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14712 Pragma names are mixed case (this is the default)
14714 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14715 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14716 Use @var{file} as a @emph{dictionary file} that defines
14717 the casing for a set of specified names,
14718 thereby overriding the effect on these names by
14719 any explicit or implicit
14720 ^-n^/NAME_CASING^ switch.
14721 To supply more than one dictionary file,
14722 use ^several @option{-D} switches^a list of files as options^.
14724 @noindent
14725 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14726 to define the casing for the Ada predefined names and
14727 the names declared in the GNAT libraries.
14729 @item ^-D-^/SPECIFIC_CASING^
14730 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14731 Do not use the default dictionary file;
14732 instead, use the casing
14733 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14734 dictionary file(s)
14735 @end table
14737 @noindent
14738 The structure of a dictionary file, and details on the conventions
14739 used in the default dictionary file, are defined in @ref{Name Casing}.
14741 The @option{^-D-^/SPECIFIC_CASING^} and
14742 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14743 compatible.
14745 @node Construct Layout Control
14746 @subsection Construct Layout Control
14747 @cindex Layout control in @command{gnatpp}
14749 @noindent
14750 This group of @command{gnatpp} switches controls the layout of comments and
14751 complex syntactic constructs.  See @ref{Formatting Comments} for details
14752 on their effect.
14754 @table @option
14755 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14756 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14757 All the comments remain unchanged
14759 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14760 GNAT-style comment line indentation (this is the default).
14762 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14763 Reference-manual comment line indentation.
14765 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14766 GNAT-style comment beginning
14768 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14769 Reformat comment blocks
14771 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14772 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14773 GNAT-style layout (this is the default)
14775 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14776 Compact layout
14778 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14779 Uncompact layout
14781 @item ^-notab^/NOTABS^
14782 All the VT characters are removed from the comment text. All the HT characters
14783 are expanded with the sequences of space characters to get to the next tab
14784 stops.
14786 @end table
14788 @ifclear vms
14789 @noindent
14790 The @option{-c1} and @option{-c2} switches are incompatible.
14791 The @option{-c3} and @option{-c4} switches are compatible with each other and
14792 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14793 the other comment formatting switches.
14795 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14796 @end ifclear
14798 @ifset vms
14799 @noindent
14800 For the @option{/COMMENTS_LAYOUT} qualifier:
14801 @itemize @bullet
14802 @item
14803 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14804 @item
14805 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14806 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14807 @end itemize
14809 @noindent
14810 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14811 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14812 @end ifset
14814 @node General Text Layout Control
14815 @subsection General Text Layout Control
14817 @noindent
14818 These switches allow control over line length and indentation.
14820 @table @option
14821 @item ^-M@i{nnn}^/LINE_LENGTH_MAX=@i{nnn}^
14822 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14823 Maximum line length, @i{nnn} from 32 ..256, the default value is 79
14825 @item ^-i@i{nnn}^/INDENTATION_LEVEL=@i{nnn}^
14826 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14827 Indentation level, @i{nnn} from 1 .. 9, the default value is 3
14829 @item ^-cl@i{nnn}^/CONTINUATION_INDENT=@i{nnn}^
14830 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14831 Indentation level for continuation lines (relative to the line being
14832 continued), @i{nnn} from 1 .. 9.
14833 The default
14834 value is one less then the (normal) indentation level, unless the
14835 indentation is set to 1 (in which case the default value for continuation
14836 line indentation is also 1)
14837 @end table
14839 @node Other Formatting Options
14840 @subsection Other Formatting Options
14842 @noindent
14843 These switches control the inclusion of missing end/exit labels, and
14844 the indentation level in @b{case} statements.
14846 @table @option
14847 @item ^-e^/NO_MISSED_LABELS^
14848 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14849 Do not insert missing end/exit labels. An end label is the name of
14850 a construct that may optionally be repeated at the end of the
14851 construct's declaration;
14852 e.g., the names of packages, subprograms, and tasks.
14853 An exit label is the name of a loop that may appear as target
14854 of an exit statement within the loop.
14855 By default, @command{gnatpp} inserts these end/exit labels when
14856 they are absent from the original source. This option suppresses such
14857 insertion, so that the formatted source reflects the original.
14859 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14860 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14861 Insert a Form Feed character after a pragma Page.
14863 @item ^-T@i{nnn}^/MAX_INDENT=@i{nnn}^
14864 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14865 Do not use an additional indentation level for @b{case} alternatives
14866 and variants if there are @i{nnn} or more (the default
14867 value is 10).
14868 If @i{nnn} is 0, an additional indentation level is
14869 used for @b{case} alternatives and variants regardless of their number.
14870 @end table
14872 @node Setting the Source Search Path
14873 @subsection Setting the Source Search Path
14875 @noindent
14876 To define the search path for the input source file, @command{gnatpp}
14877 uses the same switches as the GNAT compiler, with the same effects.
14879 @table @option
14880 @item ^-I^/SEARCH=^@var{dir}
14881 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14882 The same as the corresponding gcc switch
14884 @item ^-I-^/NOCURRENT_DIRECTORY^
14885 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14886 The same as the corresponding gcc switch
14888 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14889 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14890 The same as the corresponding gcc switch
14892 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14893 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14894 The same as the corresponding gcc switch
14896 @end table
14898 @node Output File Control
14899 @subsection Output File Control
14901 @noindent
14902 By default the output is sent to the file whose name is obtained by appending
14903 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14904 (if the file with this name already exists, it is unconditionally overwritten).
14905 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14906 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14907 as output file.
14908 The output may be redirected by the following switches:
14910 @table @option
14911 @item ^-pipe^/STANDARD_OUTPUT^
14912 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14913 Send the output to @code{Standard_Output}
14915 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14916 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14917 Write the output into @var{output_file}.
14918 If @var{output_file} already exists, @command{gnatpp} terminates without
14919 reading or processing the input file.
14921 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14922 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14923 Write the output into @var{output_file}, overwriting the existing file
14924 (if one is present).
14926 @item ^-r^/REPLACE^
14927 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14928 Replace the input source file with the reformatted output, and copy the
14929 original input source into the file whose name is obtained by appending the
14930 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14931 If a file with this name already exists, @command{gnatpp} terminates without
14932 reading or processing the input file.
14934 @item ^-rf^/OVERRIDING_REPLACE^
14935 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14936 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14937 already exists, it is overwritten.
14939 @item ^-rnb^/NO_BACKUP^
14940 @cindex @option{^-rnb^/NO_BACKUP^} (@code{gnatpp})
14941 Replace the input source file with the reformatted output without
14942 creating any backup copy of the input source.
14943 @end table
14945 @noindent
14946 Options @option{^-pipe^/STANDARD_OUTPUT^},
14947 @option{^-o^/OUTPUT^} and
14948 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14949 contains only one file to reformat
14951 @node Other gnatpp Switches
14952 @subsection Other @code{gnatpp} Switches
14954 @noindent
14955 The additional @command{gnatpp} switches are defined in this subsection.
14957 @table @option
14958 @item ^-files @var{filename}^/FILES=@var{output_file}^
14959 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14960 Take the argument source files from the specified file. This file should be an
14961 ordinary textual file containing file names separated by spaces or
14962 line breaks. You can use this switch more then once in the same call to
14963 @command{gnatpp}. You also can combine this switch with explicit list of
14964 files.
14966 @item ^-v^/VERBOSE^
14967 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14968 Verbose mode;
14969 @command{gnatpp} generates version information and then
14970 a trace of the actions it takes to produce or obtain the ASIS tree.
14972 @item ^-w^/WARNINGS^
14973 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14974 Warning mode;
14975 @command{gnatpp} generates a warning whenever it can not provide
14976 a required layout in the result source.
14977 @end table
14979 @node Formatting Rules
14980 @section Formatting Rules
14982 @noindent
14983 The following subsections show how @command{gnatpp} treats ``white space'',
14984 comments, program layout, and name casing.
14985 They provide the detailed descriptions of the switches shown above.
14987 @menu
14988 * White Space and Empty Lines::
14989 * Formatting Comments::
14990 * Construct Layout::
14991 * Name Casing::
14992 @end menu
14994 @node White Space and Empty Lines
14995 @subsection White Space and Empty Lines
14997 @noindent
14998 @command{gnatpp} does not have an option to control space characters.
14999 It will add or remove spaces according to the style illustrated by the
15000 examples in the @cite{Ada Reference Manual}.
15002 The only format effectors
15003 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
15004 that will appear in the output file are platform-specific line breaks,
15005 and also format effectors within (but not at the end of) comments.
15006 In particular, each horizontal tab character that is not inside
15007 a comment will be treated as a space and thus will appear in the
15008 output file as zero or more spaces depending on
15009 the reformatting of the line in which it appears.
15010 The only exception is a Form Feed character, which is inserted after a
15011 pragma @code{Page} when @option{-ff} is set.
15013 The output file will contain no lines with trailing ``white space'' (spaces,
15014 format effectors).
15016 Empty lines in the original source are preserved
15017 only if they separate declarations or statements.
15018 In such contexts, a
15019 sequence of two or more empty lines is replaced by exactly one empty line.
15020 Note that a blank line will be removed if it separates two ``comment blocks''
15021 (a comment block is a sequence of whole-line comments).
15022 In order to preserve a visual separation between comment blocks, use an
15023 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
15024 Likewise, if for some reason you wish to have a sequence of empty lines,
15025 use a sequence of empty comments instead.
15027 @node Formatting Comments
15028 @subsection Formatting Comments
15030 @noindent
15031 Comments in Ada code are of two kinds:
15032 @itemize @bullet
15033 @item
15034 a @emph{whole-line comment}, which appears by itself (possibly preceded by
15035 ``white space'') on a line
15037 @item
15038 an @emph{end-of-line comment}, which follows some other Ada lexical element
15039 on the same line.
15040 @end itemize
15042 @noindent
15043 The indentation of a whole-line comment is that of either
15044 the preceding or following line in
15045 the formatted source, depending on switch settings as will be described below.
15047 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
15048 between the end of the preceding Ada lexical element and the beginning
15049 of the comment as appear in the original source,
15050 unless either the comment has to be split to
15051 satisfy the line length limitation, or else the next line contains a
15052 whole line comment that is considered a continuation of this end-of-line
15053 comment (because it starts at the same position).
15054 In the latter two
15055 cases, the start of the end-of-line comment is moved right to the nearest
15056 multiple of the indentation level.
15057 This may result in a ``line overflow'' (the right-shifted comment extending
15058 beyond the maximum line length), in which case the comment is split as
15059 described below.
15061 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
15062 (GNAT-style comment line indentation)
15063 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
15064 (reference-manual comment line indentation).
15065 With reference-manual style, a whole-line comment is indented as if it
15066 were a declaration or statement at the same place
15067 (i.e., according to the indentation of the preceding line(s)).
15068 With GNAT style, a whole-line comment that is immediately followed by an
15069 @b{if} or @b{case} statement alternative, a record variant, or the reserved
15070 word @b{begin}, is indented based on the construct that follows it.
15072 For example:
15073 @smallexample @c ada
15074 @cartouche
15075 if A then
15076     null;
15077        -- some comment
15078 else
15079    null;
15080 end if;
15081 @end cartouche
15082 @end smallexample
15084 @noindent
15085 Reference-manual indentation produces:
15087 @smallexample @c ada
15088 @cartouche
15089 if A then
15090    null;
15091    --  some comment
15092 else
15093    null;
15094 end if;
15095 @end cartouche
15096 @end smallexample
15098 @noindent
15099 while GNAT-style indentation produces:
15101 @smallexample @c ada
15102 @cartouche
15103 if A then
15104    null;
15105 --  some comment
15106 else
15107    null;
15108 end if;
15109 @end cartouche
15110 @end smallexample
15112 @noindent
15113 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
15114 (GNAT style comment beginning) has the following
15115 effect:
15117 @itemize @bullet
15118 @item
15119 For each whole-line comment that does not end with two hyphens,
15120 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
15121 to ensure that there are at least two spaces between these hyphens and the
15122 first non-blank character of the comment.
15123 @end itemize
15125 @noindent
15126 For an end-of-line comment, if in the original source the next line is a
15127 whole-line comment that starts at the same position
15128 as the end-of-line comment,
15129 then the whole-line comment (and all whole-line comments
15130 that follow it and that start at the same position)
15131 will start at this position in the output file.
15133 @noindent
15134 That is, if in the original source we have:
15136 @smallexample @c ada
15137 @cartouche
15138 begin
15139 A := B + C;            --  B must be in the range Low1..High1
15140                        --  C must be in the range Low2..High2
15141              --B+C will be in the range Low1+Low2..High1+High2
15142 X := X + 1;
15143 @end cartouche
15144 @end smallexample
15146 @noindent
15147 Then in the formatted source we get
15149 @smallexample @c ada
15150 @cartouche
15151 begin
15152    A := B + C;            --  B must be in the range Low1..High1
15153                           --  C must be in the range Low2..High2
15154    --  B+C will be in the range Low1+Low2..High1+High2
15155    X := X + 1;
15156 @end cartouche
15157 @end smallexample
15159 @noindent
15160 A comment that exceeds the line length limit will be split.
15161 Unless switch
15162 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
15163 the line belongs to a reformattable block, splitting the line generates a
15164 @command{gnatpp} warning.
15165 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
15166 comments may be reformatted in typical
15167 word processor style (that is, moving words between lines and putting as
15168 many words in a line as possible).
15170 @node Construct Layout
15171 @subsection Construct Layout
15173 @noindent
15174 In several cases the suggested layout in the Ada Reference Manual includes
15175 an extra level of indentation that many programmers prefer to avoid. The
15176 affected cases include:
15178 @itemize @bullet
15180 @item Record type declaration (RM 3.8)
15182 @item Record representation clause (RM 13.5.1)
15184 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
15186 @item Block statement in case if a block has a statement identifier (RM 5.6)
15187 @end itemize
15189 @noindent
15190 In compact mode (when GNAT style layout or compact layout is set),
15191 the pretty printer uses one level of indentation instead
15192 of two. This is achived in the record definition and record representation
15193 clause cases by putting the @code{record} keyword on the same line as the
15194 start of the declaration or representation clause, and in the block and loop
15195 case by putting the block or loop header on the same line as the statement
15196 identifier.
15198 @noindent
15199 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
15200 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
15201 layout on the one hand, and uncompact layout
15202 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
15203 can be illustrated by the following examples:
15205 @iftex
15206 @cartouche
15207 @multitable @columnfractions .5 .5
15208 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
15210 @item
15211 @smallexample @c ada
15212 type q is record
15213    a : integer;
15214    b : integer;
15215 end record;
15216 @end smallexample
15217 @tab
15218 @smallexample @c ada
15219 type q is
15220    record
15221       a : integer;
15222       b : integer;
15223    end record;
15224 @end smallexample
15226 @item
15227 @smallexample @c ada
15228 for q use record
15229    a at 0 range  0 .. 31;
15230    b at 4 range  0 .. 31;
15231 end record;
15232 @end smallexample
15233 @tab
15234 @smallexample @c ada
15235 for q use
15236    record
15237       a at 0 range  0 .. 31;
15238       b at 4 range  0 .. 31;
15239    end record;
15240 @end smallexample
15242 @item
15243 @smallexample @c ada
15244 Block : declare
15245    A : Integer := 3;
15246 begin
15247    Proc (A, A);
15248 end Block;
15249 @end smallexample
15250 @tab
15251 @smallexample @c ada
15252 Block :
15253    declare
15254       A : Integer := 3;
15255    begin
15256       Proc (A, A);
15257    end Block;
15258 @end smallexample
15260 @item
15261 @smallexample @c ada
15262 Clear : for J in 1 .. 10 loop
15263    A (J) := 0;
15264 end loop Clear;
15265 @end smallexample
15266 @tab
15267 @smallexample @c ada
15268 Clear :
15269    for J in 1 .. 10 loop
15270       A (J) := 0;
15271    end loop Clear;
15272 @end smallexample
15273 @end multitable
15274 @end cartouche
15275 @end iftex
15277 @ifnottex
15278 @smallexample
15279 @cartouche
15280 GNAT style, compact layout              Uncompact layout
15282 type q is record                        type q is
15283    a : integer;                            record
15284    b : integer;                               a : integer;
15285 end record;                                   b : integer;
15286                                            end record;
15288 for q use record                        for q use
15289    a at 0 range  0 .. 31;                  record
15290    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
15291 end record;                                   b at 4 range  0 .. 31;
15292                                            end record;
15294 Block : declare                         Block :
15295    A : Integer := 3;                       declare
15296 begin                                         A : Integer := 3;
15297    Proc (A, A);                            begin
15298 end Block;                                    Proc (A, A);
15299                                            end Block;
15301 Clear : for J in 1 .. 10 loop           Clear :
15302    A (J) := 0;                             for J in 1 .. 10 loop
15303 end loop Clear;                               A (J) := 0;
15304                                            end loop Clear;
15305 @end cartouche
15306 @end smallexample
15307 @end ifnottex
15309 @noindent
15310 A further difference between GNAT style layout and compact layout is that
15311 GNAT style layout inserts empty lines as separation for
15312 compound statements, return statements and bodies.
15314 @node Name Casing
15315 @subsection Name Casing
15317 @noindent
15318 @command{gnatpp} always converts the usage occurrence of a (simple) name to
15319 the same casing as the corresponding defining identifier.
15321 You control the casing for defining occurrences via the
15322 @option{^-n^/NAME_CASING^} switch.
15323 @ifclear vms
15324 With @option{-nD} (``as declared'', which is the default),
15325 @end ifclear
15326 @ifset vms
15327 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15328 @end ifset
15329 defining occurrences appear exactly as in the source file
15330 where they are declared.
15331 The other ^values for this switch^options for this qualifier^ ---
15332 @option{^-nU^UPPER_CASE^},
15333 @option{^-nL^LOWER_CASE^},
15334 @option{^-nM^MIXED_CASE^} ---
15335 result in
15336 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15337 If @command{gnatpp} changes the casing of a defining
15338 occurrence, it analogously changes the casing of all the
15339 usage occurrences of this name.
15341 If the defining occurrence of a name is not in the source compilation unit
15342 currently being processed by @command{gnatpp}, the casing of each reference to
15343 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15344 switch (subject to the dictionary file mechanism described below).
15345 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15346 had affected the
15347 casing for the defining occurrence of the name.
15349 Some names may need to be spelled with casing conventions that are not
15350 covered by the upper-, lower-, and mixed-case transformations.
15351 You can arrange correct casing by placing such names in a
15352 @emph{dictionary file},
15353 and then supplying a @option{^-D^/DICTIONARY^} switch.
15354 The casing of names from dictionary files overrides
15355 any @option{^-n^/NAME_CASING^} switch.
15357 To handle the casing of Ada predefined names and the names from GNAT libraries,
15358 @command{gnatpp} assumes a default dictionary file.
15359 The name of each predefined entity is spelled with the same casing as is used
15360 for the entity in the @cite{Ada Reference Manual}.
15361 The name of each entity in the GNAT libraries is spelled with the same casing
15362 as is used in the declaration of that entity.
15364 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
15365 default dictionary file.
15366 Instead, the casing for predefined and GNAT-defined names will be established
15367 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15368 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15369 will appear as just shown,
15370 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15371 To ensure that even such names are rendered in uppercase,
15372 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15373 (or else, less conveniently, place these names in upper case in a dictionary
15374 file).
15376 A dictionary file is
15377 a plain text file; each line in this file can be either a blank line
15378 (containing only space characters and ASCII.HT characters), an Ada comment
15379 line, or the specification of exactly one @emph{casing schema}.
15381 A casing schema is a string that has the following syntax:
15383 @smallexample
15384 @cartouche
15385   @var{casing_schema} ::= @var{identifier} | [*]@var{simple_identifier}[*]
15387   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15388 @end cartouche
15389 @end smallexample
15391 @noindent
15392 (The @code{[]} metanotation stands for an optional part;
15393 see @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15394 @var{identifier} lexical element and the @var{letter_or_digit} category).
15396 The casing schema string can be followed by white space and/or an Ada-style
15397 comment; any amount of white space is allowed before the string.
15399 If a dictionary file is passed as
15400 @ifclear vms
15401 the value of a @option{-D@var{file}} switch
15402 @end ifclear
15403 @ifset vms
15404 an option to the @option{/DICTIONARY} qualifier
15405 @end ifset
15406 then for every
15407 simple name and every identifier, @command{gnatpp} checks if the dictionary
15408 defines the casing for the name or for some of its parts (the term ``subword''
15409 is used below to denote the part of a name which is delimited by ``_'' or by
15410 the beginning or end of the word and which does not contain any ``_'' inside):
15412 @itemize @bullet
15413 @item
15414 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15415 the casing defined by the dictionary; no subwords are checked for this word
15417 @item
15418 for the first subword (that is, for the subword preceding the leftmost
15419 ``_''), @command{gnatpp} checks if the dictionary contains the corresponding
15420 string of the form @code{@var{simple_identifier}*}, and if it does, the
15421 casing of this @var{simple_identifier} is used for this subword
15423 @item
15424 for the last subword (following the rightmost ``_'') @command{gnatpp}
15425 checks if the dictionary contains the corresponding string of the form
15426 @code{*@var{simple_identifier}}, and if it does, the casing of this
15427 @var{simple_identifier} is used for this subword
15429 @item
15430 for every intermediate subword (surrounded by two'_') @command{gnatpp} checks
15431 if the dictionary contains the corresponding string of the form
15432 @code{*@var{simple_identifier}*}, and if it does, the casing of this
15433 simple_identifier is used for this subword
15435 @item
15436 if more than one dictionary file is passed as @command{gnatpp} switches, each
15437 dictionary adds new casing exceptions and overrides all the existing casing
15438 exceptions set by the previous dictionaries
15440 @item
15441 when @command{gnatpp} checks if the word or subword is in the dictionary,
15442 this check is not case sensitive
15443 @end itemize
15445 @noindent
15446 For example, suppose we have the following source to reformat:
15448 @smallexample @c ada
15449 @cartouche
15450 procedure test is
15451    name1 : integer := 1;
15452    name4_name3_name2 : integer := 2;
15453    name2_name3_name4 : Boolean;
15454    name1_var : Float;
15455 begin
15456    name2_name3_name4 := name4_name3_name2 > name1;
15457 end;
15458 @end cartouche
15459 @end smallexample
15461 @noindent
15462 And suppose we have two dictionaries:
15464 @smallexample
15465 @cartouche
15466 @i{dict1:}
15467    NAME1
15468    *NaMe3*
15469    *NAME2
15470 @end cartouche
15472 @cartouche
15473 @i{dict2:}
15474   *NAME3*
15475 @end cartouche
15476 @end smallexample
15478 @noindent
15479 If @command{gnatpp} is called with the following switches:
15481 @smallexample
15482 @ifclear vms
15483 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15484 @end ifclear
15485 @ifset vms
15486 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15487 @end ifset
15488 @end smallexample
15490 @noindent
15491 then we will get the following name casing in the @command{gnatpp} output:
15493 @smallexample @c ada
15494 @cartouche
15495 procedure Test is
15496    NAME1             : Integer := 1;
15497    Name4_NAME3_NAME2 : integer := 2;
15498    Name2_NAME3_Name4 : Boolean;
15499    Name1_Var         : Float;
15500 begin
15501    Name2_NAME3_Name4 := Name4_NAME3_NAME2 > NAME1;
15502 end Test;
15503 @end cartouche
15504 @end smallexample
15506 @c *********************************
15507 @node The GNAT Metric Tool gnatmetric
15508 @chapter The GNAT Metric Tool @command{gnatmetric}
15509 @findex gnatmetric
15510 @cindex Metric tool
15512 @noindent
15513 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15514 for computing various program metrics.
15515 It takes an Ada source file as input and generates a file containing the
15516 metrics data as output. Various switches control which
15517 metrics are computed and output.
15519 @command{gnatmetric} generates and uses the ASIS
15520 tree for the input source and thus requires the input to be syntactically and
15521 semantically legal.
15522 If this condition is not met, @command{gnatmetric} will generate
15523 an error message; no metric information for this file will be
15524 computed and reported.
15526 If the compilation unit contained in the input source depends semantically
15527 upon units in files located outside the current directory, you have to provide
15528 the source search path when invoking @command{gnatmetric}.
15529 If it depends semantically upon units that are contained
15530 in files with names that do not follow the GNAT file naming rules, you have to
15531 provide the configuration file describing the corresponding naming scheme; see
15532 the description of the @command{gnatmetric} switches below.
15533 Alternatively, you may use a project file and invoke @command{gnatmetric}
15534 through the @command{gnat} driver.
15537 The @command{gnatmetric} command has the form
15539 @smallexample
15540 $ gnatmetric [@i{switches}] @{@i{filename}@} [@i{-cargs gcc_switches}]
15541 @end smallexample
15543 @noindent
15544 where
15545 @itemize @bullet
15546 @item
15547 @i{switches} specify the metrics to compute and define the destination for
15548 the output
15550 @item
15551 Each @i{filename} is the name (including the extension) of a source
15552 file to process. ``Wildcards'' are allowed, and
15553 the file name may contain path information.
15554 If no @i{filename} is supplied, then the @i{switches} list must contain
15555 at least one
15556 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15557 Including both a @option{-files} switch and one or more
15558 @i{filename} arguments is permitted.
15560 @item
15561 @i{-cargs gcc_switches} is a list of switches for
15562 @command{gcc}. They will be passed on to all compiler invocations made by
15563 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15564 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15565 and use the @option{-gnatec} switch to set the configuration file.
15566 @end itemize
15568 @menu
15569 * Switches for gnatmetric::
15570 @end menu
15572 @node Switches for gnatmetric
15573 @section Switches for @command{gnatmetric}
15575 @noindent
15576 The following subsections describe the various switches accepted by
15577 @command{gnatmetric}, organized by category.
15579 @menu
15580 * Output Files Control::
15581 * Disable Metrics For Local Units::
15582 * Line Metrics Control::
15583 * Syntax Metrics Control::
15584 * Complexity Metrics Control::
15585 * Other gnatmetric Switches::
15586 @end menu
15588 @node Output Files Control
15589 @subsection Output File Control
15590 @cindex Output file control in @command{gnatmetric}
15592 @noindent
15593 @command{gnatmetric} has two output formats. It can generate a
15594 textual (human-readable) form, and also XML. By default only textual
15595 output is generated.
15597 When generating the output in textual form, @command{gnatmetric} creates
15598 for each Ada source file a corresponding text file
15599 containing the computed metrics. By default, this file
15600 is placed in the same directory as where the source file is located, and
15601 its name is obtained
15602 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15603 input file.
15605 All the output information generated in XML format is placed in a single
15606 file. By default this file is placed in the current directory and has the
15607 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15609 Some of the computed metrics are summed over the units passed to
15610 @command{gnatmetric}; for example, the total number of lines of code.
15611 By default this information is sent to @file{stdout}, but a file
15612 can be specified with the @option{-og} switch.
15614 The following switches control the @command{gnatmetric} output:
15616 @table @option
15617 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15618 @item ^-x^/XML^
15619 Generate the XML output
15621 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15622 @item ^-nt^/NO_TEXT^
15623 Do not generate the output in text form (implies @option{^-x^/XML^})
15625 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15626 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15627 Put textual files with detailed metrics into @var{output_dir}
15629 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15630 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15631 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15632 in the name of the output file.
15634 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15635 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15636 Put global metrics into @var{file_name}
15638 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15639 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15640 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15642 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15643 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15644 Use ``short'' source file names in the output.  (The @command{gnatmetric}
15645 output includes the name(s) of the Ada source file(s) from which the metrics
15646 are computed.  By default each name includes the absolute path. The
15647 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15648 to exclude all directory information from the file names that are output.)
15650 @end table
15652 @node Disable Metrics For Local Units
15653 @subsection Disable Metrics For Local Units
15654 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15656 @noindent
15657 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15658 one compilation
15659 unit per one source file. It computes line metrics for the whole source
15660 file, and it also computes syntax
15661 and complexity metrics for the file's outermost unit.
15663 By default, @command{gnatmetric} will also compute all metrics for certain
15664 kinds of locally declared program units:
15666 @itemize @bullet
15667 @item
15668 subprogram (and generic subprogram) bodies;
15670 @item
15671 package (and generic package) specifications and bodies;
15673 @item
15674 task object and type specifications and bodies;
15676 @item
15677 protected object and type specifications and bodies.
15678 @end itemize
15680 @noindent
15681 These kinds of entities will be referred to as
15682 @emph{eligible local program units}, or simply @emph{eligible local units},
15683 @cindex Eligible local unit (for @command{gnatmetric})
15684 in the discussion below.
15686 Note that a subprogram declaration, generic instantiation,
15687 or renaming declaration only receives metrics
15688 computation when it appear as the outermost entity
15689 in a source file.
15691 Suppression of metrics computation for eligible local units can be
15692 obtained via the following switch:
15694 @table @option
15695 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15696 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15697 Do not compute detailed metrics for eligible local program units
15699 @end table
15701 @node Line Metrics Control
15702 @subsection Line Metrics Control
15703 @cindex Line metrics control in @command{gnatmetric}
15705 @noindent
15706 For any (legal) source file, and for each of its
15707 eligible local program units, @command{gnatmetric} computes the following
15708 metrics:
15710 @itemize @bullet
15711 @item
15712 the total number of lines;
15714 @item
15715 the total number of code lines (i.e., non-blank lines that are not comments)
15717 @item
15718 the number of comment lines
15720 @item
15721 the number of code lines containing end-of-line comments;
15723 @item
15724 the number of empty lines and lines containing only space characters and/or
15725 format effectors (blank lines)
15727 @end itemize
15729 If @command{gnatmetric} is invoked on more than one source file, it sums the
15730 values of the line metrics for all the files being processed and then
15731 generates the cumulative results.
15733 By default, all the line metrics are computed and reported. You can use the
15734 following switches to select the specific line metrics to be computed and
15735 reported (if any of these parameters is set, only explicitly specified line
15736 metrics are computed).
15738 @table @option
15739 @cindex @option{^-la^/LINES_ALL^} (@command{gnatmetric})
15740 @item ^-la^/LINES_ALL^
15741 The number of all lines
15743 @cindex @option{^-lcode^/CODE_LINES^} (@command{gnatmetric})
15744 @item ^-lcode^/CODE_LINES^
15745 The number of code lines
15747 @cindex @option{^-lcomm^/COMENT_LINES^} (@command{gnatmetric})
15748 @item ^-lcomm^/COMENT_LINES^
15749 The number of comment lines
15751 @cindex @option{^-leol^/MIXED_CODE_COMMENTS^} (@command{gnatmetric})
15752 @item ^-leol^/MIXED_CODE_COMMENTS^
15753 The number of code lines containing
15754 end-of-line comments
15756 @cindex @option{^-lb^/BLANK_LINES^} (@command{gnatmetric})
15757 @item ^-lb^/BLANK_LINES^
15758 The number of blank lines
15760 @end table
15763 @node Syntax Metrics Control
15764 @subsection Syntax Metrics Control
15765 @cindex Syntax metrics control in @command{gnatmetric}
15767 @noindent
15768 @command{gnatmetric} computes various syntactic metrics for the
15769 outermost unit and for each eligible local unit:
15771 @table @emph
15772 @item LSLOC (``Logical Source Lines Of Code'')
15773 The total number of declarations and the total number of statements
15775 @item Maximal static nesting level of inner program units
15776 According to
15777 @cite{Ada 95 Language Reference Manual}, 10.1(1), ``A program unit is either a
15778 package, a task unit, a protected unit, a
15779 protected entry, a generic unit, or an explicitly declared subprogram other
15780 than an enumeration literal.''
15782 @item Maximal nesting level of composite syntactic constructs
15783 This corresponds to the notion of the
15784 maximum nesting level in the GNAT built-in style checks
15785 (@pxref{Style Checking})
15786 @end table
15788 @noindent
15789 For the outermost unit in the file, @command{gnatmetric} additionally computes
15790 the following metrics:
15792 @table @emph
15793 @item Public subprograms
15794 This metric is computed for package specifications. It is the
15795 number of subprograms and generic subprograms declared in the visible
15796 part (including in nested packages, protected objects, and
15797 protected types).
15799 @item All subprograms
15800 This metric is computed for bodies and subunits. The
15801 metric is equal to a total number of subprogram bodies in the compilation
15802 unit.
15803 Neither generic instantiations nor renamings-as-a-body nor body stubs
15804 are counted. Any subprogram body is counted, independently of its nesting
15805 level and enclosing constructs. Generic bodies and bodies of protected
15806 subprograms are counted in the same way as ``usual'' subprogram bodies.
15808 @item Public types
15809 This metric is computed for package specifications and
15810 generic package declarations. It is the total number of types
15811 that can be referenced from outside this compilation unit, plus the
15812 number of types from all the visible parts of all the visible generic packages.
15813 Generic formal types are not counted.  Only types, not subtypes,
15814 are included.
15816 @noindent
15817 Along with the total number of public types, the following
15818 types are counted and reported separately:
15820 @itemize @bullet
15821 @item
15822 Abstract types
15824 @item
15825 Root tagged types (abstract, non-abstract, private, non-private). Type
15826 extensions are @emph{not} counted
15828 @item
15829 Private types (including private extensions)
15831 @item
15832 Task types
15834 @item
15835 Protected types
15837 @end itemize
15839 @item All types
15840 This metric is computed for any compilation unit. It is equal to the total
15841 number of the declarations of different types given in the compilation unit.
15842 The private and the corresponding full type declaration are counted as one
15843 type declaration. Incomplete type declarations and generic formal types
15844 are not counted.
15845 No distinction is made among different kinds of types (abstract,
15846 private etc.); the total number of types is computed and reported.
15848 @end table
15850 @noindent
15851 By default, all the syntax metrics are computed and reported. You can use the
15852 following switches to select specific syntax metrics;
15853 if any of these is set, only the explicitly specified metrics are computed.
15855 @table @option
15856 @cindex @option{^-ed^/DECLARATION_TOTAL^} (@command{gnatmetric})
15857 @item ^-ed^/DECLARATION_TOTAL^
15858 The total number of declarations
15860 @cindex @option{^-es^/STATEMENT_TOTAL^} (@command{gnatmetric})
15861 @item ^-es^/STATEMENT_TOTAL^
15862 The total number of statements
15864 @cindex @option{^-eps^/^} (@command{gnatmetric})
15865 @item ^-eps^/INT_SUBPROGRAMS^
15866 The number of public subprograms in a compilation unit
15868 @cindex @option{^-eas^/SUBPROGRAMS_ALL^} (@command{gnatmetric})
15869 @item ^-eas^/SUBPROGRAMS_ALL^
15870 The number of all the subprograms in a compilation unit
15872 @cindex @option{^-ept^/INT_TYPES^} (@command{gnatmetric})
15873 @item ^-ept^/INT_TYPES^
15874 The number of public types in a compilation unit
15876 @cindex @option{^-eat^/TYPES_ALL^} (@command{gnatmetric})
15877 @item ^-eat^/TYPES_ALL^
15878 The number of all the types in a compilation unit
15880 @cindex @option{^-enu^/PROGRAM_NESTING_MAX^} (@command{gnatmetric})
15881 @item ^-enu^/PROGRAM_NESTING_MAX^
15882 The maximal program unit nesting level
15884 @cindex @option{^-ec^/CONSTRUCT_NESTING_MAX^} (@command{gnatmetric})
15885 @item ^-ec^/CONSTRUCT_NESTING_MAX^
15886 The maximal construct nesting level
15888 @end table
15890 @node Complexity Metrics Control
15891 @subsection Complexity Metrics Control
15892 @cindex Complexity metrics control in @command{gnatmetric}
15894 @noindent
15895 For a program unit that is an executable body (a subprogram body (including
15896 generic bodies), task body, entry body or a package body containing
15897 its own statement sequence ) @command{gnatmetric} computes the following
15898 complexity metrics:
15900 @itemize @bullet
15901 @item
15902 McCabe cyclomatic complexity;
15904 @item
15905 McCabe essential complexity;
15907 @item
15908 maximal loop nesting level
15910 @end itemize
15912 @noindent
15913 The McCabe complexity metrics are defined
15914 in @url{www.mccabe.com/pdf/nist235r.pdf}
15916 According to McCabe, both control statements and short-circuit control forms
15917 should be taken into account when computing cyclomatic complexity. For each
15918 body, we compute three metric values:
15920 @itemize @bullet
15921 @item
15922 the complexity introduced by control
15923 statements only, without taking into account short-circuit forms,
15925 @item
15926 the complexity introduced by short-circuit control forms only, and
15928 @item
15929 the total
15930 cyclomatic complexity, which is the sum of these two values.
15931 @end itemize
15933 @noindent
15934 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15935 the code in the exception handlers and in all the nested program units.
15937 By default, all the complexity metrics are computed and reported.
15938 For more finely-grained control you can use
15939 the following switches:
15941 @table @option
15942 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15944 @item ^-nocc^/SUPPRESS=CYCLOMATIC_COMPLEXITY^
15945 Do not compute the McCabe Cyclomatic Complexity
15947 @item ^-noec^/SUPPRESS=ESSENTIAL_COMPLEXITY^
15948 Do not compute the Essential Complexity
15950 @item ^-nonl^/SUPPRESS=MAXIMAL_LOOP_NESTING^
15951 Do not compute maximal loop nesting level
15953 @item ^-ne^/SUPPRESS=EXITS_AS_GOTOS^
15954 Do not consider @code{exit} statements as @code{goto}s when
15955 computing Essential Complexity
15957 @end table
15959 @node Other gnatmetric Switches
15960 @subsection Other @code{gnatmetric} Switches
15962 @noindent
15963 Additional @command{gnatmetric} switches are as follows:
15965 @table @option
15966 @item ^-files @var{filename}^/FILES=@var{filename}^
15967 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
15968 Take the argument source files from the specified file. This file should be an
15969 ordinary textual file containing file names separated by spaces or
15970 line breaks. You can use this switch more then once in the same call to
15971 @command{gnatmetric}. You also can combine this switch with
15972 an explicit list of files.
15974 @item ^-v^/VERBOSE^
15975 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
15976 Verbose mode;
15977 @command{gnatmetric} generates version information and then
15978 a trace of sources being procesed.
15980 @item ^-dv^/DEBUG_OUTPUT^
15981 @cindex @option{^-dv^/DEBUG_OUTPUT^} (@code{gnatmetric})
15982 Debug mode;
15983 @command{gnatmetric} generates various messages useful to understand what
15984 happens during the metrics computation
15986 @item ^-q^/QUIET^
15987 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
15988 Quiet mode.
15989 @end table
15991 @c ***********************************
15992 @node File Name Krunching Using gnatkr
15993 @chapter File Name Krunching Using @code{gnatkr}
15994 @findex gnatkr
15996 @noindent
15997 This chapter discusses the method used by the compiler to shorten
15998 the default file names chosen for Ada units so that they do not
15999 exceed the maximum length permitted. It also describes the
16000 @code{gnatkr} utility that can be used to determine the result of
16001 applying this shortening.
16002 @menu
16003 * About gnatkr::
16004 * Using gnatkr::
16005 * Krunching Method::
16006 * Examples of gnatkr Usage::
16007 @end menu
16009 @node About gnatkr
16010 @section About @code{gnatkr}
16012 @noindent
16013 The default file naming rule in GNAT
16014 is that the file name must be derived from
16015 the unit name. The exact default rule is as follows:
16016 @itemize @bullet
16017 @item
16018 Take the unit name and replace all dots by hyphens.
16019 @item
16020 If such a replacement occurs in the
16021 second character position of a name, and the first character is
16022 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
16023 ^~ (tilde)^$ (dollar sign)^
16024 instead of a minus.
16025 @end itemize
16026 The reason for this exception is to avoid clashes
16027 with the standard names for children of System, Ada, Interfaces,
16028 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
16029 respectively.
16031 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16032 switch of the compiler activates a ``krunching''
16033 circuit that limits file names to nn characters (where nn is a decimal
16034 integer). For example, using OpenVMS,
16035 where the maximum file name length is
16036 39, the value of nn is usually set to 39, but if you want to generate
16037 a set of files that would be usable if ported to a system with some
16038 different maximum file length, then a different value can be specified.
16039 The default value of 39 for OpenVMS need not be specified.
16041 The @code{gnatkr} utility can be used to determine the krunched name for
16042 a given file, when krunched to a specified maximum length.
16044 @node Using gnatkr
16045 @section Using @code{gnatkr}
16047 @noindent
16048 The @code{gnatkr} command has the form
16050 @ifclear vms
16051 @smallexample
16052 $ gnatkr @var{name} [@var{length}]
16053 @end smallexample
16054 @end ifclear
16056 @ifset vms
16057 @smallexample
16058 $ gnatkr @var{name} /COUNT=nn
16059 @end smallexample
16060 @end ifset
16062 @noindent
16063 @var{name} is the uncrunched file name, derived from the name of the unit
16064 in the standard manner described in the previous section (i.e. in particular
16065 all dots are replaced by hyphens). The file name may or may not have an
16066 extension (defined as a suffix of the form period followed by arbitrary
16067 characters other than period). If an extension is present then it will
16068 be preserved in the output. For example, when krunching @file{hellofile.ads}
16069 to eight characters, the result will be hellofil.ads.
16071 Note: for compatibility with previous versions of @code{gnatkr} dots may
16072 appear in the name instead of hyphens, but the last dot will always be
16073 taken as the start of an extension. So if @code{gnatkr} is given an argument
16074 such as @file{Hello.World.adb} it will be treated exactly as if the first
16075 period had been a hyphen, and for example krunching to eight characters
16076 gives the result @file{hellworl.adb}.
16078 Note that the result is always all lower case (except on OpenVMS where it is
16079 all upper case). Characters of the other case are folded as required.
16081 @var{length} represents the length of the krunched name. The default
16082 when no argument is given is ^8^39^ characters. A length of zero stands for
16083 unlimited, in other words do not chop except for system files where the
16084 impled crunching length is always eight characters.
16086 @noindent
16087 The output is the krunched name. The output has an extension only if the
16088 original argument was a file name with an extension.
16090 @node Krunching Method
16091 @section Krunching Method
16093 @noindent
16094 The initial file name is determined by the name of the unit that the file
16095 contains. The name is formed by taking the full expanded name of the
16096 unit and replacing the separating dots with hyphens and
16097 using ^lowercase^uppercase^
16098 for all letters, except that a hyphen in the second character position is
16099 replaced by a ^tilde^dollar sign^ if the first character is
16100 ^a, i, g, or s^A, I, G, or S^.
16101 The extension is @code{.ads} for a
16102 specification and @code{.adb} for a body.
16103 Krunching does not affect the extension, but the file name is shortened to
16104 the specified length by following these rules:
16106 @itemize @bullet
16107 @item
16108 The name is divided into segments separated by hyphens, tildes or
16109 underscores and all hyphens, tildes, and underscores are
16110 eliminated. If this leaves the name short enough, we are done.
16112 @item
16113 If the name is too long, the longest segment is located (left-most
16114 if there are two of equal length), and shortened by dropping
16115 its last character. This is repeated until the name is short enough.
16117 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16118 to fit the name into 8 characters as required by some operating systems.
16120 @smallexample
16121 our-strings-wide_fixed 22
16122 our strings wide fixed 19
16123 our string  wide fixed 18
16124 our strin   wide fixed 17
16125 our stri    wide fixed 16
16126 our stri    wide fixe  15
16127 our str     wide fixe  14
16128 our str     wid  fixe  13
16129 our str     wid  fix   12
16130 ou  str     wid  fix   11
16131 ou  st      wid  fix   10
16132 ou  st      wi   fix   9
16133 ou  st      wi   fi    8
16134 Final file name: oustwifi.adb
16135 @end smallexample
16137 @item
16138 The file names for all predefined units are always krunched to eight
16139 characters. The krunching of these predefined units uses the following
16140 special prefix replacements:
16142 @table @file
16143 @item ada-
16144 replaced by @file{^a^A^-}
16146 @item gnat-
16147 replaced by @file{^g^G^-}
16149 @item interfaces-
16150 replaced by @file{^i^I^-}
16152 @item system-
16153 replaced by @file{^s^S^-}
16154 @end table
16156 These system files have a hyphen in the second character position. That
16157 is why normal user files replace such a character with a
16158 ^tilde^dollar sign^, to
16159 avoid confusion with system file names.
16161 As an example of this special rule, consider
16162 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16164 @smallexample
16165 ada-strings-wide_fixed 22
16166 a-  strings wide fixed 18
16167 a-  string  wide fixed 17
16168 a-  strin   wide fixed 16
16169 a-  stri    wide fixed 15
16170 a-  stri    wide fixe  14
16171 a-  str     wide fixe  13
16172 a-  str     wid  fixe  12
16173 a-  str     wid  fix   11
16174 a-  st      wid  fix   10
16175 a-  st      wi   fix   9
16176 a-  st      wi   fi    8
16177 Final file name: a-stwifi.adb
16178 @end smallexample
16179 @end itemize
16181 Of course no file shortening algorithm can guarantee uniqueness over all
16182 possible unit names, and if file name krunching is used then it is your
16183 responsibility to ensure that no name clashes occur. The utility
16184 program @code{gnatkr} is supplied for conveniently determining the
16185 krunched name of a file.
16187 @node Examples of gnatkr Usage
16188 @section Examples of @code{gnatkr} Usage
16190 @smallexample
16191 @iftex
16192 @leftskip=0cm
16193 @end iftex
16194 @ifclear vms
16195 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16196 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16197 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16198 $ gnatkr grandparent-parent-child     --> grparchi
16199 @end ifclear
16200 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16201 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16202 @end smallexample
16204 @node Preprocessing Using gnatprep
16205 @chapter Preprocessing Using @code{gnatprep}
16206 @findex gnatprep
16208 @noindent
16209 The @code{gnatprep} utility provides
16210 a simple preprocessing capability for Ada programs.
16211 It is designed for use with GNAT, but is not dependent on any special
16212 features of GNAT.
16214 @menu
16215 * Using gnatprep::
16216 * Switches for gnatprep::
16217 * Form of Definitions File::
16218 * Form of Input Text for gnatprep::
16219 @end menu
16221 @node Using gnatprep
16222 @section Using @code{gnatprep}
16224 @noindent
16225 To call @code{gnatprep} use
16227 @smallexample
16228 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
16229 @end smallexample
16231 @noindent
16232 where
16233 @table @code
16234 @item infile
16235 is the full name of the input file, which is an Ada source
16236 file containing preprocessor directives.
16238 @item outfile
16239 is the full name of the output file, which is an Ada source
16240 in standard Ada form. When used with GNAT, this file name will
16241 normally have an ads or adb suffix.
16243 @item deffile
16244 is the full name of a text file containing definitions of
16245 symbols to be referenced by the preprocessor. This argument is
16246 optional, and can be replaced by the use of the @option{-D} switch.
16248 @item switches
16249 is an optional sequence of switches as described in the next section.
16250 @end table
16252 @node Switches for gnatprep
16253 @section Switches for @code{gnatprep}
16255 @table @option
16256 @c !sort!
16258 @item ^-b^/BLANK_LINES^
16259 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16260 Causes both preprocessor lines and the lines deleted by
16261 preprocessing to be replaced by blank lines in the output source file,
16262 preserving line numbers in the output file.
16264 @item ^-c^/COMMENTS^
16265 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16266 Causes both preprocessor lines and the lines deleted
16267 by preprocessing to be retained in the output source as comments marked
16268 with the special string @code{"--! "}. This option will result in line numbers
16269 being preserved in the output file.
16271 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16272 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16273 Defines a new symbol, associated with value. If no value is given on the
16274 command line, then symbol is considered to be @code{True}. This switch
16275 can be used in place of a definition file.
16277 @ifset vms
16278 @item /REMOVE
16279 @cindex @option{/REMOVE} (@command{gnatprep})
16280 This is the default setting which causes lines deleted by preprocessing
16281 to be entirely removed from the output file.
16282 @end ifset
16284 @item ^-r^/REFERENCE^
16285 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16286 Causes a @code{Source_Reference} pragma to be generated that
16287 references the original input file, so that error messages will use
16288 the file name of this original file. The use of this switch implies
16289 that preprocessor lines are not to be removed from the file, so its
16290 use will force @option{^-b^/BLANK_LINES^} mode if
16291 @option{^-c^/COMMENTS^}
16292 has not been specified explicitly.
16294 Note that if the file to be preprocessed contains multiple units, then
16295 it will be necessary to @code{gnatchop} the output file from
16296 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16297 in the preprocessed file, it will be respected by
16298 @code{gnatchop ^-r^/REFERENCE^}
16299 so that the final chopped files will correctly refer to the original
16300 input source file for @code{gnatprep}.
16302 @item ^-s^/SYMBOLS^
16303 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16304 Causes a sorted list of symbol names and values to be
16305 listed on the standard output file.
16307 @item ^-u^/UNDEFINED^
16308 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16309 Causes undefined symbols to be treated as having the value FALSE in the context
16310 of a preprocessor test. In the absence of this option, an undefined symbol in
16311 a @code{#if} or @code{#elsif} test will be treated as an error.
16313 @end table
16315 @ifclear vms
16316 @noindent
16317 Note: if neither @option{-b} nor @option{-c} is present,
16318 then preprocessor lines and
16319 deleted lines are completely removed from the output, unless -r is
16320 specified, in which case -b is assumed.
16321 @end ifclear
16323 @node Form of Definitions File
16324 @section Form of Definitions File
16326 @noindent
16327 The definitions file contains lines of the form
16329 @smallexample
16330 symbol := value
16331 @end smallexample
16333 @noindent
16334 where symbol is an identifier, following normal Ada (case-insensitive)
16335 rules for its syntax, and value is one of the following:
16337 @itemize @bullet
16338 @item
16339 Empty, corresponding to a null substitution
16340 @item
16341 A string literal using normal Ada syntax
16342 @item
16343 Any sequence of characters from the set
16344 (letters, digits, period, underline).
16345 @end itemize
16347 @noindent
16348 Comment lines may also appear in the definitions file, starting with
16349 the usual @code{--},
16350 and comments may be added to the definitions lines.
16352 @node Form of Input Text for gnatprep
16353 @section Form of Input Text for @code{gnatprep}
16355 @noindent
16356 The input text may contain preprocessor conditional inclusion lines,
16357 as well as general symbol substitution sequences.
16359 The preprocessor conditional inclusion commands have the form
16361 @smallexample
16362 @group
16363 @cartouche
16364 #if @i{expression} [then]
16365    lines
16366 #elsif @i{expression} [then]
16367    lines
16368 #elsif @i{expression} [then]
16369    lines
16371 #else
16372    lines
16373 #end if;
16374 @end cartouche
16375 @end group
16376 @end smallexample
16378 @noindent
16379 In this example, @i{expression} is defined by the following grammar:
16380 @smallexample
16381 @i{expression} ::=  <symbol>
16382 @i{expression} ::=  <symbol> = "<value>"
16383 @i{expression} ::=  <symbol> = <symbol>
16384 @i{expression} ::=  <symbol> 'Defined
16385 @i{expression} ::=  not @i{expression}
16386 @i{expression} ::=  @i{expression} and @i{expression}
16387 @i{expression} ::=  @i{expression} or @i{expression}
16388 @i{expression} ::=  @i{expression} and then @i{expression}
16389 @i{expression} ::=  @i{expression} or else @i{expression}
16390 @i{expression} ::=  ( @i{expression} )
16391 @end smallexample
16393 @noindent
16394 For the first test (@i{expression} ::= <symbol>) the symbol must have
16395 either the value true or false, that is to say the right-hand of the
16396 symbol definition must be one of the (case-insensitive) literals
16397 @code{True} or @code{False}. If the value is true, then the
16398 corresponding lines are included, and if the value is false, they are
16399 excluded.
16401 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16402 the symbol has been defined in the definition file or by a @option{-D}
16403 switch on the command line. Otherwise, the test is false.
16405 The equality tests are case insensitive, as are all the preprocessor lines.
16407 If the symbol referenced is not defined in the symbol definitions file,
16408 then the effect depends on whether or not switch @option{-u}
16409 is specified. If so, then the symbol is treated as if it had the value
16410 false and the test fails. If this switch is not specified, then
16411 it is an error to reference an undefined symbol. It is also an error to
16412 reference a symbol that is defined with a value other than @code{True}
16413 or @code{False}.
16415 The use of the @code{not} operator inverts the sense of this logical test, so
16416 that the lines are included only if the symbol is not defined.
16417 The @code{then} keyword is optional as shown
16419 The @code{#} must be the first non-blank character on a line, but
16420 otherwise the format is free form. Spaces or tabs may appear between
16421 the @code{#} and the keyword. The keywords and the symbols are case
16422 insensitive as in normal Ada code. Comments may be used on a
16423 preprocessor line, but other than that, no other tokens may appear on a
16424 preprocessor line. Any number of @code{elsif} clauses can be present,
16425 including none at all. The @code{else} is optional, as in Ada.
16427 The @code{#} marking the start of a preprocessor line must be the first
16428 non-blank character on the line, i.e. it must be preceded only by
16429 spaces or horizontal tabs.
16431 Symbol substitution outside of preprocessor lines is obtained by using
16432 the sequence
16434 @smallexample
16435 $symbol
16436 @end smallexample
16438 @noindent
16439 anywhere within a source line, except in a comment or within a
16440 string literal. The identifier
16441 following the @code{$} must match one of the symbols defined in the symbol
16442 definition file, and the result is to substitute the value of the
16443 symbol in place of @code{$symbol} in the output file.
16445 Note that although the substitution of strings within a string literal
16446 is not possible, it is possible to have a symbol whose defined value is
16447 a string literal. So instead of setting XYZ to @code{hello} and writing:
16449 @smallexample
16450 Header : String := "$XYZ";
16451 @end smallexample
16453 @noindent
16454 you should set XYZ to @code{"hello"} and write:
16456 @smallexample
16457 Header : String := $XYZ;
16458 @end smallexample
16460 @noindent
16461 and then the substitution will occur as desired.
16463 @ifset vms
16464 @node The GNAT Run-Time Library Builder gnatlbr
16465 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
16466 @findex gnatlbr
16467 @cindex Library builder
16469 @noindent
16470 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
16471 supplied configuration pragmas.
16473 @menu
16474 * Running gnatlbr::
16475 * Switches for gnatlbr::
16476 * Examples of gnatlbr Usage::
16477 @end menu
16479 @node Running gnatlbr
16480 @section Running @code{gnatlbr}
16482 @noindent
16483 The @code{gnatlbr} command has the form
16485 @smallexample
16486 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
16487 @end smallexample
16489 @node Switches for gnatlbr
16490 @section Switches for @code{gnatlbr}
16492 @noindent
16493 @code{gnatlbr} recognizes the following switches:
16495 @table @option
16496 @c !sort!
16497 @item /CREATE=directory
16498 @cindex @code{/CREATE} (@code{gnatlbr})
16499      Create the new run-time library in the specified directory.
16501 @item /SET=directory
16502 @cindex @code{/SET} (@code{gnatlbr})
16503      Make the library in the specified directory the current run-time
16504      library.
16506 @item /DELETE=directory
16507 @cindex @code{/DELETE} (@code{gnatlbr})
16508      Delete the run-time library in the specified directory.
16510 @item /CONFIG=file
16511 @cindex @code{/CONFIG} (@code{gnatlbr})
16512      With /CREATE:
16513      Use the configuration pragmas in the specified file when building
16514      the library.
16516      With /SET:
16517      Use the configuration pragmas in the specified file when compiling.
16519 @end table
16521 @node Examples of gnatlbr Usage
16522 @section Example of @code{gnatlbr} Usage
16524 @smallexample
16525 Contents of VAXFLOAT.ADC:
16526 pragma Float_Representation (VAX_Float);
16528 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
16530 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
16532 @end smallexample
16533 @end ifset
16535 @node The GNAT Library Browser gnatls
16536 @chapter The GNAT Library Browser @code{gnatls}
16537 @findex gnatls
16538 @cindex Library browser
16540 @noindent
16541 @code{gnatls} is a tool that outputs information about compiled
16542 units. It gives the relationship between objects, unit names and source
16543 files. It can also be used to check the source dependencies of a unit
16544 as well as various characteristics.
16546 @menu
16547 * Running gnatls::
16548 * Switches for gnatls::
16549 * Examples of gnatls Usage::
16550 @end menu
16552 @node Running gnatls
16553 @section Running @code{gnatls}
16555 @noindent
16556 The @code{gnatls} command has the form
16558 @smallexample
16559 $ gnatls switches @var{object_or_ali_file}
16560 @end smallexample
16562 @noindent
16563 The main argument is the list of object or @file{ali} files
16564 (@pxref{The Ada Library Information Files})
16565 for which information is requested.
16567 In normal mode, without additional option, @code{gnatls} produces a
16568 four-column listing. Each line represents information for a specific
16569 object. The first column gives the full path of the object, the second
16570 column gives the name of the principal unit in this object, the third
16571 column gives the status of the source and the fourth column gives the
16572 full path of the source representing this unit.
16573 Here is a simple example of use:
16575 @smallexample
16576 $ gnatls *.o
16577 ^./^[]^demo1.o            demo1            DIF demo1.adb
16578 ^./^[]^demo2.o            demo2             OK demo2.adb
16579 ^./^[]^hello.o            h1                OK hello.adb
16580 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
16581 ^./^[]^instr.o            instr             OK instr.adb
16582 ^./^[]^tef.o              tef              DIF tef.adb
16583 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
16584 ^./^[]^tgef.o             tgef             DIF tgef.adb
16585 @end smallexample
16587 @noindent
16588 The first line can be interpreted as follows: the main unit which is
16589 contained in
16590 object file @file{demo1.o} is demo1, whose main source is in
16591 @file{demo1.adb}. Furthermore, the version of the source used for the
16592 compilation of demo1 has been modified (DIF). Each source file has a status
16593 qualifier which can be:
16595 @table @code
16596 @item OK (unchanged)
16597 The version of the source file used for the compilation of the
16598 specified unit corresponds exactly to the actual source file.
16600 @item MOK (slightly modified)
16601 The version of the source file used for the compilation of the
16602 specified unit differs from the actual source file but not enough to
16603 require recompilation. If you use gnatmake with the qualifier
16604 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16605 MOK will not be recompiled.
16607 @item DIF (modified)
16608 No version of the source found on the path corresponds to the source
16609 used to build this object.
16611 @item ??? (file not found)
16612 No source file was found for this unit.
16614 @item HID (hidden,  unchanged version not first on PATH)
16615 The version of the source that corresponds exactly to the source used
16616 for compilation has been found on the path but it is hidden by another
16617 version of the same source that has been modified.
16619 @end table
16621 @node Switches for gnatls
16622 @section Switches for @code{gnatls}
16624 @noindent
16625 @code{gnatls} recognizes the following switches:
16627 @table @option
16628 @c !sort!
16629 @item ^-a^/ALL_UNITS^
16630 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16631 Consider all units, including those of the predefined Ada library.
16632 Especially useful with @option{^-d^/DEPENDENCIES^}.
16634 @item ^-d^/DEPENDENCIES^
16635 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16636 List sources from which specified units depend on.
16638 @item ^-h^/OUTPUT=OPTIONS^
16639 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16640 Output the list of options.
16642 @item ^-o^/OUTPUT=OBJECTS^
16643 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16644 Only output information about object files.
16646 @item ^-s^/OUTPUT=SOURCES^
16647 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16648 Only output information about source files.
16650 @item ^-u^/OUTPUT=UNITS^
16651 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16652 Only output information about compilation units.
16654 @item ^-files^/FILES^=@var{file}
16655 @cindex @option{^-files^/FILES^} (@code{gnatls})
16656 Take as arguments the files listed in text file @var{file}.
16657 Text file @var{file} may contain empty lines that are ignored.
16658 Each non empty line should contain the name of an existing file.
16659 Several such switches may be specified simultaneously.
16661 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16662 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16663 @itemx ^-I^/SEARCH=^@var{dir}
16664 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
16665 @itemx -nostdinc
16666 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16667 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16668 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16669 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16670 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16671 flags (@pxref{Switches for gnatmake}).
16673 @item --RTS=@var{rts-path}
16674 @cindex @option{--RTS} (@code{gnatls})
16675 Specifies the default location of the runtime library. Same meaning as the
16676 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16678 @item ^-v^/OUTPUT=VERBOSE^
16679 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16680 Verbose mode. Output the complete source, object and project paths. Do not use
16681 the default column layout but instead use long format giving as much as
16682 information possible on each requested units, including special
16683 characteristics such as:
16685 @table @code
16686 @item  Preelaborable
16687 The unit is preelaborable in the Ada 95 sense.
16689 @item No_Elab_Code
16690 No elaboration code has been produced by the compiler for this unit.
16692 @item Pure
16693 The unit is pure in the Ada 95 sense.
16695 @item Elaborate_Body
16696 The unit contains a pragma Elaborate_Body.
16698 @item Remote_Types
16699 The unit contains a pragma Remote_Types.
16701 @item Shared_Passive
16702 The unit contains a pragma Shared_Passive.
16704 @item Predefined
16705 This unit is part of the predefined environment and cannot be modified
16706 by the user.
16708 @item Remote_Call_Interface
16709 The unit contains a pragma Remote_Call_Interface.
16711 @end table
16713 @end table
16715 @node Examples of gnatls Usage
16716 @section Example of @code{gnatls} Usage
16717 @ifclear vms
16719 @noindent
16720 Example of using the verbose switch. Note how the source and
16721 object paths are affected by the -I switch.
16723 @smallexample
16724 $ gnatls -v -I.. demo1.o
16726 GNATLS 5.03w (20041123-34)
16727 Copyright 1997-2004 Free Software Foundation, Inc.
16729 Source Search Path:
16730    <Current_Directory>
16731    ../
16732    /home/comar/local/adainclude/
16734 Object Search Path:
16735    <Current_Directory>
16736    ../
16737    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
16739 Project Search Path:
16740    <Current_Directory>
16741    /home/comar/local/lib/gnat/
16743 ./demo1.o
16744    Unit =>
16745      Name   => demo1
16746      Kind   => subprogram body
16747      Flags  => No_Elab_Code
16748      Source => demo1.adb    modified
16749 @end smallexample
16751 @noindent
16752 The following is an example of use of the dependency list.
16753 Note the use of the -s switch
16754 which gives a straight list of source files. This can be useful for
16755 building specialized scripts.
16757 @smallexample
16758 $ gnatls -d demo2.o
16759 ./demo2.o   demo2        OK demo2.adb
16760                          OK gen_list.ads
16761                          OK gen_list.adb
16762                          OK instr.ads
16763                          OK instr-child.ads
16765 $ gnatls -d -s -a demo1.o
16766 demo1.adb
16767 /home/comar/local/adainclude/ada.ads
16768 /home/comar/local/adainclude/a-finali.ads
16769 /home/comar/local/adainclude/a-filico.ads
16770 /home/comar/local/adainclude/a-stream.ads
16771 /home/comar/local/adainclude/a-tags.ads
16772 gen_list.ads
16773 gen_list.adb
16774 /home/comar/local/adainclude/gnat.ads
16775 /home/comar/local/adainclude/g-io.ads
16776 instr.ads
16777 /home/comar/local/adainclude/system.ads
16778 /home/comar/local/adainclude/s-exctab.ads
16779 /home/comar/local/adainclude/s-finimp.ads
16780 /home/comar/local/adainclude/s-finroo.ads
16781 /home/comar/local/adainclude/s-secsta.ads
16782 /home/comar/local/adainclude/s-stalib.ads
16783 /home/comar/local/adainclude/s-stoele.ads
16784 /home/comar/local/adainclude/s-stratt.ads
16785 /home/comar/local/adainclude/s-tasoli.ads
16786 /home/comar/local/adainclude/s-unstyp.ads
16787 /home/comar/local/adainclude/unchconv.ads
16788 @end smallexample
16789 @end ifclear
16791 @ifset vms
16792 @smallexample
16793 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
16795 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
16796 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
16797 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
16798 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
16799 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
16800 demo1.adb
16801 gen_list.ads
16802 gen_list.adb
16803 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
16804 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
16805 instr.ads
16806 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
16807 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
16808 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
16809 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
16810 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
16811 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
16812 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
16813 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
16814 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
16815 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
16816 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
16817 @end smallexample
16818 @end ifset
16820 @node Cleaning Up Using gnatclean
16821 @chapter Cleaning Up Using @code{gnatclean}
16822 @findex gnatclean
16823 @cindex Cleaning tool
16825 @noindent
16826 @code{gnatclean} is a tool that allows the deletion of files produced by the
16827 compiler, binder and linker, including ALI files, object files, tree files,
16828 expanded source files, library files, interface copy source files, binder
16829 generated files and executable files.
16831 @menu
16832 * Running gnatclean::
16833 * Switches for gnatclean::
16834 * Examples of gnatclean Usage::
16835 @end menu
16837 @node Running gnatclean
16838 @section Running @code{gnatclean}
16840 @noindent
16841 The @code{gnatclean} command has the form:
16843 @smallexample
16844 $ gnatclean switches @var{names}
16845 @end smallexample
16847 @noindent
16848 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
16849 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
16850 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
16852 @noindent
16853 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
16854 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
16855 the linker. In informative-only mode, specified by switch
16856 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
16857 normal mode is listed, but no file is actually deleted.
16859 @node Switches for gnatclean
16860 @section Switches for @code{gnatclean}
16862 @noindent
16863 @code{gnatclean} recognizes the following switches:
16865 @table @option
16866 @c !sort!
16867 @item ^-c^/COMPILER_FILES_ONLY^
16868 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
16869 Only attempt to delete the files produced by the compiler, not those produced
16870 by the binder or the linker. The files that are not to be deleted are library
16871 files, interface copy files, binder generated files and executable files.
16873 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
16874 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
16875 Indicate that ALI and object files should normally be found in directory
16876 @var{dir}.
16878 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
16879 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
16880 When using project files, if some errors or warnings are detected during
16881 parsing and verbose mode is not in effect (no use of switch
16882 ^-v^/VERBOSE^), then error lines start with the full path name of the project
16883 file, rather than its simple file name.
16885 @item ^-h^/HELP^
16886 @cindex @option{^-h^/HELP^} (@code{gnatclean})
16887 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
16889 @item ^-n^/NODELETE^
16890 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
16891 Informative-only mode. Do not delete any files. Output the list of the files
16892 that would have been deleted if this switch was not specified.
16894 @item ^-P^/PROJECT_FILE=^@var{project}
16895 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
16896 Use project file @var{project}. Only one such switch can be used.
16897 When cleaning a project file, the files produced by the compilation of the
16898 immediate sources or inherited sources of the project files are to be
16899 deleted. This is not depending on the presence or not of executable names
16900 on the command line.
16902 @item ^-q^/QUIET^
16903 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
16904 Quiet output. If there are no error, do not ouuput anything, except in
16905 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
16906 (switch ^-n^/NODELETE^).
16908 @item ^-r^/RECURSIVE^
16909 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
16910 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
16911 clean all imported and extended project files, recursively. If this switch
16912 is not specified, only the files related to the main project file are to be
16913 deleted. This switch has no effect if no project file is specified.
16915 @item ^-v^/VERBOSE^
16916 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
16917 Verbose mode.
16919 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
16920 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
16921 Indicates the verbosity of the parsing of GNAT project files.
16922 @xref{Switches Related to Project Files}.
16924 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
16925 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
16926 Indicates that external variable @var{name} has the value @var{value}.
16927 The Project Manager will use this value for occurrences of
16928 @code{external(name)} when parsing the project file.
16929 @xref{Switches Related to Project Files}.
16931 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16932 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
16933 When searching for ALI and object files, look in directory
16934 @var{dir}.
16936 @item ^-I^/SEARCH=^@var{dir}
16937 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
16938 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
16940 @item ^-I-^/NOCURRENT_DIRECTORY^
16941 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
16942 @cindex Source files, suppressing search
16943 Do not look for ALI or object files in the directory
16944 where @code{gnatclean} was invoked.
16946 @end table
16948 @node Examples of gnatclean Usage
16949 @section Examples of @code{gnatclean} Usage
16951 @ifclear vms
16952 @node GNAT and Libraries
16953 @chapter GNAT and Libraries
16954 @cindex Library, building, installing, using
16956 @noindent
16957 This chapter describes how to build and use libraries with GNAT, and also shows
16958 how to recompile the GNAT run-time library. You should be familiar with the
16959 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
16960 chapter.
16962 @menu
16963 * Introduction to Libraries in GNAT::
16964 * General Ada Libraries::
16965 * Stand-alone Ada Libraries::
16966 * Rebuilding the GNAT Run-Time Library::
16967 @end menu
16969 @node Introduction to Libraries in GNAT
16970 @section Introduction to Libraries in GNAT
16972 @noindent
16973 A library is, conceptually, a collection of objects which does not have its
16974 own main thread of execution, but rather provides certain services to the
16975 applications that use it. A library can be either statically linked with the
16976 application, in which case its code is directly included in the application,
16977 or, on platforms that support it, be dynamically linked, in which case
16978 its code is shared by all applications making use of this library.
16980 GNAT supports both types of libraries.
16981 In the static case, the compiled code can be provided in different ways. The
16982 simplest approach is to provide directly the set of objects resulting from
16983 compilation of the library source files. Alternatively, you can group the
16984 objects into an archive using whatever commands are provided by the operating
16985 system. For the latter case, the objects are grouped into a shared library.
16987 In the GNAT environment, a library has three types of components:
16988 @itemize @bullet
16989 @item
16990 Source files.
16991 @item
16992 @file{ALI} files.
16993 @xref{The Ada Library Information Files}.
16994 @item
16995 Object files, an archive or a shared library.
16996 @end itemize
16998 @noindent
16999 A GNAT library may expose all its source files, which is useful for
17000 documentation purposes. Alternatively, it may expose only the units needed by
17001 an external user to make use of the library. That is to say, the specs
17002 reflecting the library services along with all the units needed to compile
17003 those specs, which can include generic bodies or any body implementing an
17004 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17005 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17007 All compilation units comprising an application, including those in a library,
17008 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17009 computes the elaboration order from the @file{ALI} files and this is why they
17010 constitute a mandatory part of GNAT libraries. Except in the case of
17011 @emph{stand-alone libraries}, where a specific library elaboration routine is
17012 produced independently of the application(s) using the library.
17014 @node General Ada Libraries
17015 @section General Ada Libraries
17017 @menu
17018 * Building a library::
17019 * Installing a library::
17020 * Using a library::
17021 @end menu
17023 @node Building a library
17024 @subsection Building a library
17026 @noindent
17027 The easiest way to build a library is to use the Project Manager,
17028 which supports a special type of project called a @emph{Library Project}
17029 (@pxref{Library Projects}).
17031 A project is considered a library project, when two project-level attributes
17032 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17033 control different aspects of library configuration, additional optional
17034 project-level attributes can be specified:
17035 @table @code
17036 @item Library_Kind
17037 This attribute controls whether the library is to be static or dynamic
17039 @item Library_Version
17040 This attribute specifies the library version; this value is used
17041 during dynamic linking of shared libraries to determine if the currently
17042 installed versions of the binaries are compatible.
17044 @item Library_Options
17045 @item Library_GCC
17046 These attributes specify additional low-level options to be used during
17047 library generation, and redefine the actual application used to generate
17048 library.
17049 @end table
17051 @noindent
17052 The GNAT Project Manager takes full care of the library maintenance task,
17053 including recompilation of the source files for which objects do not exist
17054 or are not up to date, assembly of the library archive, and installation of
17055 the library (i.e., copying associated source, object and @file{ALI} files
17056 to the specified location).
17058 Here is a simple library project file:
17059 @smallexample @c ada
17060 project My_Lib is
17061    for Source_Dirs use ("src1", "src2");
17062    for Object_Dir use "obj";
17063    for Library_Name use "mylib";
17064    for Library_Dir use "lib";
17065    for Library_Kind use "dynamic";
17066 end My_lib;
17067 @end smallexample
17069 @noindent
17070 and the compilation command to build and install the library:
17072 @smallexample @c ada
17073   $ gnatmake -Pmy_lib
17074 @end smallexample
17076 @noindent
17077 It is not entirely trivial to perform manually all the steps required to
17078 produce a library. We recommend that you use the GNAT Project Manager
17079 for this task. In special cases where this is not desired, the necessary
17080 steps are discussed below.
17082 There are various possibilities for compiling the units that make up the
17083 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17084 with a conventional script. For simple libraries, it is also possible to create
17085 a dummy main program which depends upon all the packages that comprise the
17086 interface of the library. This dummy main program can then be given to
17087 @command{gnatmake}, which will ensure that all necessary objects are built.
17089 After this task is accomplished, you should follow the standard procedure
17090 of the underlying operating system to produce the static or shared library.
17092 Here is an example of such a dummy program:
17093 @smallexample @c ada
17094 @group
17095 with My_Lib.Service1;
17096 with My_Lib.Service2;
17097 with My_Lib.Service3;
17098 procedure My_Lib_Dummy is
17099 begin
17100    null;
17101 end;
17102 @end group
17103 @end smallexample
17105 @noindent
17106 Here are the generic commands that will build an archive or a shared library.
17108 @smallexample
17109 # compiling the library
17110 $ gnatmake -c my_lib_dummy.adb
17112 # we don't need the dummy object itself
17113 $ rm my_lib_dummy.o my_lib_dummy.ali
17115 # create an archive with the remaining objects
17116 $ ar rc libmy_lib.a *.o
17117 # some systems may require "ranlib" to be run as well
17119 # or create a shared library
17120 $ gcc -shared -o libmy_lib.so *.o
17121 # some systems may require the code to have been compiled with -fPIC
17123 # remove the object files that are now in the library
17124 $ rm *.o
17126 # Make the ALI files read-only so that gnatmake will not try to
17127 # regenerate the objects that are in the library
17128 $ chmod -w *.ali
17129 @end smallexample
17131 @noindent
17132 Please note that the library must have a name of the form @file{libxxx.a} or
17133 @file{libxxx.so} (or @file{libxxx.dll} on Windows) in order to be accessed by
17134 the directive @option{-lxxx} at link time.
17136 @node Installing a library
17137 @subsection Installing a library
17139 @noindent
17140 If you use project files, library installation is part of the library build
17141 process. Thus no further action is needed in order to make use of the
17142 libraries that are built as part of the general application build. A usable
17143 version of the library is installed in the directory specified by the
17144 @code{Library_Dir} attribute of the library project file.
17146 You may want to install a library in a context different from where the library
17147 is built. This situation arises with third party suppliers, who may want
17148 to distribute a library in binary form where the user is not expected to be
17149 able to recompile the library. The simplest option in this case is to provide
17150 a project file slightly different from the one used to build the library, by
17151 using the @code{externally_built} attribute. For instance, the project
17152 file used to build the library in the previous section can be changed into the
17153 following one when the library is installed:
17155 @smallexample @c projectfile
17156 project My_Lib is
17157    for Source_Dirs use ("src1", "src2");
17158    for Library_Name use "mylib";
17159    for Library_Dir use "lib";
17160    for Library_Kind use "dynamic";
17161    for Externally_Built use "true";
17162 end My_lib;
17163 @end smallexample
17165 @noindent
17166 This project file assumes that the directories @file{src1},
17167 @file{src2}, and @file{lib} exist in
17168 the directory containing the project file. The @code{externally_built}
17169 attribute makes it clear to the GNAT builder that it should not attempt to
17170 recompile any of the units from this library. It allows the library provider to
17171 restrict the source set to the minimum necessary for clients to make use of the
17172 library as described in the first section of this chapter. It is the
17173 responsibility of the library provider to install the necessary sources, ALI
17174 files and libraries in the directories mentioned in the project file. For
17175 convenience, the user's library project file should be installed in a location
17176 that will be searched automatically by the GNAT
17177 builder. These are the directories referenced in the @code{ADA_LIBRARY_PATH}
17178 environment variable (@pxref{Importing Projects}), and also the default GNAT
17179 library location that can be queried with @command{gnatls -v} and is usually of
17180 the form $gnat_install_root/lib/gnat.
17182 When project files are not an option, it is also possible, but not recommended,
17183 to install the library so that the sources needed to use the library are on the
17184 Ada source path and the ALI files & libraries be on the Ada Object path (see
17185 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17186 administrator can place general-purpose libraries in the default compiler
17187 paths, by specifying the libraries' location in the configuration files
17188 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17189 must be located in the GNAT installation tree at the same place as the gcc spec
17190 file. The location of the gcc spec file can be determined as follows:
17191 @smallexample
17192 $ gcc -v
17193 @end smallexample
17195 @noindent
17196 The configuration files mentioned above have a simple format: each line
17197 must contain one unique directory name.
17198 Those names are added to the corresponding path
17199 in their order of appearance in the file. The names can be either absolute
17200 or relative; in the latter case, they are relative to where theses files
17201 are located.
17203 The files @file{ada_source_path} and @file{ada_object_path} might not be
17204 present in a
17205 GNAT installation, in which case, GNAT will look for its run-time library in
17206 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17207 objects and @file{ALI} files). When the files exist, the compiler does not
17208 look in @file{adainclude} and @file{adalib}, and thus the
17209 @file{ada_source_path} file
17210 must contain the location for the GNAT run-time sources (which can simply
17211 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17212 contain the location for the GNAT run-time objects (which can simply
17213 be @file{adalib}).
17215 You can also specify a new default path to the run-time library at compilation
17216 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17217 the run-time library you want your program to be compiled with. This switch is
17218 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17219 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17221 It is possible to install a library before or after the standard GNAT
17222 library, by reordering the lines in the configuration files. In general, a
17223 library must be installed before the GNAT library if it redefines
17224 any part of it.
17226 @node Using a library
17227 @subsection Using a library
17229 @noindent Once again, the project facility greatly simplifies the use of
17230 libraries. In this context, using a library is just a matter of adding a
17231 @code{with} clause in the user project. For instance, to make use of the
17232 library @code{My_Lib} shown in examples in earlier sections, you can
17233 write:
17235 @smallexample @c projectfile
17236 with "my_lib";
17237 project My_Proj is
17238   ...
17239 end My_Proj;
17240 @end smallexample
17242 Even if you have a third-party, non-Ada library, you can still use GNAT's
17243 Project Manager facility to provide a wrapper for it. For example, the
17244 following project, when @code{with}ed by your main project, will link with the
17245 third-party library @file{liba.a}:
17247 @smallexample @c projectfile
17248 @group
17249 project Liba is
17250    for Source_Dirs use ();
17251    for Library_Dir use "lib";
17252    for Library_Name use "a";
17253    for Library_Kind use "static";
17254 end Liba;
17255 @end group
17256 @end smallexample
17258 @noindent
17259 In order to use an Ada library manually, you need to make sure that this
17260 library is on both your source and object path
17261 (see @ref{Search Paths and the Run-Time Library (RTL)}
17262 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17263 in an archive or a shared library, you need to specify the desired
17264 library at link time.
17266 For example, you can use the library @file{mylib} installed in
17267 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17269 @smallexample
17270 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17271   -largs -lmy_lib
17272 @end smallexample
17274 @noindent
17275 This can be expressed more simply:
17276 @smallexample
17277 $ gnatmake my_appl
17278 @end smallexample
17279 @noindent
17280 when the following conditions are met:
17281 @itemize @bullet
17282 @item
17283 @file{/dir/my_lib_src} has been added by the user to the environment
17284 variable @code{ADA_INCLUDE_PATH}, or by the administrator to the file
17285 @file{ada_source_path}
17286 @item
17287 @file{/dir/my_lib_obj} has been added by the user to the environment
17288 variable @code{ADA_OBJECTS_PATH}, or by the administrator to the file
17289 @file{ada_object_path}
17290 @item
17291 a pragma @code{Linker_Options} has been added to one of the sources.
17292 For example:
17294 @smallexample @c ada
17295 pragma Linker_Options ("-lmy_lib");
17296 @end smallexample
17297 @end itemize
17299 @node Stand-alone Ada Libraries
17300 @section Stand-alone Ada Libraries
17301 @cindex Stand-alone library, building, using
17303 @menu
17304 * Introduction to Stand-alone Libraries::
17305 * Building a Stand-alone Library::
17306 * Creating a Stand-alone Library to be used in a non-Ada context::
17307 * Restrictions in Stand-alone Libraries::
17308 @end menu
17310 @node Introduction to Stand-alone Libraries
17311 @subsection Introduction to Stand-alone Libraries
17313 @noindent
17314 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17315 necessary code to
17316 elaborate the Ada units that are included in the library. In contrast with
17317 an ordinary library, which consists of all sources, objects and @file{ALI}
17318 files of the
17319 library, a SAL may specify a restricted subset of compilation units
17320 to serve as a library interface. In this case, the fully
17321 self-sufficient set of files will normally consist of an objects
17322 archive, the sources of interface units' specs, and the @file{ALI}
17323 files of interface units.
17324 If an interface spec contains a generic unit or an inlined subprogram,
17325 the body's
17326 source must also be provided; if the units that must be provided in the source
17327 form depend on other units, the source and @file{ALI} files of those must
17328 also be provided.
17330 The main purpose of a SAL is to minimize the recompilation overhead of client
17331 applications when a new version of the library is installed. Specifically,
17332 if the interface sources have not changed, client applications do not need to
17333 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17334 version, controlled by @code{Library_Version} attribute, is not changed,
17335 then the clients do not need to be relinked.
17337 SALs also allow the library providers to minimize the amount of library source
17338 text exposed to the clients.  Such ``information hiding'' might be useful or
17339 necessary for various reasons.
17341 Stand-alone libraries are also well suited to be used in an executable whose
17342 main routine is not written in Ada.
17344 @node Building a Stand-alone Library
17345 @subsection Building a Stand-alone Library
17347 @noindent
17348 GNAT's Project facility provides a simple way of building and installing
17349 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17350 To be a Stand-alone Library Project, in addition to the two attributes
17351 that make a project a Library Project (@code{Library_Name} and
17352 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17353 @code{Library_Interface} must be defined.  For example:
17355 @smallexample @c projectfile
17356 @group
17357    for Library_Dir use "lib_dir";
17358    for Library_Name use "dummy";
17359    for Library_Interface use ("int1", "int1.child");
17360 @end group
17361 @end smallexample
17363 @noindent
17364 Attribute @code{Library_Interface} has a non-empty string list value,
17365 each string in the list designating a unit contained in an immediate source
17366 of the project file.
17368 When a Stand-alone Library is built, first the binder is invoked to build
17369 a package whose name depends on the library name
17370 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17371 This binder-generated package includes initialization and
17372 finalization procedures whose
17373 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17374 in the example
17375 above). The object corresponding to this package is included in the library.
17377 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17378 calling of these procedures if a static SAL is built, or if a shared SAL
17379 is built
17380 with the project-level attribute @code{Library_Auto_Init} set to
17381 @code{"false"}.
17383 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17384 (those that are listed in attribute @code{Library_Interface}) are copied to
17385 the Library Directory. As a consequence, only the Interface Units may be
17386 imported from Ada units outside of the library. If other units are imported,
17387 the binding phase will fail.
17389 The attribute @code{Library_Src_Dir} may be specified for a
17390 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17391 single string value. Its value must be the path (absolute or relative to the
17392 project directory) of an existing directory. This directory cannot be the
17393 object directory or one of the source directories, but it can be the same as
17394 the library directory. The sources of the Interface
17395 Units of the library that are needed by an Ada client of the library will be
17396 copied to the designated directory, called the Interface Copy directory.
17397 These sources include the specs of the Interface Units, but they may also
17398 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17399 are used, or when there is a generic unit in the spec. Before the sources
17400 are copied to the Interface Copy directory, an attempt is made to delete all
17401 files in the Interface Copy directory.
17403 Building stand-alone libraries by hand is somewhat tedious, but for those
17404 occasions when it is necessary here are the steps that you need to perform:
17405 @itemize @bullet
17406 @item
17407 Compile all library sources.
17409 @item
17410 Invoke the binder with the switch @option{-n} (No Ada main program),
17411 with all the @file{ALI} files of the interfaces, and
17412 with the switch @option{-L} to give specific names to the @code{init}
17413 and @code{final} procedures.  For example:
17414 @smallexample
17415   gnatbind -n int1.ali int2.ali -Lsal1
17416 @end smallexample
17418 @item
17419 Compile the binder generated file:
17420 @smallexample
17421   gcc -c b~int2.adb
17422 @end smallexample
17424 @item
17425 Link the dynamic library with all the necessary object files,
17426 indicating to the linker the names of the @code{init} (and possibly
17427 @code{final}) procedures for automatic initialization (and finalization).
17428 The built library should be placed in a directory different from
17429 the object directory.
17431 @item
17432 Copy the @code{ALI} files of the interface to the library directory,
17433 add in this copy an indication that it is an interface to a SAL
17434 (i.e. add a word @option{SL} on the line in the @file{ALI} file that starts
17435 with letter ``P'') and make the modified copy of the @file{ALI} file
17436 read-only.
17437 @end itemize
17439 @noindent
17440 Using SALs is not different from using other libraries
17441 (see @ref{Using a library}).
17443 @node Creating a Stand-alone Library to be used in a non-Ada context
17444 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17446 @noindent
17447 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17448 a non-Ada context.
17450 The only extra step required is to ensure that library interface subprograms
17451 are compatible with the main program, by means of @code{pragma Export}
17452 or @code{pragma Convention}.
17454 Here is an example of simple library interface for use with C main program:
17456 @smallexample @c ada
17457 package Interface is
17459    procedure Do_Something;
17460    pragma Export (C, Do_Something, "do_something");
17462    procedure Do_Something_Else;
17463    pragma Export (C, Do_Something_Else, "do_something_else");
17465 end Interface;
17466 @end smallexample
17468 @noindent
17469 On the foreign language side, you must provide a ``foreign'' view of the
17470 library interface; remember that it should contain elaboration routines in
17471 addition to interface subprograms.
17473 The example below shows the content of @code{mylib_interface.h} (note
17474 that there is no rule for the naming of this file, any name can be used)
17475 @smallexample
17476 /* the library elaboration procedure */
17477 extern void mylibinit (void);
17479 /* the library finalization procedure */
17480 extern void mylibfinal (void);
17482 /* the interface exported by the library */
17483 extern void do_something (void);
17484 extern void do_something_else (void);
17485 @end smallexample
17487 @noindent
17488 Libraries built as explained above can be used from any program, provided
17489 that the elaboration procedures (named @code{mylibinit} in the previous
17490 example) are called before the library services are used. Any number of
17491 libraries can be used simultaneously, as long as the elaboration
17492 procedure of each library is called.
17494 Below is an example of a C program that uses the @code{mylib} library.
17496 @smallexample
17497 #include "mylib_interface.h"
17500 main (void)
17502    /* First, elaborate the library before using it */
17503    mylibinit ();
17505    /* Main program, using the library exported entities */
17506    do_something ();
17507    do_something_else ();
17509    /* Library finalization at the end of the program */
17510    mylibfinal ();
17511    return 0;
17513 @end smallexample
17515 @noindent
17516 Note that invoking any library finalization procedure generated by
17517 @code{gnatbind} shuts down the Ada run-time environment.
17518 Consequently, the
17519 finalization of all Ada libraries must be performed at the end of the program.
17520 No call to these libraries or to the Ada run-time library should be made
17521 after the finalization phase.
17523 @node Restrictions in Stand-alone Libraries
17524 @subsection Restrictions in Stand-alone Libraries
17526 @noindent
17527 The pragmas listed below should be used with caution inside libraries,
17528 as they can create incompatibilities with other Ada libraries:
17529 @itemize @bullet
17530 @item pragma @code{Locking_Policy}
17531 @item pragma @code{Queuing_Policy}
17532 @item pragma @code{Task_Dispatching_Policy}
17533 @item pragma @code{Unreserve_All_Interrupts}
17534 @end itemize
17536 @noindent
17537 When using a library that contains such pragmas, the user must make sure
17538 that all libraries use the same pragmas with the same values. Otherwise,
17539 @code{Program_Error} will
17540 be raised during the elaboration of the conflicting
17541 libraries. The usage of these pragmas and its consequences for the user
17542 should therefore be well documented.
17544 Similarly, the traceback in the exception occurrence mechanism should be
17545 enabled or disabled in a consistent manner across all libraries.
17546 Otherwise, Program_Error will be raised during the elaboration of the
17547 conflicting libraries.
17549 If the @code{Version} or @code{Body_Version}
17550 attributes are used inside a library, then you need to
17551 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17552 libraries, so that version identifiers can be properly computed.
17553 In practice these attributes are rarely used, so this is unlikely
17554 to be a consideration.
17556 @node  Rebuilding the GNAT Run-Time Library
17557 @section Rebuilding the GNAT Run-Time Library
17558 @cindex GNAT Run-Time Library, rebuilding
17560 @noindent
17561 It may be useful to recompile the GNAT library in various contexts, the
17562 most important one being the use of partition-wide configuration pragmas
17563 such as @code{Normalize_Scalars}. A special Makefile called
17564 @code{Makefile.adalib} is provided to that effect and can be found in
17565 the directory containing the GNAT library. The location of this
17566 directory depends on the way the GNAT environment has been installed and can
17567 be determined by means of the command:
17569 @smallexample
17570 $ gnatls -v
17571 @end smallexample
17573 @noindent
17574 The last entry in the object search path usually contains the
17575 gnat library. This Makefile contains its own documentation and in
17576 particular the set of instructions needed to rebuild a new library and
17577 to use it.
17579 @node Using the GNU make Utility
17580 @chapter Using the GNU @code{make} Utility
17581 @findex make
17583 @noindent
17584 This chapter offers some examples of makefiles that solve specific
17585 problems. It does not explain how to write a makefile (see the GNU make
17586 documentation), nor does it try to replace the @command{gnatmake} utility
17587 (@pxref{The GNAT Make Program gnatmake}).
17589 All the examples in this section are specific to the GNU version of
17590 make. Although @code{make} is a standard utility, and the basic language
17591 is the same, these examples use some advanced features found only in
17592 @code{GNU make}.
17594 @menu
17595 * Using gnatmake in a Makefile::
17596 * Automatically Creating a List of Directories::
17597 * Generating the Command Line Switches::
17598 * Overcoming Command Line Length Limits::
17599 @end menu
17601 @node Using gnatmake in a Makefile
17602 @section Using gnatmake in a Makefile
17603 @findex makefile
17604 @cindex GNU make
17606 @noindent
17607 Complex project organizations can be handled in a very powerful way by
17608 using GNU make combined with gnatmake. For instance, here is a Makefile
17609 which allows you to build each subsystem of a big project into a separate
17610 shared library. Such a makefile allows you to significantly reduce the link
17611 time of very big applications while maintaining full coherence at
17612 each step of the build process.
17614 The list of dependencies are handled automatically by
17615 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17616 the appropriate directories.
17618 Note that you should also read the example on how to automatically
17619 create the list of directories
17620 (@pxref{Automatically Creating a List of Directories})
17621 which might help you in case your project has a lot of subdirectories.
17623 @smallexample
17624 @iftex
17625 @leftskip=0cm
17626 @font@heightrm=cmr8
17627 @heightrm
17628 @end iftex
17629 ## This Makefile is intended to be used with the following directory
17630 ## configuration:
17631 ##  - The sources are split into a series of csc (computer software components)
17632 ##    Each of these csc is put in its own directory.
17633 ##    Their name are referenced by the directory names.
17634 ##    They will be compiled into shared library (although this would also work
17635 ##    with static libraries
17636 ##  - The main program (and possibly other packages that do not belong to any
17637 ##    csc is put in the top level directory (where the Makefile is).
17638 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17639 ##                    \_ second_csc (sources) __ lib (will contain the library)
17640 ##                    \_ ...
17641 ## Although this Makefile is build for shared library, it is easy to modify
17642 ## to build partial link objects instead (modify the lines with -shared and
17643 ## gnatlink below)
17645 ## With this makefile, you can change any file in the system or add any new
17646 ## file, and everything will be recompiled correctly (only the relevant shared
17647 ## objects will be recompiled, and the main program will be re-linked).
17649 # The list of computer software component for your project. This might be
17650 # generated automatically.
17651 CSC_LIST=aa bb cc
17653 # Name of the main program (no extension)
17654 MAIN=main
17656 # If we need to build objects with -fPIC, uncomment the following line
17657 #NEED_FPIC=-fPIC
17659 # The following variable should give the directory containing libgnat.so
17660 # You can get this directory through 'gnatls -v'. This is usually the last
17661 # directory in the Object_Path.
17662 GLIB=...
17664 # The directories for the libraries
17665 # (This macro expands the list of CSC to the list of shared libraries, you
17666 # could simply use the expanded form :
17667 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17668 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17670 $@{MAIN@}: objects $@{LIB_DIR@}
17671     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17672     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17674 objects::
17675     # recompile the sources
17676     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17678 # Note: In a future version of GNAT, the following commands will be simplified
17679 # by a new tool, gnatmlib
17680 $@{LIB_DIR@}:
17681     mkdir -p $@{dir $@@ @}
17682     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17683     cd $@{dir $@@ @}; cp -f ../*.ali .
17685 # The dependencies for the modules
17686 # Note that we have to force the expansion of *.o, since in some cases
17687 # make won't be able to do it itself.
17688 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17689 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17690 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17692 # Make sure all of the shared libraries are in the path before starting the
17693 # program
17694 run::
17695     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17697 clean::
17698     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17699     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17700     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17701     $@{RM@} *.o *.ali $@{MAIN@}
17702 @end smallexample
17704 @node Automatically Creating a List of Directories
17705 @section Automatically Creating a List of Directories
17707 @noindent
17708 In most makefiles, you will have to specify a list of directories, and
17709 store it in a variable. For small projects, it is often easier to
17710 specify each of them by hand, since you then have full control over what
17711 is the proper order for these directories, which ones should be
17712 included...
17714 However, in larger projects, which might involve hundreds of
17715 subdirectories, it might be more convenient to generate this list
17716 automatically.
17718 The example below presents two methods. The first one, although less
17719 general, gives you more control over the list. It involves wildcard
17720 characters, that are automatically expanded by @code{make}. Its
17721 shortcoming is that you need to explicitly specify some of the
17722 organization of your project, such as for instance the directory tree
17723 depth, whether some directories are found in a separate tree,...
17725 The second method is the most general one. It requires an external
17726 program, called @code{find}, which is standard on all Unix systems. All
17727 the directories found under a given root directory will be added to the
17728 list.
17730 @smallexample
17731 @iftex
17732 @leftskip=0cm
17733 @font@heightrm=cmr8
17734 @heightrm
17735 @end iftex
17736 # The examples below are based on the following directory hierarchy:
17737 # All the directories can contain any number of files
17738 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17739 #                       ->  ab
17740 #                       ->  ac
17741 #                ->  b  ->  ba  ->  baa
17742 #                       ->  bb
17743 #                       ->  bc
17744 # This Makefile creates a variable called DIRS, that can be reused any time
17745 # you need this list (see the other examples in this section)
17747 # The root of your project's directory hierarchy
17748 ROOT_DIRECTORY=.
17750 ####
17751 # First method: specify explicitly the list of directories
17752 # This allows you to specify any subset of all the directories you need.
17753 ####
17755 DIRS := a/aa/ a/ab/ b/ba/
17757 ####
17758 # Second method: use wildcards
17759 # Note that the argument(s) to wildcard below should end with a '/'.
17760 # Since wildcards also return file names, we have to filter them out
17761 # to avoid duplicate directory names.
17762 # We thus use make's @code{dir} and @code{sort} functions.
17763 # It sets DIRs to the following value (note that the directories aaa and baa
17764 # are not given, unless you change the arguments to wildcard).
17765 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17766 ####
17768 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17769                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17771 ####
17772 # Third method: use an external program
17773 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17774 # This is the most complete command: it sets DIRs to the following value:
17775 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17776 ####
17778 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17780 @end smallexample
17782 @node Generating the Command Line Switches
17783 @section Generating the Command Line Switches
17785 @noindent
17786 Once you have created the list of directories as explained in the
17787 previous section (@pxref{Automatically Creating a List of Directories}),
17788 you can easily generate the command line arguments to pass to gnatmake.
17790 For the sake of completeness, this example assumes that the source path
17791 is not the same as the object path, and that you have two separate lists
17792 of directories.
17794 @smallexample
17795 # see "Automatically creating a list of directories" to create
17796 # these variables
17797 SOURCE_DIRS=
17798 OBJECT_DIRS=
17800 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17801 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17803 all:
17804         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17805 @end smallexample
17807 @node Overcoming Command Line Length Limits
17808 @section Overcoming Command Line Length Limits
17810 @noindent
17811 One problem that might be encountered on big projects is that many
17812 operating systems limit the length of the command line. It is thus hard to give
17813 gnatmake the list of source and object directories.
17815 This example shows how you can set up environment variables, which will
17816 make @command{gnatmake} behave exactly as if the directories had been
17817 specified on the command line, but have a much higher length limit (or
17818 even none on most systems).
17820 It assumes that you have created a list of directories in your Makefile,
17821 using one of the methods presented in
17822 @ref{Automatically Creating a List of Directories}.
17823 For the sake of completeness, we assume that the object
17824 path (where the ALI files are found) is different from the sources patch.
17826 Note a small trick in the Makefile below: for efficiency reasons, we
17827 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17828 expanded immediately by @code{make}. This way we overcome the standard
17829 make behavior which is to expand the variables only when they are
17830 actually used.
17832 On Windows, if you are using the standard Windows command shell, you must
17833 replace colons with semicolons in the assignments to these variables.
17835 @smallexample
17836 @iftex
17837 @leftskip=0cm
17838 @font@heightrm=cmr8
17839 @heightrm
17840 @end iftex
17841 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
17842 # This is the same thing as putting the -I arguments on the command line.
17843 # (the equivalent of using -aI on the command line would be to define
17844 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
17845 # You can of course have different values for these variables.
17847 # Note also that we need to keep the previous values of these variables, since
17848 # they might have been set before running 'make' to specify where the GNAT
17849 # library is installed.
17851 # see "Automatically creating a list of directories" to create these
17852 # variables
17853 SOURCE_DIRS=
17854 OBJECT_DIRS=
17856 empty:=
17857 space:=$@{empty@} $@{empty@}
17858 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17859 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17860 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17861 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
17862 export ADA_INCLUDE_PATH
17863 export ADA_OBJECT_PATH
17865 all:
17866         gnatmake main_unit
17867 @end smallexample
17868 @end ifclear
17870 @node Memory Management Issues
17871 @chapter Memory Management Issues
17873 @noindent
17874 This chapter describes some useful memory pools provided in the GNAT library
17875 and in particular the GNAT Debug Pool facility, which can be used to detect
17876 incorrect uses of access values (including ``dangling references'').
17877 @ifclear vms
17878 It also describes the @command{gnatmem} tool, which can be used to track down
17879 ``memory leaks''.
17880 @end ifclear
17882 @menu
17883 * Some Useful Memory Pools::
17884 * The GNAT Debug Pool Facility::
17885 @ifclear vms
17886 * The gnatmem Tool::
17887 @end ifclear
17888 @end menu
17890 @node Some Useful Memory Pools
17891 @section Some Useful Memory Pools
17892 @findex Memory Pool
17893 @cindex storage, pool
17895 @noindent
17896 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
17897 storage pool. Allocations use the standard system call @code{malloc} while
17898 deallocations use the standard system call @code{free}. No reclamation is
17899 performed when the pool goes out of scope. For performance reasons, the
17900 standard default Ada allocators/deallocators do not use any explicit storage
17901 pools but if they did, they could use this storage pool without any change in
17902 behavior. That is why this storage pool is used  when the user
17903 manages to make the default implicit allocator explicit as in this example:
17904 @smallexample @c ada
17905    type T1 is access Something;
17906     -- no Storage pool is defined for T2
17907    type T2 is access Something_Else;
17908    for T2'Storage_Pool use T1'Storage_Pool;
17909    -- the above is equivalent to
17910    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
17911 @end smallexample
17913 @noindent
17914 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
17915 pool. The allocation strategy is similar to @code{Pool_Local}'s
17916 except that the all
17917 storage allocated with this pool is reclaimed when the pool object goes out of
17918 scope. This pool provides a explicit mechanism similar to the implicit one
17919 provided by several Ada 83 compilers for allocations performed through a local
17920 access type and whose purpose was to reclaim memory when exiting the
17921 scope of a given local access. As an example, the following program does not
17922 leak memory even though it does not perform explicit deallocation:
17924 @smallexample @c ada
17925 with System.Pool_Local;
17926 procedure Pooloc1 is
17927    procedure Internal is
17928       type A is access Integer;
17929       X : System.Pool_Local.Unbounded_Reclaim_Pool;
17930       for A'Storage_Pool use X;
17931       v : A;
17932    begin
17933       for I in  1 .. 50 loop
17934          v := new Integer;
17935       end loop;
17936    end Internal;
17937 begin
17938    for I in  1 .. 100 loop
17939       Internal;
17940    end loop;
17941 end Pooloc1;
17942 @end smallexample
17944 @noindent
17945 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
17946 @code{Storage_Size} is specified for an access type.
17947 The whole storage for the pool is
17948 allocated at once, usually on the stack at the point where the access type is
17949 elaborated. It is automatically reclaimed when exiting the scope where the
17950 access type is defined. This package is not intended to be used directly by the
17951 user and it is implicitly used for each such declaration:
17953 @smallexample @c ada
17954    type T1 is access Something;
17955    for T1'Storage_Size use 10_000;
17956 @end smallexample
17959 @node The GNAT Debug Pool Facility
17960 @section The GNAT Debug Pool Facility
17961 @findex Debug Pool
17962 @cindex storage, pool, memory corruption
17964 @noindent
17965 The use of unchecked deallocation and unchecked conversion can easily
17966 lead to incorrect memory references. The problems generated by such
17967 references are usually difficult to tackle because the symptoms can be
17968 very remote from the origin of the problem. In such cases, it is
17969 very helpful to detect the problem as early as possible. This is the
17970 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
17972 In order to use the GNAT specific debugging pool, the user must
17973 associate a debug pool object with each of the access types that may be
17974 related to suspected memory problems. See Ada Reference Manual 13.11.
17975 @smallexample @c ada
17976 type Ptr is access Some_Type;
17977 Pool : GNAT.Debug_Pools.Debug_Pool;
17978 for Ptr'Storage_Pool use Pool;
17979 @end smallexample
17981 @noindent
17982 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
17983 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
17984 allow the user to redefine allocation and deallocation strategies. They
17985 also provide a checkpoint for each dereference, through the use of
17986 the primitive operation @code{Dereference} which is implicitly called at
17987 each dereference of an access value.
17989 Once an access type has been associated with a debug pool, operations on
17990 values of the type may raise four distinct exceptions,
17991 which correspond to four potential kinds of memory corruption:
17992 @itemize @bullet
17993 @item
17994 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
17995 @item
17996 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
17997 @item
17998 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
17999 @item
18000 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18001 @end itemize
18003 @noindent
18004 For types associated with a Debug_Pool, dynamic allocation is performed using
18005 the standard GNAT allocation routine. References to all allocated chunks of
18006 memory are kept in an internal dictionary. Several deallocation strategies are
18007 provided, whereupon the user can choose to release the memory to the system,
18008 keep it allocated for further invalid access checks, or fill it with an easily
18009 recognizable pattern for debug sessions. The memory pattern is the old IBM
18010 hexadecimal convention: @code{16#DEADBEEF#}.
18012 See the documentation in the file g-debpoo.ads for more information on the
18013 various strategies.
18015 Upon each dereference, a check is made that the access value denotes a
18016 properly allocated memory location. Here is a complete example of use of
18017 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18018 @smallexample @c ada
18019 @iftex
18020 @leftskip=0cm
18021 @end iftex
18022 with Gnat.Io; use Gnat.Io;
18023 with Unchecked_Deallocation;
18024 with Unchecked_Conversion;
18025 with GNAT.Debug_Pools;
18026 with System.Storage_Elements;
18027 with Ada.Exceptions; use Ada.Exceptions;
18028 procedure Debug_Pool_Test is
18030    type T is access Integer;
18031    type U is access all T;
18033    P : GNAT.Debug_Pools.Debug_Pool;
18034    for T'Storage_Pool use P;
18036    procedure Free is new Unchecked_Deallocation (Integer, T);
18037    function UC is new Unchecked_Conversion (U, T);
18038    A, B : aliased T;
18040    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18042 begin
18043    Info (P);
18044    A := new Integer;
18045    B := new Integer;
18046    B := A;
18047    Info (P);
18048    Free (A);
18049    begin
18050       Put_Line (Integer'Image(B.all));
18051    exception
18052       when E : others => Put_Line ("raised: " & Exception_Name (E));
18053    end;
18054    begin
18055       Free (B);
18056    exception
18057       when E : others => Put_Line ("raised: " & Exception_Name (E));
18058    end;
18059    B := UC(A'Access);
18060    begin
18061       Put_Line (Integer'Image(B.all));
18062    exception
18063       when E : others => Put_Line ("raised: " & Exception_Name (E));
18064    end;
18065    begin
18066       Free (B);
18067    exception
18068       when E : others => Put_Line ("raised: " & Exception_Name (E));
18069    end;
18070    Info (P);
18071 end Debug_Pool_Test;
18072 @end smallexample
18074 @noindent
18075 The debug pool mechanism provides the following precise diagnostics on the
18076 execution of this erroneous program:
18077 @smallexample
18078 Debug Pool info:
18079   Total allocated bytes :  0
18080   Total deallocated bytes :  0
18081   Current Water Mark:  0
18082   High Water Mark:  0
18084 Debug Pool info:
18085   Total allocated bytes :  8
18086   Total deallocated bytes :  0
18087   Current Water Mark:  8
18088   High Water Mark:  8
18090 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18091 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18092 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18093 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18094 Debug Pool info:
18095   Total allocated bytes :  8
18096   Total deallocated bytes :  4
18097   Current Water Mark:  4
18098   High Water Mark:  8
18099 @end smallexample
18101 @ifclear vms
18102 @node The gnatmem Tool
18103 @section The @command{gnatmem} Tool
18104 @findex gnatmem
18106 @noindent
18107 The @code{gnatmem} utility monitors dynamic allocation and
18108 deallocation activity in a program, and displays information about
18109 incorrect deallocations and possible sources of memory leaks.
18110 It provides three type of information:
18111 @itemize @bullet
18112 @item
18113 General information concerning memory management, such as the total
18114 number of allocations and deallocations, the amount of allocated
18115 memory and the high water mark, i.e. the largest amount of allocated
18116 memory in the course of program execution.
18118 @item
18119 Backtraces for all incorrect deallocations, that is to say deallocations
18120 which do not correspond to a valid allocation.
18122 @item
18123 Information on each allocation that is potentially the origin of a memory
18124 leak.
18125 @end itemize
18127 @menu
18128 * Running gnatmem::
18129 * Switches for gnatmem::
18130 * Example of gnatmem Usage::
18131 @end menu
18133 @node Running gnatmem
18134 @subsection Running @code{gnatmem}
18136 @noindent
18137 @code{gnatmem} makes use of the output created by the special version of
18138 allocation and deallocation routines that record call information. This
18139 allows to obtain accurate dynamic memory usage history at a minimal cost to
18140 the execution speed. Note however, that @code{gnatmem} is not supported on
18141 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux x86,
18142 Solaris (sparc and x86) and Windows NT/2000/XP (x86).
18144 @noindent
18145 The @code{gnatmem} command has the form
18147 @smallexample
18148    $ gnatmem [switches] user_program
18149 @end smallexample
18151 @noindent
18152 The program must have been linked with the instrumented version of the
18153 allocation and deallocation routines. This is done by linking with the
18154 @file{libgmem.a} library. For correct symbolic backtrace information,
18155 the user program should be compiled with debugging options
18156 @ref{Switches for gcc}. For example to build @file{my_program}:
18158 @smallexample
18159 $ gnatmake -g my_program -largs -lgmem
18160 @end smallexample
18162 @noindent
18163 When running @file{my_program} the file @file{gmem.out} is produced. This file
18164 contains information about all allocations and deallocations done by the
18165 program. It is produced by the instrumented allocations and
18166 deallocations routines and will be used by @code{gnatmem}.
18168 @noindent
18169 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18170 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18171 @code{-i} switch, gnatmem will assume that this file can be found in the
18172 current directory. For example, after you have executed @file{my_program},
18173 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18175 @smallexample
18176 $ gnatmem my_program
18177 @end smallexample
18179 @noindent
18180 This will produce the output with the following format:
18182 *************** debut cc
18183 @smallexample
18184 $ gnatmem my_program
18186 Global information
18187 ------------------
18188    Total number of allocations        :  45
18189    Total number of deallocations      :   6
18190    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18191    High Water Mark                    :  11.40 Kilobytes
18196 Allocation Root # 2
18197 -------------------
18198  Number of non freed allocations    :  11
18199  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18200  High Water Mark                    :   1.27 Kilobytes
18201  Backtrace                          :
18202    my_program.adb:23 my_program.alloc
18206 @end smallexample
18208 The first block of output gives general information. In this case, the
18209 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18210 Unchecked_Deallocation routine occurred.
18212 @noindent
18213 Subsequent paragraphs display  information on all allocation roots.
18214 An allocation root is a specific point in the execution of the program
18215 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18216 construct. This root is represented by an execution backtrace (or subprogram
18217 call stack). By default the backtrace depth for allocations roots is 1, so
18218 that a root corresponds exactly to a source location. The backtrace can
18219 be made deeper, to make the root more specific.
18221 @node Switches for gnatmem
18222 @subsection Switches for @code{gnatmem}
18224 @noindent
18225 @code{gnatmem} recognizes the following switches:
18227 @table @option
18229 @item -q
18230 @cindex @option{-q} (@code{gnatmem})
18231 Quiet. Gives the minimum output needed to identify the origin of the
18232 memory leaks. Omits statistical information.
18234 @item @var{N}
18235 @cindex @var{N} (@code{gnatmem})
18236 N is an integer literal (usually between 1 and 10) which controls the
18237 depth of the backtraces defining allocation root. The default value for
18238 N is 1. The deeper the backtrace, the more precise the localization of
18239 the root. Note that the total number of roots can depend on this
18240 parameter. This parameter must be specified @emph{before} the name of the
18241 executable to be analyzed, to avoid ambiguity.
18243 @item -b n
18244 @cindex @option{-b} (@code{gnatmem})
18245 This switch has the same effect as just depth parameter.
18247 @item -i @var{file}
18248 @cindex @option{-i} (@code{gnatmem})
18249 Do the @code{gnatmem} processing starting from @file{file}, rather than
18250 @file{gmem.out} in the current directory.
18252 @item -m n
18253 @cindex @option{-m} (@code{gnatmem})
18254 This switch causes @code{gnatmem} to mask the allocation roots that have less
18255 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18256 examine even the roots that didn't result in leaks.
18258 @item -s order
18259 @cindex @option{-s} (@code{gnatmem})
18260 This switch causes @code{gnatmem} to sort the allocation roots according to the
18261 specified order of sort criteria, each identified by a single letter. The
18262 currently supported criteria are @code{n, h, w} standing respectively for
18263 number of unfreed allocations, high watermark, and final watermark
18264 corresponding to a specific root. The default order is @code{nwh}.
18266 @end table
18268 @node Example of gnatmem Usage
18269 @subsection Example of @code{gnatmem} Usage
18271 @noindent
18272 The following example shows the use of @code{gnatmem}
18273 on a simple memory-leaking program.
18274 Suppose that we have the following Ada program:
18276 @smallexample @c ada
18277 @group
18278 @cartouche
18279 with Unchecked_Deallocation;
18280 procedure Test_Gm is
18282    type T is array (1..1000) of Integer;
18283    type Ptr is access T;
18284    procedure Free is new Unchecked_Deallocation (T, Ptr);
18285    A : Ptr;
18287    procedure My_Alloc is
18288    begin
18289       A := new T;
18290    end My_Alloc;
18292    procedure My_DeAlloc is
18293       B : Ptr := A;
18294    begin
18295       Free (B);
18296    end My_DeAlloc;
18298 begin
18299    My_Alloc;
18300    for I in 1 .. 5 loop
18301       for J in I .. 5 loop
18302          My_Alloc;
18303       end loop;
18304       My_Dealloc;
18305    end loop;
18306 end;
18307 @end cartouche
18308 @end group
18309 @end smallexample
18311 @noindent
18312 The program needs to be compiled with debugging option and linked with
18313 @code{gmem} library:
18315 @smallexample
18316 $ gnatmake -g test_gm -largs -lgmem
18317 @end smallexample
18319 @noindent
18320 Then we execute the program as usual:
18322 @smallexample
18323 $ test_gm
18324 @end smallexample
18326 @noindent
18327 Then @code{gnatmem} is invoked simply with
18328 @smallexample
18329 $ gnatmem test_gm
18330 @end smallexample
18332 @noindent
18333 which produces the following output (result may vary on different platforms):
18335 @smallexample
18336 Global information
18337 ------------------
18338    Total number of allocations        :  18
18339    Total number of deallocations      :   5
18340    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18341    High Water Mark                    :  56.90 Kilobytes
18343 Allocation Root # 1
18344 -------------------
18345  Number of non freed allocations    :  11
18346  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18347  High Water Mark                    :  46.88 Kilobytes
18348  Backtrace                          :
18349    test_gm.adb:11 test_gm.my_alloc
18351 Allocation Root # 2
18352 -------------------
18353  Number of non freed allocations    :   1
18354  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18355  High Water Mark                    :  10.02 Kilobytes
18356  Backtrace                          :
18357    s-secsta.adb:81 system.secondary_stack.ss_init
18359 Allocation Root # 3
18360 -------------------
18361  Number of non freed allocations    :   1
18362  Final Water Mark (non freed mem)   :  12 Bytes
18363  High Water Mark                    :  12 Bytes
18364  Backtrace                          :
18365    s-secsta.adb:181 system.secondary_stack.ss_init
18366 @end smallexample
18368 @noindent
18369 Note that the GNAT run time contains itself a certain number of
18370 allocations that have no  corresponding deallocation,
18371 as shown here for root #2 and root
18372 #3. This is a normal behavior when the number of non freed allocations
18373 is one, it allocates dynamic data structures that the run time needs for
18374 the complete lifetime of the program. Note also that there is only one
18375 allocation root in the user program with a single line back trace:
18376 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18377 program shows that 'My_Alloc' is called at 2 different points in the
18378 source (line 21 and line 24). If those two allocation roots need to be
18379 distinguished, the backtrace depth parameter can be used:
18381 @smallexample
18382 $ gnatmem 3 test_gm
18383 @end smallexample
18385 @noindent
18386 which will give the following output:
18388 @smallexample
18389 Global information
18390 ------------------
18391    Total number of allocations        :  18
18392    Total number of deallocations      :   5
18393    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18394    High Water Mark                    :  56.90 Kilobytes
18396 Allocation Root # 1
18397 -------------------
18398  Number of non freed allocations    :  10
18399  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18400  High Water Mark                    :  42.97 Kilobytes
18401  Backtrace                          :
18402    test_gm.adb:11 test_gm.my_alloc
18403    test_gm.adb:24 test_gm
18404    b_test_gm.c:52 main
18406 Allocation Root # 2
18407 -------------------
18408  Number of non freed allocations    :   1
18409  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18410  High Water Mark                    :  10.02 Kilobytes
18411  Backtrace                          :
18412    s-secsta.adb:81  system.secondary_stack.ss_init
18413    s-secsta.adb:283 <system__secondary_stack___elabb>
18414    b_test_gm.c:33   adainit
18416 Allocation Root # 3
18417 -------------------
18418  Number of non freed allocations    :   1
18419  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18420  High Water Mark                    :   3.91 Kilobytes
18421  Backtrace                          :
18422    test_gm.adb:11 test_gm.my_alloc
18423    test_gm.adb:21 test_gm
18424    b_test_gm.c:52 main
18426 Allocation Root # 4
18427 -------------------
18428  Number of non freed allocations    :   1
18429  Final Water Mark (non freed mem)   :  12 Bytes
18430  High Water Mark                    :  12 Bytes
18431  Backtrace                          :
18432    s-secsta.adb:181 system.secondary_stack.ss_init
18433    s-secsta.adb:283 <system__secondary_stack___elabb>
18434    b_test_gm.c:33   adainit
18435 @end smallexample
18437 @noindent
18438 The allocation root #1 of the first example has been split in 2 roots #1
18439 and #3 thanks to the more precise associated backtrace.
18441 @end ifclear
18443 @node Creating Sample Bodies Using gnatstub
18444 @chapter Creating Sample Bodies Using @command{gnatstub}
18445 @findex gnatstub
18447 @noindent
18448 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18449 for library unit declarations.
18451 To create a body stub, @command{gnatstub} has to compile the library
18452 unit declaration. Therefore, bodies can be created only for legal
18453 library units. Moreover, if a library unit depends semantically upon
18454 units located outside the current directory, you have to provide
18455 the source search path when calling @command{gnatstub}, see the description
18456 of @command{gnatstub} switches below.
18458 @menu
18459 * Running gnatstub::
18460 * Switches for gnatstub::
18461 @end menu
18463 @node Running gnatstub
18464 @section Running @command{gnatstub}
18466 @noindent
18467 @command{gnatstub} has the command-line interface of the form
18469 @smallexample
18470 $ gnatstub [switches] filename [directory]
18471 @end smallexample
18473 @noindent
18474 where
18475 @table @emph
18476 @item filename
18477 is the name of the source file that contains a library unit declaration
18478 for which a body must be created. The file name may contain the path
18479 information.
18480 The file name does not have to follow the GNAT file name conventions. If the
18481 name
18482 does not follow GNAT file naming conventions, the name of the body file must
18483 be provided
18484 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
18485 If the file name follows the GNAT file naming
18486 conventions and the name of the body file is not provided,
18487 @command{gnatstub}
18488 creates the name
18489 of the body file from the argument file name by replacing the @file{.ads}
18490 suffix
18491 with the @file{.adb} suffix.
18493 @item directory
18494 indicates the directory in which the body stub is to be placed (the default
18495 is the
18496 current directory)
18498 @item switches
18499 is an optional sequence of switches as described in the next section
18500 @end table
18502 @node Switches for gnatstub
18503 @section Switches for @command{gnatstub}
18505 @table @option
18506 @c !sort!
18508 @item ^-f^/FULL^
18509 @cindex @option{^-f^/FULL^} (@command{gnatstub})
18510 If the destination directory already contains a file with the name of the
18511 body file
18512 for the argument spec file, replace it with the generated body stub.
18514 @item ^-hs^/HEADER=SPEC^
18515 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
18516 Put the comment header (i.e., all the comments preceding the
18517 compilation unit) from the source of the library unit declaration
18518 into the body stub.
18520 @item ^-hg^/HEADER=GENERAL^
18521 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
18522 Put a sample comment header into the body stub.
18524 @ifclear vms
18525 @item -IDIR
18526 @cindex @option{-IDIR} (@command{gnatstub})
18527 @itemx -I-
18528 @cindex @option{-I-} (@command{gnatstub})
18529 @end ifclear
18530 @ifset vms
18531 @item /NOCURRENT_DIRECTORY
18532 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
18533 @end ifset
18534 ^These switches have ^This switch has^ the same meaning as in calls to
18535 @command{gcc}.
18536 ^They define ^It defines ^ the source search path in the call to
18537 @command{gcc} issued
18538 by @command{gnatstub} to compile an argument source file.
18540 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
18541 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
18542 This switch has the same meaning as in calls to @command{gcc}.
18543 It defines the additional configuration file to be passed to the call to
18544 @command{gcc} issued
18545 by @command{gnatstub} to compile an argument source file.
18547 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
18548 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
18549 (@var{n} is a non-negative integer). Set the maximum line length in the
18550 body stub to @var{n}; the default is 79. The maximum value that can be
18551 specified is 32767. Note that in the special case of configuration
18552 pragma files, the maximum is always 32767 regardless of whether or
18553 not this switch appears.
18555 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
18556 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
18557 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
18558 the generated body sample to @var{n}.
18559 The default indentation is 3.
18561 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
18562 @cindex @option{^-gnato^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
18563 Order local bodies alphabetically. (By default local bodies are ordered
18564 in the same way as the corresponding local specs in the argument spec file.)
18566 @item ^-i^/INDENTATION=^@var{n}
18567 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
18568 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
18570 @item ^-k^/TREE_FILE=SAVE^
18571 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
18572 Do not remove the tree file (i.e., the snapshot of the compiler internal
18573 structures used by @command{gnatstub}) after creating the body stub.
18575 @item ^-l^/LINE_LENGTH=^@var{n}
18576 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
18577 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
18579 @item ^-o^/BODY=^@var{body-name}
18580 @cindex @option{^-o^/BODY^} (@command{gnatstub})
18581 Body file name.  This should be set if the argument file name does not
18582 follow
18583 the GNAT file naming
18584 conventions. If this switch is omitted the default name for the body will be
18585 obtained
18586 from the argument file name according to the GNAT file naming conventions.
18588 @item ^-q^/QUIET^
18589 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
18590 Quiet mode: do not generate a confirmation when a body is
18591 successfully created, and do not generate a message when a body is not
18592 required for an
18593 argument unit.
18595 @item ^-r^/TREE_FILE=REUSE^
18596 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
18597 Reuse the tree file (if it exists) instead of creating it.  Instead of
18598 creating the tree file for the library unit declaration, @command{gnatstub}
18599 tries to find it in the current directory and use it for creating
18600 a body. If the tree file is not found, no body is created. This option
18601 also implies @option{^-k^/SAVE^}, whether or not
18602 the latter is set explicitly.
18604 @item ^-t^/TREE_FILE=OVERWRITE^
18605 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
18606 Overwrite the existing tree file.  If the current directory already
18607 contains the file which, according to the GNAT file naming rules should
18608 be considered as a tree file for the argument source file,
18609 @command{gnatstub}
18610 will refuse to create the tree file needed to create a sample body
18611 unless this option is set.
18613 @item ^-v^/VERBOSE^
18614 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
18615 Verbose mode: generate version information.
18617 @end table
18619 @node Other Utility Programs
18620 @chapter Other Utility Programs
18622 @noindent
18623 This chapter discusses some other utility programs available in the Ada
18624 environment.
18626 @menu
18627 * Using Other Utility Programs with GNAT::
18628 * The External Symbol Naming Scheme of GNAT::
18629 @ifclear vms
18630 * Ada Mode for Glide::
18631 @end ifclear
18632 * Converting Ada Files to html with gnathtml::
18633 * Installing gnathtml::
18634 @ifset vms
18635 * LSE::
18636 * Profiling::
18637 @end ifset
18638 @end menu
18640 @node Using Other Utility Programs with GNAT
18641 @section Using Other Utility Programs with GNAT
18643 @noindent
18644 The object files generated by GNAT are in standard system format and in
18645 particular the debugging information uses this format. This means
18646 programs generated by GNAT can be used with existing utilities that
18647 depend on these formats.
18649 @ifclear vms
18650 In general, any utility program that works with C will also often work with
18651 Ada programs generated by GNAT. This includes software utilities such as
18652 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
18653 as Purify.
18654 @end ifclear
18656 @node The External Symbol Naming Scheme of GNAT
18657 @section The External Symbol Naming Scheme of GNAT
18659 @noindent
18660 In order to interpret the output from GNAT, when using tools that are
18661 originally intended for use with other languages, it is useful to
18662 understand the conventions used to generate link names from the Ada
18663 entity names.
18665 All link names are in all lowercase letters. With the exception of library
18666 procedure names, the mechanism used is simply to use the full expanded
18667 Ada name with dots replaced by double underscores. For example, suppose
18668 we have the following package spec:
18670 @smallexample @c ada
18671 @group
18672 @cartouche
18673 package QRS is
18674    MN : Integer;
18675 end QRS;
18676 @end cartouche
18677 @end group
18678 @end smallexample
18680 @noindent
18681 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
18682 the corresponding link name is @code{qrs__mn}.
18683 @findex Export
18684 Of course if a @code{pragma Export} is used this may be overridden:
18686 @smallexample @c ada
18687 @group
18688 @cartouche
18689 package Exports is
18690    Var1 : Integer;
18691    pragma Export (Var1, C, External_Name => "var1_name");
18692    Var2 : Integer;
18693    pragma Export (Var2, C, Link_Name => "var2_link_name");
18694 end Exports;
18695 @end cartouche
18696 @end group
18697 @end smallexample
18699 @noindent
18700 In this case, the link name for @var{Var1} is whatever link name the
18701 C compiler would assign for the C function @var{var1_name}. This typically
18702 would be either @var{var1_name} or @var{_var1_name}, depending on operating
18703 system conventions, but other possibilities exist. The link name for
18704 @var{Var2} is @var{var2_link_name}, and this is not operating system
18705 dependent.
18707 @findex _main
18708 One exception occurs for library level procedures. A potential ambiguity
18709 arises between the required name @code{_main} for the C main program,
18710 and the name we would otherwise assign to an Ada library level procedure
18711 called @code{Main} (which might well not be the main program).
18713 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
18714 names. So if we have a library level procedure such as
18716 @smallexample @c ada
18717 @group
18718 @cartouche
18719 procedure Hello (S : String);
18720 @end cartouche
18721 @end group
18722 @end smallexample
18724 @noindent
18725 the external name of this procedure will be @var{_ada_hello}.
18727 @ifclear vms
18728 @node Ada Mode for Glide
18729 @section Ada Mode for @code{Glide}
18730 @cindex Ada mode (for Glide)
18732 @noindent
18733 The Glide mode for programming in Ada (both Ada83 and Ada95) helps the
18734 user to understand and navigate existing code, and facilitates writing
18735 new code. It furthermore provides some utility functions for easier
18736 integration of standard Emacs features when programming in Ada.
18738 Its general features include:
18740 @itemize @bullet
18741 @item
18742 An Integrated Development Environment with functionality such as the
18743 following
18745 @itemize @bullet
18746 @item
18747 ``Project files'' for configuration-specific aspects
18748 (e.g. directories and compilation options)
18750 @item
18751 Compiling and stepping through error messages.
18753 @item
18754 Running and debugging an applications within Glide.
18755 @end itemize
18757 @item
18758 Pull-down menus
18760 @item
18761 User configurability
18762 @end itemize
18764 Some of the specific Ada mode features are:
18766 @itemize @bullet
18767 @item
18768 Functions for easy and quick stepping through Ada code
18770 @item
18771 Getting cross reference information for identifiers (e.g., finding a
18772 defining occurrence)
18774 @item
18775 Displaying an index menu of types and subprograms, allowing
18776 direct selection for browsing
18778 @item
18779 Automatic color highlighting of the various Ada entities
18780 @end itemize
18782 Glide directly supports writing Ada code, via several facilities:
18784 @itemize @bullet
18785 @item
18786 Switching between spec and body files with possible
18787 autogeneration of body files
18789 @item
18790 Automatic formating of subprogram parameter lists
18792 @item
18793 Automatic indentation according to Ada syntax
18795 @item
18796 Automatic completion of identifiers
18798 @item
18799 Automatic (and configurable) casing of identifiers, keywords, and attributes
18801 @item
18802 Insertion of syntactic templates
18804 @item
18805 Block commenting / uncommenting
18806 @end itemize
18808 @noindent
18809 For more information, please refer to the online documentation
18810 available in the @code{Glide} @result{} @code{Help} menu.
18811 @end ifclear
18813 @node Converting Ada Files to html with gnathtml
18814 @section Converting Ada Files to HTML with @code{gnathtml}
18816 @noindent
18817 This @code{Perl} script allows Ada source files to be browsed using
18818 standard Web browsers. For installation procedure, see the section
18819 @xref{Installing gnathtml}.
18821 Ada reserved keywords are highlighted in a bold font and Ada comments in
18822 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
18823 switch to suppress the generation of cross-referencing information, user
18824 defined variables and types will appear in a different color; you will
18825 be able to click on any identifier and go to its declaration.
18827 The command line is as follow:
18828 @smallexample
18829 $ perl gnathtml.pl [switches] ada-files
18830 @end smallexample
18832 @noindent
18833 You can pass it as many Ada files as you want. @code{gnathtml} will generate
18834 an html file for every ada file, and a global file called @file{index.htm}.
18835 This file is an index of every identifier defined in the files.
18837 The available switches are the following ones :
18839 @table @option
18840 @item -83
18841 @cindex @option{-83} (@code{gnathtml})
18842 Only the subset on the Ada 83 keywords will be highlighted, not the full
18843 Ada 95 keywords set.
18845 @item -cc @var{color}
18846 @cindex @option{-cc} (@code{gnathtml})
18847 This option allows you to change the color used for comments. The default
18848 value is green. The color argument can be any name accepted by html.
18850 @item -d
18851 @cindex @option{-d} (@code{gnathtml})
18852 If the ada files depend on some other files (using for instance the
18853 @code{with} command, the latter will also be converted to html.
18854 Only the files in the user project will be converted to html, not the files
18855 in the run-time library itself.
18857 @item -D
18858 @cindex @option{-D} (@code{gnathtml})
18859 This command is the same as @option{-d} above, but @command{gnathtml} will
18860 also look for files in the run-time library, and generate html files for them.
18862 @item -ext @var{extension}
18863 @cindex @option{-ext} (@code{gnathtml})
18864 This option allows you to change the extension of the generated HTML files.
18865 If you do not specify an extension, it will default to @file{htm}.
18867 @item -f
18868 @cindex @option{-f} (@code{gnathtml})
18869 By default, gnathtml will generate html links only for global entities
18870 ('with'ed units, global variables and types,...). If you specify the
18871 @option{-f} on the command line, then links will be generated for local
18872 entities too.
18874 @item -l @var{number}
18875 @cindex @option{-l} (@code{gnathtml})
18876 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
18877 will number the html files every @var{number} line.
18879 @item -I @var{dir}
18880 @cindex @option{-I} (@code{gnathtml})
18881 Specify a directory to search for library files (@file{.ALI} files) and
18882 source files. You can provide several -I switches on the command line,
18883 and the directories will be parsed in the order of the command line.
18885 @item -o @var{dir}
18886 @cindex @option{-o} (@code{gnathtml})
18887 Specify the output directory for html files. By default, gnathtml will
18888 saved the generated html files in a subdirectory named @file{html/}.
18890 @item -p @var{file}
18891 @cindex @option{-p} (@code{gnathtml})
18892 If you are using Emacs and the most recent Emacs Ada mode, which provides
18893 a full Integrated Development Environment for compiling, checking,
18894 running and debugging applications, you may use @file{.gpr} files
18895 to give the directories where Emacs can find sources and object files.
18897 Using this switch, you can tell gnathtml to use these files. This allows
18898 you to get an html version of your application, even if it is spread
18899 over multiple directories.
18901 @item -sc @var{color}
18902 @cindex @option{-sc} (@code{gnathtml})
18903 This option allows you to change the color used for symbol definitions.
18904 The default value is red. The color argument can be any name accepted by html.
18906 @item -t @var{file}
18907 @cindex @option{-t} (@code{gnathtml})
18908 This switch provides the name of a file. This file contains a list of
18909 file names to be converted, and the effect is exactly as though they had
18910 appeared explicitly on the command line. This
18911 is the recommended way to work around the command line length limit on some
18912 systems.
18914 @end table
18916 @node Installing gnathtml
18917 @section Installing @code{gnathtml}
18919 @noindent
18920 @code{Perl} needs to be installed on your machine to run this script.
18921 @code{Perl} is freely available for almost every architecture and
18922 Operating System via the Internet.
18924 On Unix systems, you  may want to modify  the  first line of  the script
18925 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
18926 is. The syntax of this line is :
18927 @smallexample
18928 #!full_path_name_to_perl
18929 @end smallexample
18931 @noindent
18932 Alternatively, you may run the script using the following command line:
18934 @smallexample
18935 $ perl gnathtml.pl [switches] files
18936 @end smallexample
18938 @ifset vms
18939 @node LSE
18940 @section LSE
18941 @findex LSE
18943 @noindent
18944 The GNAT distribution provides an Ada 95 template for the Digital Language
18945 Sensitive Editor (LSE), a component of DECset. In order to
18946 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
18948 @node Profiling
18949 @section Profiling
18950 @findex PCA
18952 @noindent
18953 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
18954 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
18955 the collection phase with the /DEBUG qualifier.
18957 @smallexample
18958 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
18959 $ DEFINE LIB$DEBUG PCA$COLLECTOR
18960 $ RUN/DEBUG <PROGRAM_NAME>
18961 @end smallexample
18962 @noindent
18963 @end ifset
18965 @node Running and Debugging Ada Programs
18966 @chapter Running and Debugging Ada Programs
18967 @cindex Debugging
18969 @noindent
18970 This chapter discusses how to debug Ada programs.
18971 @ifset vms
18972 It applies to the Alpha OpenVMS platform;
18973 the debugger for Integrity OpenVMS is scheduled for a subsequent release.
18974 @end ifset
18976 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18978 @enumerate
18979 @item
18980 The illegality may be a violation of the static semantics of Ada. In
18981 that case GNAT diagnoses the constructs in the program that are illegal.
18982 It is then a straightforward matter for the user to modify those parts of
18983 the program.
18985 @item
18986 The illegality may be a violation of the dynamic semantics of Ada. In
18987 that case the program compiles and executes, but may generate incorrect
18988 results, or may terminate abnormally with some exception.
18990 @item
18991 When presented with a program that contains convoluted errors, GNAT
18992 itself may terminate abnormally without providing full diagnostics on
18993 the incorrect user program.
18994 @end enumerate
18996 @menu
18997 * The GNAT Debugger GDB::
18998 * Running GDB::
18999 * Introduction to GDB Commands::
19000 * Using Ada Expressions::
19001 * Calling User-Defined Subprograms::
19002 * Using the Next Command in a Function::
19003 * Ada Exceptions::
19004 * Ada Tasks::
19005 * Debugging Generic Units::
19006 * GNAT Abnormal Termination or Failure to Terminate::
19007 * Naming Conventions for GNAT Source Files::
19008 * Getting Internal Debugging Information::
19009 * Stack Traceback::
19010 @end menu
19012 @cindex Debugger
19013 @findex gdb
19015 @node The GNAT Debugger GDB
19016 @section The GNAT Debugger GDB
19018 @noindent
19019 @code{GDB} is a general purpose, platform-independent debugger that
19020 can be used to debug mixed-language programs compiled with @command{gcc},
19021 and in particular is capable of debugging Ada programs compiled with
19022 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19023 complex Ada data structures.
19025 The manual @cite{Debugging with GDB}
19026 @ifset vms
19027 , located in the GNU:[DOCS] directory,
19028 @end ifset
19029 contains full details on the usage of @code{GDB}, including a section on
19030 its usage on programs. This manual should be consulted for full
19031 details. The section that follows is a brief introduction to the
19032 philosophy and use of @code{GDB}.
19034 When GNAT programs are compiled, the compiler optionally writes debugging
19035 information into the generated object file, including information on
19036 line numbers, and on declared types and variables. This information is
19037 separate from the generated code. It makes the object files considerably
19038 larger, but it does not add to the size of the actual executable that
19039 will be loaded into memory, and has no impact on run-time performance. The
19040 generation of debug information is triggered by the use of the
19041 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
19042 the compilations. It is important to emphasize that the use of these
19043 options does not change the generated code.
19045 The debugging information is written in standard system formats that
19046 are used by many tools, including debuggers and profilers. The format
19047 of the information is typically designed to describe C types and
19048 semantics, but GNAT implements a translation scheme which allows full
19049 details about Ada types and variables to be encoded into these
19050 standard C formats. Details of this encoding scheme may be found in
19051 the file exp_dbug.ads in the GNAT source distribution. However, the
19052 details of this encoding are, in general, of no interest to a user,
19053 since @code{GDB} automatically performs the necessary decoding.
19055 When a program is bound and linked, the debugging information is
19056 collected from the object files, and stored in the executable image of
19057 the program. Again, this process significantly increases the size of
19058 the generated executable file, but it does not increase the size of
19059 the executable program itself. Furthermore, if this program is run in
19060 the normal manner, it runs exactly as if the debug information were
19061 not present, and takes no more actual memory.
19063 However, if the program is run under control of @code{GDB}, the
19064 debugger is activated.  The image of the program is loaded, at which
19065 point it is ready to run.  If a run command is given, then the program
19066 will run exactly as it would have if @code{GDB} were not present. This
19067 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19068 entirely non-intrusive until a breakpoint is encountered.  If no
19069 breakpoint is ever hit, the program will run exactly as it would if no
19070 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19071 the debugging information and can respond to user commands to inspect
19072 variables, and more generally to report on the state of execution.
19074 @c **************
19075 @node Running GDB
19076 @section Running GDB
19078 @noindent
19079 The debugger can be launched directly and simply from @code{glide} or
19080 through its graphical interface: @code{gvd}. It can also be used
19081 directly in text mode. Here is described the basic use of @code{GDB}
19082 in text mode. All the commands described below can be used in the
19083 @code{gvd} console window even though there is usually other more
19084 graphical ways to achieve the same goals.
19086 @ifclear vms
19087 @noindent
19088 The command to run the graphical interface of the debugger is
19089 @smallexample
19090 $ gvd program
19091 @end smallexample
19092 @end ifclear
19094 @noindent
19095 The command to run @code{GDB} in text mode is
19097 @smallexample
19098 $ ^gdb program^$ GDB PROGRAM^
19099 @end smallexample
19101 @noindent
19102 where @code{^program^PROGRAM^} is the name of the executable file. This
19103 activates the debugger and results in a prompt for debugger commands.
19104 The simplest command is simply @code{run}, which causes the program to run
19105 exactly as if the debugger were not present. The following section
19106 describes some of the additional commands that can be given to @code{GDB}.
19108 @c *******************************
19109 @node Introduction to GDB Commands
19110 @section Introduction to GDB Commands
19112 @noindent
19113 @code{GDB} contains a large repertoire of commands. The manual
19114 @cite{Debugging with GDB}
19115 @ifset vms
19116 , located in the GNU:[DOCS] directory,
19117 @end ifset
19118 includes extensive documentation on the use
19119 of these commands, together with examples of their use. Furthermore,
19120 the command @var{help} invoked from within @code{GDB} activates a simple help
19121 facility which summarizes the available commands and their options.
19122 In this section we summarize a few of the most commonly
19123 used commands to give an idea of what @code{GDB} is about. You should create
19124 a simple program with debugging information and experiment with the use of
19125 these @code{GDB} commands on the program as you read through the
19126 following section.
19128 @table @code
19129 @item set args @var{arguments}
19130 The @var{arguments} list above is a list of arguments to be passed to
19131 the program on a subsequent run command, just as though the arguments
19132 had been entered on a normal invocation of the program. The @code{set args}
19133 command is not needed if the program does not require arguments.
19135 @item run
19136 The @code{run} command causes execution of the program to start from
19137 the beginning. If the program is already running, that is to say if
19138 you are currently positioned at a breakpoint, then a prompt will ask
19139 for confirmation that you want to abandon the current execution and
19140 restart.
19142 @item breakpoint @var{location}
19143 The breakpoint command sets a breakpoint, that is to say a point at which
19144 execution will halt and @code{GDB} will await further
19145 commands. @var{location} is
19146 either a line number within a file, given in the format @code{file:linenumber},
19147 or it is the name of a subprogram. If you request that a breakpoint be set on
19148 a subprogram that is overloaded, a prompt will ask you to specify on which of
19149 those subprograms you want to breakpoint. You can also
19150 specify that all of them should be breakpointed. If the program is run
19151 and execution encounters the breakpoint, then the program
19152 stops and @code{GDB} signals that the breakpoint was encountered by
19153 printing the line of code before which the program is halted.
19155 @item breakpoint exception @var{name}
19156 A special form of the breakpoint command which breakpoints whenever
19157 exception @var{name} is raised.
19158 If @var{name} is omitted,
19159 then a breakpoint will occur when any exception is raised.
19161 @item print @var{expression}
19162 This will print the value of the given expression. Most simple
19163 Ada expression formats are properly handled by @code{GDB}, so the expression
19164 can contain function calls, variables, operators, and attribute references.
19166 @item continue
19167 Continues execution following a breakpoint, until the next breakpoint or the
19168 termination of the program.
19170 @item step
19171 Executes a single line after a breakpoint. If the next statement
19172 is a subprogram call, execution continues into (the first statement of)
19173 the called subprogram.
19175 @item next
19176 Executes a single line. If this line is a subprogram call, executes and
19177 returns from the call.
19179 @item list
19180 Lists a few lines around the current source location. In practice, it
19181 is usually more convenient to have a separate edit window open with the
19182 relevant source file displayed. Successive applications of this command
19183 print subsequent lines. The command can be given an argument which is a
19184 line number, in which case it displays a few lines around the specified one.
19186 @item backtrace
19187 Displays a backtrace of the call chain. This command is typically
19188 used after a breakpoint has occurred, to examine the sequence of calls that
19189 leads to the current breakpoint. The display includes one line for each
19190 activation record (frame) corresponding to an active subprogram.
19192 @item up
19193 At a breakpoint, @code{GDB} can display the values of variables local
19194 to the current frame. The command @code{up} can be used to
19195 examine the contents of other active frames, by moving the focus up
19196 the stack, that is to say from callee to caller, one frame at a time.
19198 @item down
19199 Moves the focus of @code{GDB} down from the frame currently being
19200 examined to the frame of its callee (the reverse of the previous command),
19202 @item frame @var{n}
19203 Inspect the frame with the given number. The value 0 denotes the frame
19204 of the current breakpoint, that is to say the top of the call stack.
19206 @end table
19208 The above list is a very short introduction to the commands that
19209 @code{GDB} provides. Important additional capabilities, including conditional
19210 breakpoints, the ability to execute command sequences on a breakpoint,
19211 the ability to debug at the machine instruction level and many other
19212 features are described in detail in @cite{Debugging with GDB}.
19213 Note that most commands can be abbreviated
19214 (for example, c for continue, bt for backtrace).
19216 @node Using Ada Expressions
19217 @section Using Ada Expressions
19218 @cindex Ada expressions
19220 @noindent
19221 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19222 extensions. The philosophy behind the design of this subset is
19224 @itemize @bullet
19225 @item
19226 That @code{GDB} should provide basic literals and access to operations for
19227 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19228 leaving more sophisticated computations to subprograms written into the
19229 program (which therefore may be called from @code{GDB}).
19231 @item
19232 That type safety and strict adherence to Ada language restrictions
19233 are not particularly important to the @code{GDB} user.
19235 @item
19236 That brevity is important to the @code{GDB} user.
19237 @end itemize
19239 Thus, for brevity, the debugger acts as if there were
19240 implicit @code{with} and @code{use} clauses in effect for all user-written
19241 packages, thus making it unnecessary to fully qualify most names with
19242 their packages, regardless of context. Where this causes ambiguity,
19243 @code{GDB} asks the user's intent.
19245 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19247 @node Calling User-Defined Subprograms
19248 @section Calling User-Defined Subprograms
19250 @noindent
19251 An important capability of @code{GDB} is the ability to call user-defined
19252 subprograms while debugging. This is achieved simply by entering
19253 a subprogram call statement in the form:
19255 @smallexample
19256 call subprogram-name (parameters)
19257 @end smallexample
19259 @noindent
19260 The keyword @code{call} can be omitted in the normal case where the
19261 @code{subprogram-name} does not coincide with any of the predefined
19262 @code{GDB} commands.
19264 The effect is to invoke the given subprogram, passing it the
19265 list of parameters that is supplied. The parameters can be expressions and
19266 can include variables from the program being debugged. The
19267 subprogram must be defined
19268 at the library level within your program, and @code{GDB} will call the
19269 subprogram within the environment of your program execution (which
19270 means that the subprogram is free to access or even modify variables
19271 within your program).
19273 The most important use of this facility is in allowing the inclusion of
19274 debugging routines that are tailored to particular data structures
19275 in your program. Such debugging routines can be written to provide a suitably
19276 high-level description of an abstract type, rather than a low-level dump
19277 of its physical layout. After all, the standard
19278 @code{GDB print} command only knows the physical layout of your
19279 types, not their abstract meaning. Debugging routines can provide information
19280 at the desired semantic level and are thus enormously useful.
19282 For example, when debugging GNAT itself, it is crucial to have access to
19283 the contents of the tree nodes used to represent the program internally.
19284 But tree nodes are represented simply by an integer value (which in turn
19285 is an index into a table of nodes).
19286 Using the @code{print} command on a tree node would simply print this integer
19287 value, which is not very useful. But the PN routine (defined in file
19288 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19289 a useful high level representation of the tree node, which includes the
19290 syntactic category of the node, its position in the source, the integers
19291 that denote descendant nodes and parent node, as well as varied
19292 semantic information. To study this example in more detail, you might want to
19293 look at the body of the PN procedure in the stated file.
19295 @node Using the Next Command in a Function
19296 @section Using the Next Command in a Function
19298 @noindent
19299 When you use the @code{next} command in a function, the current source
19300 location will advance to the next statement as usual. A special case
19301 arises in the case of a @code{return} statement.
19303 Part of the code for a return statement is the ``epilog'' of the function.
19304 This is the code that returns to the caller. There is only one copy of
19305 this epilog code, and it is typically associated with the last return
19306 statement in the function if there is more than one return. In some
19307 implementations, this epilog is associated with the first statement
19308 of the function.
19310 The result is that if you use the @code{next} command from a return
19311 statement that is not the last return statement of the function you
19312 may see a strange apparent jump to the last return statement or to
19313 the start of the function. You should simply ignore this odd jump.
19314 The value returned is always that from the first return statement
19315 that was stepped through.
19317 @node Ada Exceptions
19318 @section Breaking on Ada Exceptions
19319 @cindex Exceptions
19321 @noindent
19322 You can set breakpoints that trip when your program raises
19323 selected exceptions.
19325 @table @code
19326 @item break exception
19327 Set a breakpoint that trips whenever (any task in the) program raises
19328 any exception.
19330 @item break exception @var{name}
19331 Set a breakpoint that trips whenever (any task in the) program raises
19332 the exception @var{name}.
19334 @item break exception unhandled
19335 Set a breakpoint that trips whenever (any task in the) program raises an
19336 exception for which there is no handler.
19338 @item info exceptions
19339 @itemx info exceptions @var{regexp}
19340 The @code{info exceptions} command permits the user to examine all defined
19341 exceptions within Ada programs. With a regular expression, @var{regexp}, as
19342 argument, prints out only those exceptions whose name matches @var{regexp}.
19343 @end table
19345 @node Ada Tasks
19346 @section Ada Tasks
19347 @cindex Tasks
19349 @noindent
19350 @code{GDB} allows the following task-related commands:
19352 @table @code
19353 @item info tasks
19354 This command shows a list of current Ada tasks, as in the following example:
19356 @smallexample
19357 @iftex
19358 @leftskip=0cm
19359 @end iftex
19360 (gdb) info tasks
19361   ID       TID P-ID   Thread Pri State                 Name
19362    1   8088000   0   807e000  15 Child Activation Wait main_task
19363    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19364    3   809a800   1   80a4800  15 Child Activation Wait a
19365 *  4   80ae800   3   80b8000  15 Running               c
19366 @end smallexample
19368 @noindent
19369 In this listing, the asterisk before the first task indicates it to be the
19370 currently running task. The first column lists the task ID that is used
19371 to refer to tasks in the following commands.
19373 @item break @var{linespec} task @var{taskid}
19374 @itemx break @var{linespec} task @var{taskid} if @dots{}
19375 @cindex Breakpoints and tasks
19376 These commands are like the @code{break @dots{} thread @dots{}}.
19377 @var{linespec} specifies source lines.
19379 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
19380 to specify that you only want @code{GDB} to stop the program when a
19381 particular Ada task reaches this breakpoint. @var{taskid} is one of the
19382 numeric task identifiers assigned by @code{GDB}, shown in the first
19383 column of the @samp{info tasks} display.
19385 If you do not specify @samp{task @var{taskid}} when you set a
19386 breakpoint, the breakpoint applies to @emph{all} tasks of your
19387 program.
19389 You can use the @code{task} qualifier on conditional breakpoints as
19390 well; in this case, place @samp{task @var{taskid}} before the
19391 breakpoint condition (before the @code{if}).
19393 @item task @var{taskno}
19394 @cindex Task switching
19396 This command allows to switch to the task referred by @var{taskno}. In
19397 particular, This allows to browse the backtrace of the specified
19398 task. It is advised to switch back to the original task before
19399 continuing execution otherwise the scheduling of the program may be
19400 perturbated.
19401 @end table
19403 @noindent
19404 For more detailed information on the tasking support,
19405 see @cite{Debugging with GDB}.
19407 @node Debugging Generic Units
19408 @section Debugging Generic Units
19409 @cindex Debugging Generic Units
19410 @cindex Generics
19412 @noindent
19413 GNAT always uses code expansion for generic instantiation. This means that
19414 each time an instantiation occurs, a complete copy of the original code is
19415 made, with appropriate substitutions of formals by actuals.
19417 It is not possible to refer to the original generic entities in
19418 @code{GDB}, but it is always possible to debug a particular instance of
19419 a generic, by using the appropriate expanded names. For example, if we have
19421 @smallexample @c ada
19422 @group
19423 @cartouche
19424 procedure g is
19426    generic package k is
19427       procedure kp (v1 : in out integer);
19428    end k;
19430    package body k is
19431       procedure kp (v1 : in out integer) is
19432       begin
19433          v1 := v1 + 1;
19434       end kp;
19435    end k;
19437    package k1 is new k;
19438    package k2 is new k;
19440    var : integer := 1;
19442 begin
19443    k1.kp (var);
19444    k2.kp (var);
19445    k1.kp (var);
19446    k2.kp (var);
19447 end;
19448 @end cartouche
19449 @end group
19450 @end smallexample
19452 @noindent
19453 Then to break on a call to procedure kp in the k2 instance, simply
19454 use the command:
19456 @smallexample
19457 (gdb) break g.k2.kp
19458 @end smallexample
19460 @noindent
19461 When the breakpoint occurs, you can step through the code of the
19462 instance in the normal manner and examine the values of local variables, as for
19463 other units.
19465 @node GNAT Abnormal Termination or Failure to Terminate
19466 @section GNAT Abnormal Termination or Failure to Terminate
19467 @cindex GNAT Abnormal Termination or Failure to Terminate
19469 @noindent
19470 When presented with programs that contain serious errors in syntax
19471 or semantics,
19472 GNAT may on rare occasions  experience problems in operation, such
19473 as aborting with a
19474 segmentation fault or illegal memory access, raising an internal
19475 exception, terminating abnormally, or failing to terminate at all.
19476 In such cases, you can activate
19477 various features of GNAT that can help you pinpoint the construct in your
19478 program that is the likely source of the problem.
19480 The following strategies are presented in increasing order of
19481 difficulty, corresponding to your experience in using GNAT and your
19482 familiarity with compiler internals.
19484 @enumerate
19485 @item
19486 Run @command{gcc} with the @option{-gnatf}. This first
19487 switch causes all errors on a given line to be reported. In its absence,
19488 only the first error on a line is displayed.
19490 The @option{-gnatdO} switch causes errors to be displayed as soon as they
19491 are encountered, rather than after compilation is terminated. If GNAT
19492 terminates prematurely or goes into an infinite loop, the last error
19493 message displayed may help to pinpoint the culprit.
19495 @item
19496 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
19497 mode, @command{gcc} produces ongoing information about the progress of the
19498 compilation and provides the name of each procedure as code is
19499 generated. This switch allows you to find which Ada procedure was being
19500 compiled when it encountered a code generation problem.
19502 @item
19503 @cindex @option{-gnatdc} switch
19504 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
19505 switch that does for the front-end what @option{^-v^VERBOSE^} does
19506 for the back end. The system prints the name of each unit,
19507 either a compilation unit or nested unit, as it is being analyzed.
19508 @item
19509 Finally, you can start
19510 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19511 front-end of GNAT, and can be run independently (normally it is just
19512 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
19513 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
19514 @code{where} command is the first line of attack; the variable
19515 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19516 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
19517 which the execution stopped, and @code{input_file name} indicates the name of
19518 the source file.
19519 @end enumerate
19521 @node Naming Conventions for GNAT Source Files
19522 @section Naming Conventions for GNAT Source Files
19524 @noindent
19525 In order to examine the workings of the GNAT system, the following
19526 brief description of its organization may be helpful:
19528 @itemize @bullet
19529 @item
19530 Files with prefix @file{^sc^SC^} contain the lexical scanner.
19532 @item
19533 All files prefixed with @file{^par^PAR^} are components of the parser. The
19534 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
19535 parsing of select statements can be found in @file{par-ch9.adb}.
19537 @item
19538 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
19539 numbers correspond to chapters of the Ada standard. For example, all
19540 issues involving context clauses can be found in @file{sem_ch10.adb}. In
19541 addition, some features of the language require sufficient special processing
19542 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19543 dynamic dispatching, etc.
19545 @item
19546 All files prefixed with @file{^exp^EXP^} perform normalization and
19547 expansion of the intermediate representation (abstract syntax tree, or AST).
19548 these files use the same numbering scheme as the parser and semantics files.
19549 For example, the construction of record initialization procedures is done in
19550 @file{exp_ch3.adb}.
19552 @item
19553 The files prefixed with @file{^bind^BIND^} implement the binder, which
19554 verifies the consistency of the compilation, determines an order of
19555 elaboration, and generates the bind file.
19557 @item
19558 The files @file{atree.ads} and @file{atree.adb} detail the low-level
19559 data structures used by the front-end.
19561 @item
19562 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
19563 the abstract syntax tree as produced by the parser.
19565 @item
19566 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
19567 all entities, computed during semantic analysis.
19569 @item
19570 Library management issues are dealt with in files with prefix
19571 @file{^lib^LIB^}.
19573 @item
19574 @findex Ada
19575 @cindex Annex A
19576 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
19577 defined in Annex A.
19579 @item
19580 @findex Interfaces
19581 @cindex Annex B
19582 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
19583 defined in Annex B.
19585 @item
19586 @findex System
19587 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
19588 both language-defined children and GNAT run-time routines.
19590 @item
19591 @findex GNAT
19592 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
19593 general-purpose packages, fully documented in their specifications. All
19594 the other @file{.c} files are modifications of common @command{gcc} files.
19595 @end itemize
19597 @node Getting Internal Debugging Information
19598 @section Getting Internal Debugging Information
19600 @noindent
19601 Most compilers have internal debugging switches and modes. GNAT
19602 does also, except GNAT internal debugging switches and modes are not
19603 secret. A summary and full description of all the compiler and binder
19604 debug flags are in the file @file{debug.adb}. You must obtain the
19605 sources of the compiler to see the full detailed effects of these flags.
19607 The switches that print the source of the program (reconstructed from
19608 the internal tree) are of general interest for user programs, as are the
19609 options to print
19610 the full internal tree, and the entity table (the symbol table
19611 information). The reconstructed source provides a readable version of the
19612 program after the front-end has completed analysis and  expansion,
19613 and is useful when studying the performance of specific constructs.
19614 For example, constraint checks are indicated, complex aggregates
19615 are replaced with loops and assignments, and tasking primitives
19616 are replaced with run-time calls.
19618 @node Stack Traceback
19619 @section Stack Traceback
19620 @cindex traceback
19621 @cindex stack traceback
19622 @cindex stack unwinding
19624 @noindent
19625 Traceback is a mechanism to display the sequence of subprogram calls that
19626 leads to a specified execution point in a program. Often (but not always)
19627 the execution point is an instruction at which an exception has been raised.
19628 This mechanism is also known as @i{stack unwinding} because it obtains
19629 its information by scanning the run-time stack and recovering the activation
19630 records of all active subprograms. Stack unwinding is one of the most
19631 important tools for program debugging.
19633 The first entry stored in traceback corresponds to the deepest calling level,
19634 that is to say the subprogram currently executing the instruction
19635 from which we want to obtain the traceback.
19637 Note that there is no runtime performance penalty when stack traceback
19638 is enabled, and no exception is raised during program execution.
19640 @menu
19641 * Non-Symbolic Traceback::
19642 * Symbolic Traceback::
19643 @end menu
19645 @node Non-Symbolic Traceback
19646 @subsection Non-Symbolic Traceback
19647 @cindex traceback, non-symbolic
19649 @noindent
19650 Note: this feature is not supported on all platforms. See
19651 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
19652 platforms.
19654 @menu
19655 * Tracebacks From an Unhandled Exception::
19656 * Tracebacks From Exception Occurrences (non-symbolic)::
19657 * Tracebacks From Anywhere in a Program (non-symbolic)::
19658 @end menu
19660 @node Tracebacks From an Unhandled Exception
19661 @subsubsection Tracebacks From an Unhandled Exception
19663 @noindent
19664 A runtime non-symbolic traceback is a list of addresses of call instructions.
19665 To enable this feature you must use the @option{-E}
19666 @code{gnatbind}'s option. With this option a stack traceback is stored as part
19667 of exception information. You can retrieve this information using the
19668 @code{addr2line} tool.
19670 Here is a simple example:
19672 @smallexample @c ada
19673 @cartouche
19674 procedure STB is
19676    procedure P1 is
19677    begin
19678       raise Constraint_Error;
19679    end P1;
19681    procedure P2 is
19682    begin
19683       P1;
19684    end P2;
19686 begin
19687    P2;
19688 end STB;
19689 @end cartouche
19690 @end smallexample
19692 @smallexample
19693 $ gnatmake stb -bargs -E
19694 $ stb
19696 Execution terminated by unhandled exception
19697 Exception name: CONSTRAINT_ERROR
19698 Message: stb.adb:5
19699 Call stack traceback locations:
19700 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19701 @end smallexample
19703 @noindent
19704 As we see the traceback lists a sequence of addresses for the unhandled
19705 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19706 guess that this exception come from procedure P1. To translate these
19707 addresses into the source lines where the calls appear, the
19708 @code{addr2line} tool, described below, is invaluable. The use of this tool
19709 requires the program to be compiled with debug information.
19711 @smallexample
19712 $ gnatmake -g stb -bargs -E
19713 $ stb
19715 Execution terminated by unhandled exception
19716 Exception name: CONSTRAINT_ERROR
19717 Message: stb.adb:5
19718 Call stack traceback locations:
19719 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19721 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19722    0x4011f1 0x77e892a4
19724 00401373 at d:/stb/stb.adb:5
19725 0040138B at d:/stb/stb.adb:10
19726 0040139C at d:/stb/stb.adb:14
19727 00401335 at d:/stb/b~stb.adb:104
19728 004011C4 at /build/.../crt1.c:200
19729 004011F1 at /build/.../crt1.c:222
19730 77E892A4 in ?? at ??:0
19731 @end smallexample
19733 @noindent
19734 The @code{addr2line} tool has several other useful options:
19736 @table @code
19737 @item --functions
19738 to get the function name corresponding to any location
19740 @item --demangle=gnat
19741 to use the gnat decoding mode for the function names. Note that
19742 for binutils version 2.9.x the option is simply @option{--demangle}.
19743 @end table
19745 @smallexample
19746 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19747    0x40139c 0x401335 0x4011c4 0x4011f1
19749 00401373 in stb.p1 at d:/stb/stb.adb:5
19750 0040138B in stb.p2 at d:/stb/stb.adb:10
19751 0040139C in stb at d:/stb/stb.adb:14
19752 00401335 in main at d:/stb/b~stb.adb:104
19753 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19754 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19755 @end smallexample
19757 @noindent
19758 From this traceback we can see that the exception was raised in
19759 @file{stb.adb} at line 5, which was reached from a procedure call in
19760 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
19761 which contains the call to the main program.
19762 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
19763 and the output will vary from platform to platform.
19765 It is also possible to use @code{GDB} with these traceback addresses to debug
19766 the program. For example, we can break at a given code location, as reported
19767 in the stack traceback:
19769 @smallexample
19770 $ gdb -nw stb
19771 @ifclear vms
19772 @noindent
19773 Furthermore, this feature is not implemented inside Windows DLL. Only
19774 the non-symbolic traceback is reported in this case.
19775 @end ifclear
19777 (gdb) break *0x401373
19778 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19779 @end smallexample
19781 @noindent
19782 It is important to note that the stack traceback addresses
19783 do not change when debug information is included. This is particularly useful
19784 because it makes it possible to release software without debug information (to
19785 minimize object size), get a field report that includes a stack traceback
19786 whenever an internal bug occurs, and then be able to retrieve the sequence
19787 of calls with the same program compiled with debug information.
19789 @node Tracebacks From Exception Occurrences (non-symbolic)
19790 @subsubsection Tracebacks From Exception Occurrences
19792 @noindent
19793 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
19794 The stack traceback is attached to the exception information string, and can
19795 be retrieved in an exception handler within the Ada program, by means of the
19796 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19798 @smallexample @c ada
19799 with Ada.Text_IO;
19800 with Ada.Exceptions;
19802 procedure STB is
19804    use Ada;
19805    use Ada.Exceptions;
19807    procedure P1 is
19808       K : Positive := 1;
19809    begin
19810       K := K - 1;
19811    exception
19812       when E : others =>
19813          Text_IO.Put_Line (Exception_Information (E));
19814    end P1;
19816    procedure P2 is
19817    begin
19818       P1;
19819    end P2;
19821 begin
19822    P2;
19823 end STB;
19824 @end smallexample
19826 @noindent
19827 This program will output:
19829 @smallexample
19830 $ stb
19832 Exception name: CONSTRAINT_ERROR
19833 Message: stb.adb:12
19834 Call stack traceback locations:
19835 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19836 @end smallexample
19838 @node Tracebacks From Anywhere in a Program (non-symbolic)
19839 @subsubsection Tracebacks From Anywhere in a Program
19841 @noindent
19842 It is also possible to retrieve a stack traceback from anywhere in a
19843 program. For this you need to
19844 use the @code{GNAT.Traceback} API. This package includes a procedure called
19845 @code{Call_Chain} that computes a complete stack traceback, as well as useful
19846 display procedures described below. It is not necessary to use the
19847 @option{-E gnatbind} option in this case, because the stack traceback mechanism
19848 is invoked explicitly.
19850 @noindent
19851 In the following example we compute a traceback at a specific location in
19852 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
19853 convert addresses to strings:
19855 @smallexample @c ada
19856 with Ada.Text_IO;
19857 with GNAT.Traceback;
19858 with GNAT.Debug_Utilities;
19860 procedure STB is
19862    use Ada;
19863    use GNAT;
19864    use GNAT.Traceback;
19866    procedure P1 is
19867       TB  : Tracebacks_Array (1 .. 10);
19868       --  We are asking for a maximum of 10 stack frames.
19869       Len : Natural;
19870       --  Len will receive the actual number of stack frames returned.
19871    begin
19872       Call_Chain (TB, Len);
19874       Text_IO.Put ("In STB.P1 : ");
19876       for K in 1 .. Len loop
19877          Text_IO.Put (Debug_Utilities.Image (TB (K)));
19878          Text_IO.Put (' ');
19879       end loop;
19881       Text_IO.New_Line;
19882    end P1;
19884    procedure P2 is
19885    begin
19886       P1;
19887    end P2;
19889 begin
19890    P2;
19891 end STB;
19892 @end smallexample
19894 @smallexample
19895 $ gnatmake -g stb
19896 $ stb
19898 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
19899 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
19900 @end smallexample
19902 @noindent
19903 You can then get further information by invoking the @code{addr2line}
19904 tool as described earlier (note that the hexadecimal addresses
19905 need to be specified in C format, with a leading ``0x'').
19907 @node Symbolic Traceback
19908 @subsection Symbolic Traceback
19909 @cindex traceback, symbolic
19911 @noindent
19912 A symbolic traceback is a stack traceback in which procedure names are
19913 associated with each code location.
19915 @noindent
19916 Note that this feature is not supported on all platforms. See
19917 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
19918 list of currently supported platforms.
19920 @noindent
19921 Note that the symbolic traceback requires that the program be compiled
19922 with debug information. If it is not compiled with debug information
19923 only the non-symbolic information will be valid.
19925 @menu
19926 * Tracebacks From Exception Occurrences (symbolic)::
19927 * Tracebacks From Anywhere in a Program (symbolic)::
19928 @end menu
19930 @node Tracebacks From Exception Occurrences (symbolic)
19931 @subsubsection Tracebacks From Exception Occurrences
19933 @smallexample @c ada
19934 with Ada.Text_IO;
19935 with GNAT.Traceback.Symbolic;
19937 procedure STB is
19939    procedure P1 is
19940    begin
19941       raise Constraint_Error;
19942    end P1;
19944    procedure P2 is
19945    begin
19946       P1;
19947    end P2;
19949    procedure P3 is
19950    begin
19951       P2;
19952    end P3;
19954 begin
19955    P3;
19956 exception
19957    when E : others =>
19958       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19959 end STB;
19960 @end smallexample
19962 @smallexample
19963 $ gnatmake -g .\stb -bargs -E -largs -lgnat -laddr2line -lintl
19964 $ stb
19966 0040149F in stb.p1 at stb.adb:8
19967 004014B7 in stb.p2 at stb.adb:13
19968 004014CF in stb.p3 at stb.adb:18
19969 004015DD in ada.stb at stb.adb:22
19970 00401461 in main at b~stb.adb:168
19971 004011C4 in __mingw_CRTStartup at crt1.c:200
19972 004011F1 in mainCRTStartup at crt1.c:222
19973 77E892A4 in ?? at ??:0
19974 @end smallexample
19976 @noindent
19977 In the above example the ``.\'' syntax in the @command{gnatmake} command
19978 is currently required by @command{addr2line} for files that are in
19979 the current working directory.
19980 Moreover, the exact sequence of linker options may vary from platform
19981 to platform.
19982 The above @option{-largs} section is for Windows platforms. By contrast,
19983 under Unix there is no need for the @option{-largs} section.
19984 Differences across platforms are due to details of linker implementation.
19986 @node Tracebacks From Anywhere in a Program (symbolic)
19987 @subsubsection Tracebacks From Anywhere in a Program
19989 @noindent
19990 It is possible to get a symbolic stack traceback
19991 from anywhere in a program, just as for non-symbolic tracebacks.
19992 The first step is to obtain a non-symbolic
19993 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19994 information. Here is an example:
19996 @smallexample @c ada
19997 with Ada.Text_IO;
19998 with GNAT.Traceback;
19999 with GNAT.Traceback.Symbolic;
20001 procedure STB is
20003    use Ada;
20004    use GNAT.Traceback;
20005    use GNAT.Traceback.Symbolic;
20007    procedure P1 is
20008       TB  : Tracebacks_Array (1 .. 10);
20009       --  We are asking for a maximum of 10 stack frames.
20010       Len : Natural;
20011       --  Len will receive the actual number of stack frames returned.
20012    begin
20013       Call_Chain (TB, Len);
20014       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20015    end P1;
20017    procedure P2 is
20018    begin
20019       P1;
20020    end P2;
20022 begin
20023    P2;
20024 end STB;
20025 @end smallexample
20027 @ifset vms
20028 @node Compatibility with DEC Ada
20029 @chapter Compatibility with DEC Ada
20030 @cindex Compatibility
20032 @noindent
20033 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
20034 OpenVMS Alpha. GNAT achieves a high level of compatibility
20035 with DEC Ada, and it should generally be straightforward to port code
20036 from the DEC Ada environment to GNAT. However, there are a few language
20037 and implementation differences of which the user must be aware. These
20038 differences are discussed in this section. In
20039 addition, the operating environment and command structure for the
20040 compiler are different, and these differences are also discussed.
20042 Note that this discussion addresses specifically the implementation
20043 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
20044 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
20045 GNAT always follows the Alpha implementation.
20047 @menu
20048 * Ada 95 Compatibility::
20049 * Differences in the Definition of Package System::
20050 * Language-Related Features::
20051 * The Package STANDARD::
20052 * The Package SYSTEM::
20053 * Tasking and Task-Related Features::
20054 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
20055 * Pragmas and Pragma-Related Features::
20056 * Library of Predefined Units::
20057 * Bindings::
20058 * Main Program Definition::
20059 * Implementation-Defined Attributes::
20060 * Compiler and Run-Time Interfacing::
20061 * Program Compilation and Library Management::
20062 * Input-Output::
20063 * Implementation Limits::
20064 * Tools::
20065 @end menu
20067 @node Ada 95 Compatibility
20068 @section Ada 95 Compatibility
20070 @noindent
20071 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
20072 compiler. Ada 95 is almost completely upwards compatible
20073 with Ada 83, and therefore Ada 83 programs will compile
20074 and run under GNAT with
20075 no changes or only minor changes. The Ada 95 Reference
20076 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
20077 incompatibilities.
20079 GNAT provides the switch /83 on the GNAT COMPILE command,
20080 as well as the pragma ADA_83, to force the compiler to
20081 operate in Ada 83 mode. This mode does not guarantee complete
20082 conformance to Ada 83, but in practice is sufficient to
20083 eliminate most sources of incompatibilities.
20084 In particular, it eliminates the recognition of the
20085 additional Ada 95 keywords, so that their use as identifiers
20086 in Ada83 program is legal, and handles the cases of packages
20087 with optional bodies, and generics that instantiate unconstrained
20088 types without the use of @code{(<>)}.
20090 @node Differences in the Definition of Package System
20091 @section Differences in the Definition of Package System
20093 @noindent
20094 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
20095 implementation-dependent declarations to package System. In normal mode,
20096 GNAT does not take advantage of this permission, and the version of System
20097 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
20099 However, DEC Ada adds an extensive set of declarations to package System,
20100 as fully documented in the DEC Ada manuals. To minimize changes required
20101 for programs that make use of these extensions, GNAT provides the pragma
20102 Extend_System for extending the definition of package System. By using:
20104 @smallexample @c ada
20105 @group
20106 @cartouche
20107 pragma Extend_System (Aux_DEC);
20108 @end cartouche
20109 @end group
20110 @end smallexample
20112 @noindent
20113 The set of definitions in System is extended to include those in package
20114 @code{System.Aux_DEC}.
20115 These definitions are incorporated directly into package
20116 System, as though they had been declared there in the first place. For a
20117 list of the declarations added, see the specification of this package,
20118 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
20119 The pragma Extend_System is a configuration pragma, which means that
20120 it can be placed in the file @file{gnat.adc}, so that it will automatically
20121 apply to all subsequent compilations. See the section on Configuration
20122 Pragmas for further details.
20124 An alternative approach that avoids the use of the non-standard
20125 Extend_System pragma is to add a context clause to the unit that
20126 references these facilities:
20128 @smallexample @c ada
20129 @group
20130 @cartouche
20131 with System.Aux_DEC;
20132 use  System.Aux_DEC;
20133 @end cartouche
20134 @end group
20135 @end smallexample
20137 @noindent
20138 The effect is not quite semantically identical to incorporating
20139 the declarations directly into package @code{System},
20140 but most programs will not notice a difference
20141 unless they use prefix notation (e.g. @code{System.Integer_8})
20142 to reference the
20143 entities directly in package @code{System}.
20144 For units containing such references,
20145 the prefixes must either be removed, or the pragma @code{Extend_System}
20146 must be used.
20148 @node Language-Related Features
20149 @section Language-Related Features
20151 @noindent
20152 The following sections highlight differences in types,
20153 representations of types, operations, alignment, and
20154 related topics.
20156 @menu
20157 * Integer Types and Representations::
20158 * Floating-Point Types and Representations::
20159 * Pragmas Float_Representation and Long_Float::
20160 * Fixed-Point Types and Representations::
20161 * Record and Array Component Alignment::
20162 * Address Clauses::
20163 * Other Representation Clauses::
20164 @end menu
20166 @node Integer Types and Representations
20167 @subsection Integer Types and Representations
20169 @noindent
20170 The set of predefined integer types is identical in DEC Ada and GNAT.
20171 Furthermore the representation of these integer types is also identical,
20172 including the capability of size clauses forcing biased representation.
20174 In addition,
20175 DEC Ada for OpenVMS Alpha systems has defined the
20176 following additional integer types in package System:
20178 @itemize @bullet
20180 @item
20181 INTEGER_8
20183 @item
20184 INTEGER_16
20186 @item
20187 INTEGER_32
20189 @item
20190 INTEGER_64
20192 @item
20193 LARGEST_INTEGER
20194 @end itemize
20196 @noindent
20197 When using GNAT, the first four of these types may be obtained from the
20198 standard Ada 95 package @code{Interfaces}.
20199 Alternatively, by use of the pragma
20200 @code{Extend_System}, identical
20201 declarations can be referenced directly in package @code{System}.
20202 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
20204 @node Floating-Point Types and Representations
20205 @subsection Floating-Point Types and Representations
20206 @cindex Floating-Point types
20208 @noindent
20209 The set of predefined floating-point types is identical in DEC Ada and GNAT.
20210 Furthermore the representation of these floating-point
20211 types is also identical. One important difference is that the default
20212 representation for DEC Ada is VAX_Float, but the default representation
20213 for GNAT is IEEE.
20215 Specific types may be declared to be VAX_Float or IEEE, using the pragma
20216 @code{Float_Representation} as described in the DEC Ada documentation.
20217 For example, the declarations:
20219 @smallexample @c ada
20220 @group
20221 @cartouche
20222 type F_Float is digits 6;
20223 pragma Float_Representation (VAX_Float, F_Float);
20224 @end cartouche
20225 @end group
20226 @end smallexample
20228 @noindent
20229 declare a type F_Float that will be represented in VAX_Float format.
20230 This set of declarations actually appears in System.Aux_DEC, which provides
20231 the full set of additional floating-point declarations provided in
20232 the DEC Ada version of package
20233 System. This and similar declarations may be accessed in a user program
20234 by using pragma @code{Extend_System}. The use of this
20235 pragma, and the related pragma @code{Long_Float} is described in further
20236 detail in the following section.
20238 @node Pragmas Float_Representation and Long_Float
20239 @subsection Pragmas Float_Representation and Long_Float
20241 @noindent
20242 DEC Ada provides the pragma @code{Float_Representation}, which
20243 acts as a program library switch to allow control over
20244 the internal representation chosen for the predefined
20245 floating-point types declared in the package @code{Standard}.
20246 The format of this pragma is as follows:
20248 @smallexample
20249 @group
20250 @cartouche
20251 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
20252 @end cartouche
20253 @end group
20254 @end smallexample
20256 @noindent
20257 This pragma controls the representation of floating-point
20258 types as follows:
20260 @itemize @bullet
20261 @item
20262 @code{VAX_Float} specifies that floating-point
20263 types are represented by default with the VAX hardware types
20264 F-floating, D-floating, G-floating. Note that the H-floating
20265 type is available only on DIGITAL Vax systems, and is not available
20266 in either DEC Ada or GNAT for Alpha systems.
20268 @item
20269 @code{IEEE_Float} specifies that floating-point
20270 types are represented by default with the IEEE single and
20271 double floating-point types.
20272 @end itemize
20274 @noindent
20275 GNAT provides an identical implementation of the pragma
20276 @code{Float_Representation}, except that it functions as a
20277 configuration pragma, as defined by Ada 95. Note that the
20278 notion of configuration pragma corresponds closely to the
20279 DEC Ada notion of a program library switch.
20281 When no pragma is used in GNAT, the default is IEEE_Float, which is different
20282 from DEC Ada 83, where the default is VAX_Float. In addition, the
20283 predefined libraries in GNAT are built using IEEE_Float, so it is not
20284 advisable to change the format of numbers passed to standard library
20285 routines, and if necessary explicit type conversions may be needed.
20287 The use of IEEE_Float is recommended in GNAT since it is more efficient,
20288 and (given that it conforms to an international standard) potentially more
20289 portable. The situation in which VAX_Float may be useful is in interfacing
20290 to existing code and data that expects the use of VAX_Float. There are
20291 two possibilities here. If the requirement for the use of VAX_Float is
20292 localized, then the best approach is to use the predefined VAX_Float
20293 types in package @code{System}, as extended by
20294 @code{Extend_System}. For example, use @code{System.F_Float}
20295 to specify the 32-bit @code{F-Float} format.
20297 Alternatively, if an entire program depends heavily on the use of
20298 the @code{VAX_Float} and in particular assumes that the types in
20299 package @code{Standard} are in @code{Vax_Float} format, then it
20300 may be desirable to reconfigure GNAT to assume Vax_Float by default.
20301 This is done by using the GNAT LIBRARY command to rebuild the library, and
20302 then using the general form of the @code{Float_Representation}
20303 pragma to ensure that this default format is used throughout.
20304 The form of the GNAT LIBRARY command is:
20306 @smallexample
20307 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
20308 @end smallexample
20310 @noindent
20311 where @i{file} contains the new configuration pragmas
20312 and @i{directory} is the directory to be created to contain
20313 the new library.
20315 @noindent
20316 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
20317 to allow control over the internal representation chosen
20318 for the predefined type @code{Long_Float} and for floating-point
20319 type declarations with digits specified in the range 7 .. 15.
20320 The format of this pragma is as follows:
20322 @smallexample @c ada
20323 @cartouche
20324 pragma Long_Float (D_FLOAT | G_FLOAT);
20325 @end cartouche
20326 @end smallexample
20328 @node Fixed-Point Types and Representations
20329 @subsection Fixed-Point Types and Representations
20331 @noindent
20332 On DEC Ada for OpenVMS Alpha systems, rounding is
20333 away from zero for both positive and negative numbers.
20334 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
20336 On GNAT for OpenVMS Alpha, the results of operations
20337 on fixed-point types are in accordance with the Ada 95
20338 rules. In particular, results of operations on decimal
20339 fixed-point types are truncated.
20341 @node Record and Array Component Alignment
20342 @subsection Record and Array Component Alignment
20344 @noindent
20345 On DEC Ada for OpenVMS Alpha, all non composite components
20346 are aligned on natural boundaries. For example, 1-byte
20347 components are aligned on byte boundaries, 2-byte
20348 components on 2-byte boundaries, 4-byte components on 4-byte
20349 byte boundaries, and so on. The OpenVMS Alpha hardware
20350 runs more efficiently with naturally aligned data.
20352 ON GNAT for OpenVMS Alpha, alignment rules are compatible
20353 with DEC Ada for OpenVMS Alpha.
20355 @node Address Clauses
20356 @subsection Address Clauses
20358 @noindent
20359 In DEC Ada and GNAT, address clauses are supported for
20360 objects and imported subprograms.
20361 The predefined type @code{System.Address} is a private type
20362 in both compilers, with the same representation (it is simply
20363 a machine pointer). Addition, subtraction, and comparison
20364 operations are available in the standard Ada 95 package
20365 @code{System.Storage_Elements}, or in package @code{System}
20366 if it is extended to include @code{System.Aux_DEC} using a
20367 pragma @code{Extend_System} as previously described.
20369 Note that code that with's both this extended package @code{System}
20370 and the package @code{System.Storage_Elements} should not @code{use}
20371 both packages, or ambiguities will result. In general it is better
20372 not to mix these two sets of facilities. The Ada 95 package was
20373 designed specifically to provide the kind of features that DEC Ada
20374 adds directly to package @code{System}.
20376 GNAT is compatible with DEC Ada in its handling of address
20377 clauses, except for some limitations in
20378 the form of address clauses for composite objects with
20379 initialization. Such address clauses are easily replaced
20380 by the use of an explicitly-defined constant as described
20381 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
20382 of declarations:
20384 @smallexample @c ada
20385 @cartouche
20386 X, Y : Integer := Init_Func;
20387 Q : String (X .. Y) := "abc";
20389 for Q'Address use Compute_Address;
20390 @end cartouche
20391 @end smallexample
20393 @noindent
20394 will be rejected by GNAT, since the address cannot be computed at the time
20395 that Q is declared. To achieve the intended effect, write instead:
20397 @smallexample @c ada
20398 @group
20399 @cartouche
20400 X, Y : Integer := Init_Func;
20401 Q_Address : constant Address := Compute_Address;
20402 Q : String (X .. Y) := "abc";
20404 for Q'Address use Q_Address;
20405 @end cartouche
20406 @end group
20407 @end smallexample
20409 @noindent
20410 which will be accepted by GNAT (and other Ada 95 compilers), and is also
20411 backwards compatible with Ada 83. A fuller description of the restrictions
20412 on address specifications is found in the GNAT Reference Manual.
20414 @node Other Representation Clauses
20415 @subsection Other Representation Clauses
20417 @noindent
20418 GNAT supports in a compatible manner all the representation
20419 clauses supported by DEC Ada. In addition, it
20420 supports representation clause forms that are new in Ada 95
20421 including COMPONENT_SIZE and SIZE clauses for objects.
20423 @node The Package STANDARD
20424 @section The Package STANDARD
20426 @noindent
20427 The package STANDARD, as implemented by DEC Ada, is fully
20428 described in the Reference Manual for the Ada Programming
20429 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
20430 Language Reference Manual. As implemented by GNAT, the
20431 package STANDARD is described in the Ada 95 Reference
20432 Manual.
20434 In addition, DEC Ada supports the Latin-1 character set in
20435 the type CHARACTER. GNAT supports the Latin-1 character set
20436 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
20437 the type WIDE_CHARACTER.
20439 The floating-point types supported by GNAT are those
20440 supported by DEC Ada, but defaults are different, and are controlled by
20441 pragmas. See @ref{Floating-Point Types and Representations} for details.
20443 @node The Package SYSTEM
20444 @section The Package SYSTEM
20446 @noindent
20447 DEC Ada provides a system-specific version of the package
20448 SYSTEM for each platform on which the language ships.
20449 For the complete specification of the package SYSTEM, see
20450 Appendix F of the DEC Ada Language Reference Manual.
20452 On DEC Ada, the package SYSTEM includes the following conversion functions:
20453 @itemize @bullet
20454 @item TO_ADDRESS(INTEGER)
20456 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
20458 @item  TO_ADDRESS(universal_integer)
20460 @item  TO_INTEGER(ADDRESS)
20462 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
20464 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
20465                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
20466 @end itemize
20468 @noindent
20469 By default, GNAT supplies a version of SYSTEM that matches
20470 the definition given in the Ada 95 Reference Manual.
20471 This
20472 is a subset of the DIGITAL system definitions, which is as
20473 close as possible to the original definitions. The only difference
20474 is that the definition of SYSTEM_NAME is different:
20476 @smallexample @c ada
20477 @group
20478 @cartouche
20479 type Name is (SYSTEM_NAME_GNAT);
20480 System_Name : constant Name := SYSTEM_NAME_GNAT;
20481 @end cartouche
20482 @end group
20483 @end smallexample
20485 @noindent
20486 Also, GNAT adds the new Ada 95 declarations for
20487 BIT_ORDER and DEFAULT_BIT_ORDER.
20489 However, the use of the following pragma causes GNAT
20490 to extend the definition of package SYSTEM so that it
20491 encompasses the full set of DIGITAL-specific extensions,
20492 including the functions listed above:
20494 @smallexample @c ada
20495 @cartouche
20496 pragma Extend_System (Aux_DEC);
20497 @end cartouche
20498 @end smallexample
20500 @noindent
20501 The pragma Extend_System is a configuration pragma that
20502 is most conveniently placed in the @file{gnat.adc} file. See the
20503 GNAT Reference Manual for further details.
20505 DEC Ada does not allow the recompilation of the package
20506 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
20507 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
20508 the package SYSTEM. On OpenVMS Alpha systems, the pragma
20509 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
20510 its single argument.
20512 GNAT does permit the recompilation of package SYSTEM using
20513 a special switch (@option{-gnatg}) and this switch can be used if
20514 it is necessary to modify the definitions in SYSTEM. GNAT does
20515 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
20516 or MEMORY_SIZE by any other means.
20518 On GNAT systems, the pragma SYSTEM_NAME takes the
20519 enumeration literal SYSTEM_NAME_GNAT.
20521 The definitions provided by the use of
20523 @smallexample @c ada
20524 pragma Extend_System (AUX_Dec);
20525 @end smallexample
20527 @noindent
20528 are virtually identical to those provided by the DEC Ada 83 package
20529 System. One important difference is that the name of the TO_ADDRESS
20530 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
20531 See the GNAT Reference manual for a discussion of why this change was
20532 necessary.
20534 @noindent
20535 The version of TO_ADDRESS taking a universal integer argument is in fact
20536 an extension to Ada 83 not strictly compatible with the reference manual.
20537 In GNAT, we are constrained to be exactly compatible with the standard,
20538 and this means we cannot provide this capability. In DEC Ada 83, the
20539 point of this definition is to deal with a call like:
20541 @smallexample @c ada
20542 TO_ADDRESS (16#12777#);
20543 @end smallexample
20545 @noindent
20546 Normally, according to the Ada 83 standard, one would expect this to be
20547 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
20548 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
20549 definition using universal_integer takes precedence.
20551 In GNAT, since the version with universal_integer cannot be supplied, it is
20552 not possible to be 100% compatible. Since there are many programs using
20553 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
20554 to change the name of the function in the UNSIGNED_LONGWORD case, so the
20555 declarations provided in the GNAT version of AUX_Dec are:
20557 @smallexample @c ada
20558 function To_Address (X : Integer) return Address;
20559 pragma Pure_Function (To_Address);
20561 function To_Address_Long (X : Unsigned_Longword) return Address;
20562 pragma Pure_Function (To_Address_Long);
20563 @end smallexample
20565 @noindent
20566 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
20567 change the name to TO_ADDRESS_LONG.
20569 @node Tasking and Task-Related Features
20570 @section Tasking and Task-Related Features
20572 @noindent
20573 The concepts relevant to a comparison of tasking on GNAT
20574 and on DEC Ada for OpenVMS Alpha systems are discussed in
20575 the following sections.
20577 For detailed information on concepts related to tasking in
20578 DEC Ada, see the DEC Ada Language Reference Manual and the
20579 relevant run-time reference manual.
20581 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20582 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
20584 @noindent
20585 On OpenVMS Alpha systems, each Ada task (except a passive
20586 task) is implemented as a single stream of execution
20587 that is created and managed by the kernel. On these
20588 systems, DEC Ada tasking support is based on DECthreads,
20589 an implementation of the POSIX standard for threads.
20591 Although tasks are implemented as threads, all tasks in
20592 an Ada program are part of the same process. As a result,
20593 resources such as open files and virtual memory can be
20594 shared easily among tasks. Having all tasks in one process
20595 allows better integration with the programming environment
20596 (the shell and the debugger, for example).
20598 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
20599 code that calls DECthreads routines can be used together.
20600 The interaction between Ada tasks and DECthreads routines
20601 can have some benefits. For example when on OpenVMS Alpha,
20602 DEC Ada can call C code that is already threaded.
20603 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
20604 and Ada tasks are mapped to threads.
20606 @menu
20607 * Assigning Task IDs::
20608 * Task IDs and Delays::
20609 * Task-Related Pragmas::
20610 * Scheduling and Task Priority::
20611 * The Task Stack::
20612 * External Interrupts::
20613 @end menu
20615 @node Assigning Task IDs
20616 @subsection Assigning Task IDs
20618 @noindent
20619 The DEC Ada Run-Time Library always assigns %TASK 1 to
20620 the environment task that executes the main program. On
20621 OpenVMS Alpha systems, %TASK 0 is often used for tasks
20622 that have been created but are not yet activated.
20624 On OpenVMS Alpha systems, task IDs are assigned at
20625 activation. On GNAT systems, task IDs are also assigned at
20626 task creation but do not have the same form or values as
20627 task ID values in DEC Ada. There is no null task, and the
20628 environment task does not have a specific task ID value.
20630 @node Task IDs and Delays
20631 @subsection Task IDs and Delays
20633 @noindent
20634 On OpenVMS Alpha systems, tasking delays are implemented
20635 using Timer System Services. The Task ID is used for the
20636 identification of the timer request (the REQIDT parameter).
20637 If Timers are used in the application take care not to use
20638 0 for the identification, because cancelling such a timer
20639 will cancel all timers and may lead to unpredictable results.
20641 @node Task-Related Pragmas
20642 @subsection Task-Related Pragmas
20644 @noindent
20645 Ada supplies the pragma TASK_STORAGE, which allows
20646 specification of the size of the guard area for a task
20647 stack. (The guard area forms an area of memory that has no
20648 read or write access and thus helps in the detection of
20649 stack overflow.) On OpenVMS Alpha systems, if the pragma
20650 TASK_STORAGE specifies a value of zero, a minimal guard
20651 area is created. In the absence of a pragma TASK_STORAGE, a default guard
20652 area is created.
20654 GNAT supplies the following task-related pragmas:
20656 @itemize @bullet
20657 @item  TASK_INFO
20659               This pragma appears within a task definition and
20660               applies to the task in which it appears. The argument
20661               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
20663 @item  TASK_STORAGE
20665               GNAT implements pragma TASK_STORAGE in the same way as
20666               DEC Ada.
20667               Both DEC Ada and GNAT supply the pragmas PASSIVE,
20668               SUPPRESS, and VOLATILE.
20669 @end itemize
20670 @node Scheduling and Task Priority
20671 @subsection Scheduling and Task Priority
20673 @noindent
20674 DEC Ada implements the Ada language requirement that
20675 when two tasks are eligible for execution and they have
20676 different priorities, the lower priority task does not
20677 execute while the higher priority task is waiting. The DEC
20678 Ada Run-Time Library keeps a task running until either the
20679 task is suspended or a higher priority task becomes ready.
20681 On OpenVMS Alpha systems, the default strategy is round-
20682 robin with preemption. Tasks of equal priority take turns
20683 at the processor. A task is run for a certain period of
20684 time and then placed at the rear of the ready queue for
20685 its priority level.
20687 DEC Ada provides the implementation-defined pragma TIME_SLICE,
20688 which can be used to enable or disable round-robin
20689 scheduling of tasks with the same priority.
20690 See the relevant DEC Ada run-time reference manual for
20691 information on using the pragmas to control DEC Ada task
20692 scheduling.
20694 GNAT follows the scheduling rules of Annex D (real-time
20695 Annex) of the Ada 95 Reference Manual. In general, this
20696 scheduling strategy is fully compatible with DEC Ada
20697 although it provides some additional constraints (as
20698 fully documented in Annex D).
20699 GNAT implements time slicing control in a manner compatible with
20700 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
20701 to the DEC Ada 83 pragma of the same name.
20702 Note that it is not possible to mix GNAT tasking and
20703 DEC Ada 83 tasking in the same program, since the two run times are
20704 not compatible.
20706 @node The Task Stack
20707 @subsection The Task Stack
20709 @noindent
20710 In DEC Ada, a task stack is allocated each time a
20711 non passive task is activated. As soon as the task is
20712 terminated, the storage for the task stack is deallocated.
20713 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
20714 a default stack size is used. Also, regardless of the size
20715 specified, some additional space is allocated for task
20716 management purposes. On OpenVMS Alpha systems, at least
20717 one page is allocated.
20719 GNAT handles task stacks in a similar manner. According to
20720 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
20721 an alternative method for controlling the task stack size.
20722 The specification of the attribute T'STORAGE_SIZE is also
20723 supported in a manner compatible with DEC Ada.
20725 @node External Interrupts
20726 @subsection External Interrupts
20728 @noindent
20729 On DEC Ada, external interrupts can be associated with task entries.
20730 GNAT is compatible with DEC Ada in its handling of external interrupts.
20732 @node Pragmas and Pragma-Related Features
20733 @section Pragmas and Pragma-Related Features
20735 @noindent
20736 Both DEC Ada and GNAT supply all language-defined pragmas
20737 as specified by the Ada 83 standard. GNAT also supplies all
20738 language-defined pragmas specified in the Ada 95 Reference Manual.
20739 In addition, GNAT implements the implementation-defined pragmas
20740 from DEC Ada 83.
20742 @itemize @bullet
20743 @item  AST_ENTRY
20745 @item  COMMON_OBJECT
20747 @item  COMPONENT_ALIGNMENT
20749 @item  EXPORT_EXCEPTION
20751 @item  EXPORT_FUNCTION
20753 @item  EXPORT_OBJECT
20755 @item  EXPORT_PROCEDURE
20757 @item  EXPORT_VALUED_PROCEDURE
20759 @item  FLOAT_REPRESENTATION
20761 @item  IDENT
20763 @item  IMPORT_EXCEPTION
20765 @item  IMPORT_FUNCTION
20767 @item  IMPORT_OBJECT
20769 @item  IMPORT_PROCEDURE
20771 @item  IMPORT_VALUED_PROCEDURE
20773 @item  INLINE_GENERIC
20775 @item  INTERFACE_NAME
20777 @item  LONG_FLOAT
20779 @item  MAIN_STORAGE
20781 @item  PASSIVE
20783 @item  PSET_OBJECT
20785 @item  SHARE_GENERIC
20787 @item  SUPPRESS_ALL
20789 @item  TASK_STORAGE
20791 @item  TIME_SLICE
20793 @item  TITLE
20794 @end itemize
20796 @noindent
20797 These pragmas are all fully implemented, with the exception of @code{Title},
20798 @code{Passive}, and @code{Share_Generic}, which are
20799 recognized, but which have no
20800 effect in GNAT. The effect of @code{Passive} may be obtained by the
20801 use of protected objects in Ada 95. In GNAT, all generics are inlined.
20803 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
20804 a separate subprogram specification which must appear before the
20805 subprogram body.
20807 GNAT also supplies a number of implementation-defined pragmas as follows:
20808 @itemize @bullet
20809 @item  C_PASS_BY_COPY
20811 @item  EXTEND_SYSTEM
20813 @item  SOURCE_FILE_NAME
20815 @item  UNSUPPRESS
20817 @item  WARNINGS
20819 @item  ABORT_DEFER
20821 @item  ADA_83
20823 @item  ADA_95
20825 @item  ANNOTATE
20827 @item  ASSERT
20829 @item  CPP_CLASS
20831 @item  CPP_CONSTRUCTOR
20833 @item  CPP_DESTRUCTOR
20835 @item  CPP_VIRTUAL
20837 @item  CP_VTABLE
20839 @item  DEBUG
20841 @item  LINKER_ALIAS
20843 @item  LINKER_SECTION
20845 @item  MACHINE_ATTRIBUTE
20847 @item  NO_RETURN
20849 @item  PURE_FUNCTION
20851 @item  SOURCE_REFERENCE
20853 @item  TASK_INFO
20855 @item  UNCHECKED_UNION
20857 @item  UNIMPLEMENTED_UNIT
20859 @item  UNIVERSAL_DATA
20861 @item  WEAK_EXTERNAL
20862 @end itemize
20864 @noindent
20865 For full details on these GNAT implementation-defined pragmas, see
20866 the GNAT Reference Manual.
20868 @menu
20869 * Restrictions on the Pragma INLINE::
20870 * Restrictions on the Pragma INTERFACE::
20871 * Restrictions on the Pragma SYSTEM_NAME::
20872 @end menu
20874 @node Restrictions on the Pragma INLINE
20875 @subsection Restrictions on the Pragma INLINE
20877 @noindent
20878 DEC Ada applies the following restrictions to the pragma INLINE:
20879 @itemize @bullet
20880 @item  Parameters cannot be a task type.
20882 @item  Function results cannot be task types, unconstrained
20883 array types, or unconstrained types with discriminants.
20885 @item  Bodies cannot declare the following:
20886 @itemize @bullet
20887 @item  Subprogram body or stub (imported subprogram is allowed)
20889 @item  Tasks
20891 @item  Generic declarations
20893 @item  Instantiations
20895 @item  Exceptions
20897 @item  Access types (types derived from access types allowed)
20899 @item  Array or record types
20901 @item  Dependent tasks
20903 @item  Direct recursive calls of subprogram or containing
20904 subprogram, directly or via a renaming
20906 @end itemize
20907 @end itemize
20909 @noindent
20910 In GNAT, the only restriction on pragma INLINE is that the
20911 body must occur before the call if both are in the same
20912 unit, and the size must be appropriately small. There are
20913 no other specific restrictions which cause subprograms to
20914 be incapable of being inlined.
20916 @node  Restrictions on the Pragma INTERFACE
20917 @subsection  Restrictions on the Pragma INTERFACE
20919 @noindent
20920 The following lists and describes the restrictions on the
20921 pragma INTERFACE on DEC Ada and GNAT:
20922 @itemize @bullet
20923 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
20924 Default is the default on OpenVMS Alpha systems.
20926 @item  Parameter passing: Language specifies default
20927 mechanisms but can be overridden with an EXPORT pragma.
20929 @itemize @bullet
20930 @item  Ada: Use internal Ada rules.
20932 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
20933 record or task type. Result cannot be a string, an
20934 array, or a record.
20936 @item  Fortran: Parameters cannot be a task. Result cannot
20937 be a string, an array, or a record.
20938 @end itemize
20939 @end itemize
20941 @noindent
20942 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
20943 record parameters for all languages.
20945 @node  Restrictions on the Pragma SYSTEM_NAME
20946 @subsection  Restrictions on the Pragma SYSTEM_NAME
20948 @noindent
20949 For DEC Ada for OpenVMS Alpha, the enumeration literal
20950 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
20951 literal for the type NAME is SYSTEM_NAME_GNAT.
20953 @node  Library of Predefined Units
20954 @section  Library of Predefined Units
20956 @noindent
20957 A library of predefined units is provided as part of the
20958 DEC Ada and GNAT implementations. DEC Ada does not provide
20959 the package MACHINE_CODE but instead recommends importing
20960 assembler code.
20962 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
20963 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
20964 version. During GNAT installation, the DEC Ada Predefined
20965 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
20966 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
20967 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
20968 for details.
20970 The GNAT RTL is contained in
20971 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
20972 the default search path is set up to find DECLIB units in preference
20973 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
20974 for example).
20976 However, it is possible to change the default so that the
20977 reverse is true, or even to mix them using child package
20978 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
20979 is the package name, and the Ada units are available in the
20980 standard manner defined for Ada 95, that is to say as Ada.xxx. To
20981 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
20982 appropriately. For example, to change the default to use the Ada95
20983 versions do:
20985 @smallexample
20986 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
20987                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20988 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
20989                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
20990 @end smallexample
20992 @menu
20993 * Changes to DECLIB::
20994 @end menu
20996 @node Changes to DECLIB
20997 @subsection Changes to DECLIB
20999 @noindent
21000 The changes made to the DEC Ada predefined library for GNAT and Ada 95
21001 compatibility are minor and include the following:
21003 @itemize @bullet
21004 @item  Adjusting the location of pragmas and record representation
21005 clauses to obey Ada 95 rules
21007 @item  Adding the proper notation to generic formal parameters
21008 that take unconstrained types in instantiation
21010 @item  Adding pragma ELABORATE_BODY to package specifications
21011 that have package bodies not otherwise allowed
21013 @item  Occurrences of the identifier @code{"PROTECTED"} are renamed to
21014 @code{"PROTECTD"}.
21015 Currently these are found only in the STARLET package spec.
21016 @end itemize
21018 @noindent
21019 None of the above changes is visible to users.
21021 @node Bindings
21022 @section Bindings
21024 @noindent
21025 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
21026 @itemize @bullet
21028 @item  Command Language Interpreter (CLI interface)
21030 @item  DECtalk Run-Time Library (DTK interface)
21032 @item  Librarian utility routines (LBR interface)
21034 @item  General Purpose Run-Time Library (LIB interface)
21036 @item  Math Run-Time Library (MTH interface)
21038 @item  National Character Set Run-Time Library (NCS interface)
21040 @item  Compiled Code Support Run-Time Library (OTS interface)
21042 @item  Parallel Processing Run-Time Library (PPL interface)
21044 @item  Screen Management Run-Time Library (SMG interface)
21046 @item  Sort Run-Time Library (SOR interface)
21048 @item  String Run-Time Library (STR interface)
21050 @item STARLET System Library
21051 @findex Starlet
21053 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
21055 @item  X Windows Toolkit (XT interface)
21057 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
21058 @end itemize
21060 @noindent
21061 GNAT provides implementations of these DEC bindings in the DECLIB directory.
21063 The X/Motif bindings used to build DECLIB are whatever versions are in the
21064 DEC Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
21065 The build script will
21066 automatically add a pragma Linker_Options to packages @code{Xm}, @code{Xt},
21067 and @code{X_Lib}
21068 causing the default X/Motif sharable image libraries to be linked in. This
21069 is done via options files named @file{xm.opt}, @file{xt.opt}, and
21070 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
21072 It may be necessary to edit these options files to update or correct the
21073 library names if, for example, the newer X/Motif bindings from
21074 @file{ADA$EXAMPLES}
21075 had been (previous to installing GNAT) copied and renamed to supersede the
21076 default @file{ADA$PREDEFINED} versions.
21078 @menu
21079 * Shared Libraries and Options Files::
21080 * Interfaces to C::
21081 @end menu
21083 @node Shared Libraries and Options Files
21084 @subsection Shared Libraries and Options Files
21086 @noindent
21087 When using the DEC Ada
21088 predefined X and Motif bindings, the linking with their sharable images is
21089 done automatically by @command{GNAT LINK}.
21090 When using other X and Motif bindings, you need
21091 to add the corresponding sharable images to the command line for
21092 @code{GNAT LINK}. When linking with shared libraries, or with
21093 @file{.OPT} files, you must
21094 also add them to the command line for @command{GNAT LINK}.
21096 A shared library to be used with GNAT is built in the same way as other
21097 libraries under VMS. The VMS Link command can be used in standard fashion.
21099 @node Interfaces to C
21100 @subsection Interfaces to C
21102 @noindent
21103 DEC Ada
21104 provides the following Ada types and operations:
21106 @itemize @bullet
21107 @item C types package (C_TYPES)
21109 @item C strings (C_TYPES.NULL_TERMINATED)
21111 @item Other_types (SHORT_INT)
21112 @end itemize
21114 @noindent
21115 Interfacing to C with GNAT, one can use the above approach
21116 described for DEC Ada or the facilities of Annex B of
21117 the Ada 95 Reference Manual (packages INTERFACES.C,
21118 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
21119 information, see the section ``Interfacing to C'' in the
21120 @cite{GNAT Reference Manual}.
21122 The @option{-gnatF} qualifier forces default and explicit
21123 @code{External_Name} parameters in pragmas Import and Export
21124 to be uppercased for compatibility with the default behavior
21125 of Compaq C. The qualifier has no effect on @code{Link_Name} parameters.
21127 @node Main Program Definition
21128 @section Main Program Definition
21130 @noindent
21131 The following section discusses differences in the
21132 definition of main programs on DEC Ada and GNAT.
21133 On DEC Ada, main programs are defined to meet the
21134 following conditions:
21135 @itemize @bullet
21136 @item  Procedure with no formal parameters (returns 0 upon
21137        normal completion)
21139 @item  Procedure with no formal parameters (returns 42 when
21140        unhandled exceptions are raised)
21142 @item  Function with no formal parameters whose returned value
21143        is of a discrete type
21145 @item  Procedure with one OUT formal of a discrete type for
21146        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
21148 @end itemize
21150 @noindent
21151 When declared with the pragma EXPORT_VALUED_PROCEDURE,
21152 a main function or main procedure returns a discrete
21153 value whose size is less than 64 bits (32 on VAX systems),
21154 the value is zero- or sign-extended as appropriate.
21155 On GNAT, main programs are defined as follows:
21156 @itemize @bullet
21157 @item  Must be a non-generic, parameter-less subprogram that
21158 is either a procedure or function returning an Ada
21159 STANDARD.INTEGER (the predefined type)
21161 @item  Cannot be a generic subprogram or an instantiation of a
21162 generic subprogram
21163 @end itemize
21165 @node Implementation-Defined Attributes
21166 @section Implementation-Defined Attributes
21168 @noindent
21169 GNAT provides all DEC Ada implementation-defined
21170 attributes.
21172 @node Compiler and Run-Time Interfacing
21173 @section Compiler and Run-Time Interfacing
21175 @noindent
21176 DEC Ada provides the following ways to pass options to the linker
21177 (ACS LINK):
21178 @itemize @bullet
21179 @item  /WAIT and /SUBMIT qualifiers
21181 @item  /COMMAND qualifier
21183 @item  /[NO]MAP qualifier
21185 @item  /OUTPUT=file-spec
21187 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
21188 @end itemize
21190 @noindent
21191 To pass options to the linker, GNAT provides the following
21192 switches:
21194 @itemize @bullet
21195 @item   @option{/EXECUTABLE=exec-name}
21197 @item   @option{/VERBOSE qualifier}
21199 @item   @option{/[NO]DEBUG} and @option{/[NO]TRACEBACK} qualifiers
21200 @end itemize
21202 @noindent
21203 For more information on these switches, see
21204 @ref{Switches for gnatlink}.
21205 In DEC Ada, the command-line switch @option{/OPTIMIZE} is available
21206 to control optimization. DEC Ada also supplies the
21207 following pragmas:
21208 @itemize @bullet
21209 @item  @code{OPTIMIZE}
21211 @item  @code{INLINE}
21213 @item  @code{INLINE_GENERIC}
21215 @item  @code{SUPPRESS_ALL}
21217 @item  @code{PASSIVE}
21218 @end itemize
21220 @noindent
21221 In GNAT, optimization is controlled strictly by command
21222 line parameters, as described in the corresponding section of this guide.
21223 The DIGITAL pragmas for control of optimization are
21224 recognized but ignored.
21226 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
21227 the default is that optimization is turned on.
21229 @node Program Compilation and Library Management
21230 @section Program Compilation and Library Management
21232 @noindent
21233 DEC Ada and GNAT provide a comparable set of commands to
21234 build programs. DEC Ada also provides a program library,
21235 which is a concept that does not exist on GNAT. Instead,
21236 GNAT provides directories of sources that are compiled as
21237 needed.
21239 The following table summarizes
21240 the DEC Ada commands and provides
21241 equivalent GNAT commands. In this table, some GNAT
21242 equivalents reflect the fact that GNAT does not use the
21243 concept of a program library. Instead, it uses a model
21244 in which collections of source and object files are used
21245 in a manner consistent with other languages like C and
21246 Fortran. Therefore, standard system file commands are used
21247 to manipulate these elements. Those GNAT commands are marked with
21248 an asterisk.
21249 Note that, unlike DEC Ada, none of the GNAT commands accepts wild cards.
21251 @need 1500
21252 @multitable @columnfractions .35 .65
21254 @item @emph{DEC Ada Command}
21255 @tab @emph{GNAT Equivalent / Description}
21257 @item @command{ADA}
21258 @tab @command{GNAT COMPILE}@*
21259 Invokes the compiler to compile one or more Ada source files.
21261 @item @command{ACS ATTACH}@*
21262 @tab [No equivalent]@*
21263 Switches control of terminal from current process running the program
21264 library manager.
21266 @item @command{ACS CHECK}
21267 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
21268 Forms the execution closure of one
21269 or more compiled units and checks completeness and currency.
21271 @item @command{ACS COMPILE}
21272 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21273 Forms the execution closure of one or
21274 more specified units, checks completeness and currency,
21275 identifies units that have revised source files, compiles same,
21276 and recompiles units that are or will become obsolete.
21277 Also completes incomplete generic instantiations.
21279 @item @command{ACS COPY FOREIGN}
21280 @tab Copy (*)@*
21281 Copies a foreign object file into the program library as a
21282 library unit body.
21284 @item @command{ACS COPY UNIT}
21285 @tab Copy (*)@*
21286 Copies a compiled unit from one program library to another.
21288 @item @command{ACS CREATE LIBRARY}
21289 @tab Create /directory (*)@*
21290 Creates a program library.
21292 @item @command{ACS CREATE SUBLIBRARY}
21293 @tab Create /directory (*)@*
21294 Creates a program sublibrary.
21296 @item @command{ACS DELETE LIBRARY}
21297 @tab @*
21298 Deletes a program library and its contents.
21300 @item @command{ACS DELETE SUBLIBRARY}
21301 @tab @*
21302 Deletes a program sublibrary and its contents.
21304 @item @command{ACS DELETE UNIT}
21305 @tab Delete file (*)@*
21306 On OpenVMS systems, deletes one or more compiled units from
21307 the current program library.
21309 @item @command{ACS DIRECTORY}
21310 @tab Directory (*)@*
21311 On OpenVMS systems, lists units contained in the current
21312 program library.
21314 @item @command{ACS ENTER FOREIGN}
21315 @tab Copy (*)@*
21316 Allows the import of a foreign body as an Ada library
21317 specification and enters a reference to a pointer.
21319 @item @command{ACS ENTER UNIT}
21320 @tab Copy (*)@*
21321 Enters a reference (pointer) from the current program library to
21322 a unit compiled into another program library.
21324 @item @command{ACS EXIT}
21325 @tab [No equivalent]@*
21326 Exits from the program library manager.
21328 @item @command{ACS EXPORT}
21329 @tab Copy (*)@*
21330 Creates an object file that contains system-specific object code
21331 for one or more units. With GNAT, object files can simply be copied
21332 into the desired directory.
21334 @item @command{ACS EXTRACT SOURCE}
21335 @tab Copy (*)@*
21336 Allows access to the copied source file for each Ada compilation unit
21338 @item @command{ACS HELP}
21339 @tab @command{HELP GNAT}@*
21340 Provides online help.
21342 @item @command{ACS LINK}
21343 @tab @command{GNAT LINK}@*
21344 Links an object file containing Ada units into an executable file.
21346 @item @command{ACS LOAD}
21347 @tab Copy (*)@*
21348 Loads (partially compiles) Ada units into the program library.
21349 Allows loading a program from a collection of files into a library
21350 without knowing the relationship among units.
21352 @item @command{ACS MERGE}
21353 @tab Copy (*)@*
21354 Merges into the current program library, one or more units from
21355 another library where they were modified.
21357 @item @command{ACS RECOMPILE}
21358 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
21359 Recompiles from   external or copied source files any obsolete
21360 unit in the closure. Also, completes any incomplete generic
21361 instantiations.
21363 @item @command{ACS REENTER}
21364 @tab @command{GNAT MAKE}@*
21365 Reenters current references to units compiled after last entered
21366 with the @command{ACS ENTER UNIT} command.
21368 @item @command{ACS SET LIBRARY}
21369 @tab Set default (*)@*
21370 Defines a program library to be the compilation context as well
21371 as the target library for compiler output and commands in general.
21373 @item @command{ACS SET PRAGMA}
21374 @tab Edit @file{gnat.adc} (*)@*
21375 Redefines specified  values of the library characteristics
21376 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
21377 and @code{Float_Representation}.
21379 @item @command{ACS SET SOURCE}
21380 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
21381 Defines the source file search list for the @command{ACS COMPILE} command.
21383 @item @command{ACS SHOW LIBRARY}
21384 @tab Directory (*)@*
21385 Lists information about one or more program libraries.
21387 @item @command{ACS SHOW PROGRAM}
21388 @tab [No equivalent]@*
21389 Lists information about the execution closure of one or
21390 more units in the program library.
21392 @item @command{ACS SHOW SOURCE}
21393 @tab Show logical @code{ADA_INCLUDE_PATH}@*
21394 Shows the source file search used when compiling units.
21396 @item @command{ACS SHOW VERSION}
21397 @tab Compile with @option{VERBOSE} option
21398 Displays the version number of the compiler and program library
21399 manager used.
21401 @item @command{ACS SPAWN}
21402 @tab [No equivalent]@*
21403 Creates a subprocess of the current process (same as @command{DCL SPAWN}
21404 command).
21406 @item @command{ACS VERIFY}
21407 @tab [No equivalent]@*
21408 Performs a series of consistency checks on a program library to
21409 determine whether the library structure and library files are in
21410 valid form.
21411 @end multitable
21413 @noindent
21415 @node Input-Output
21416 @section Input-Output
21418 @noindent
21419 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
21420 Management Services (RMS) to perform operations on
21421 external files.
21423 @noindent
21424 DEC Ada and GNAT predefine an identical set of input-
21425 output packages. To make the use of the
21426 generic TEXT_IO operations more convenient, DEC Ada
21427 provides predefined library packages that instantiate the
21428 integer and floating-point operations for the predefined
21429 integer and floating-point types as shown in the following table.
21431 @multitable @columnfractions .45 .55
21432 @item @emph{Package Name} @tab Instantiation
21434 @item @code{INTEGER_TEXT_IO}
21435 @tab @code{INTEGER_IO(INTEGER)}
21437 @item @code{SHORT_INTEGER_TEXT_IO}
21438 @tab @code{INTEGER_IO(SHORT_INTEGER)}
21440 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
21441 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
21443 @item @code{FLOAT_TEXT_IO}
21444 @tab @code{FLOAT_IO(FLOAT)}
21446 @item @code{LONG_FLOAT_TEXT_IO}
21447 @tab @code{FLOAT_IO(LONG_FLOAT)}
21448 @end multitable
21450 @noindent
21451 The DEC Ada predefined packages and their operations
21452 are implemented using OpenVMS Alpha files and input-
21453 output facilities. DEC Ada supports asynchronous input-
21454 output on OpenVMS Alpha. Familiarity with the following is
21455 recommended:
21456 @itemize @bullet
21457 @item  RMS file organizations and access methods
21459 @item  OpenVMS file specifications and directories
21461 @item  OpenVMS File Definition Language (FDL)
21462 @end itemize
21464 @noindent
21465 GNAT provides I/O facilities that are completely
21466 compatible with DEC Ada. The distribution includes the
21467 standard DEC Ada versions of all I/O packages, operating
21468 in a manner compatible with DEC Ada. In particular, the
21469 following packages are by default the DEC Ada (Ada 83)
21470 versions of these packages rather than the renamings
21471 suggested in annex J of the Ada 95 Reference Manual:
21472 @itemize @bullet
21473 @item  @code{TEXT_IO}
21475 @item  @code{SEQUENTIAL_IO}
21477 @item  @code{DIRECT_IO}
21478 @end itemize
21480 @noindent
21481 The use of the standard Ada 95 syntax for child packages (for
21482 example, @code{ADA.TEXT_IO}) retrieves the Ada 95 versions of these
21483 packages, as defined in the Ada 95 Reference Manual.
21484 GNAT provides DIGITAL-compatible predefined instantiations
21485 of the @code{TEXT_IO} packages, and also
21486 provides the standard predefined instantiations required
21487 by the Ada 95 Reference Manual.
21489 For further information on how GNAT interfaces to the file
21490 system or how I/O is implemented in programs written in
21491 mixed languages, see the chapter ``Implementation of the
21492 Standard I/O'' in the @cite{GNAT Reference Manual}.
21493 This chapter covers the following:
21494 @itemize @bullet
21495 @item  Standard I/O packages
21497 @item  @code{FORM} strings
21499 @item  @code{ADA.DIRECT_IO}
21501 @item  @code{ADA.SEQUENTIAL_IO}
21503 @item  @code{ADA.TEXT_IO}
21505 @item  Stream pointer positioning
21507 @item  Reading and writing non-regular files
21509 @item  @code{GET_IMMEDIATE}
21511 @item  Treating @code{TEXT_IO} files as streams
21513 @item  Shared files
21515 @item  Open modes
21516 @end itemize
21518 @node Implementation Limits
21519 @section Implementation Limits
21521 @noindent
21522 The following table lists implementation limits for DEC Ada
21523 and GNAT systems.
21524 @multitable @columnfractions .60 .20 .20
21525 @sp 1
21526 @item  @emph{Compilation Parameter}
21527 @tab   @emph{DEC Ada}
21528 @tab   @emph{GNAT}
21529 @sp 1
21531 @item  In a subprogram or entry  declaration, maximum number of
21532        formal parameters that are of an unconstrained record type
21533 @tab   32
21534 @tab   No set limit
21535 @sp 1
21537 @item  Maximum identifier length (number of characters)
21538 @tab   255
21539 @tab   255
21540 @sp 1
21542 @item  Maximum number of characters in a source line
21543 @tab   255
21544 @tab   255
21545 @sp 1
21547 @item  Maximum collection size   (number of bytes)
21548 @tab   2**31-1
21549 @tab   2**31-1
21550 @sp 1
21552 @item  Maximum number of discriminants for a record type
21553 @tab   245
21554 @tab   No set limit
21555 @sp 1
21557 @item  Maximum number of formal parameters in an entry or
21558        subprogram declaration
21559 @tab   246
21560 @tab    No set limit
21561 @sp 1
21563 @item  Maximum number of dimensions in an array type
21564 @tab   255
21565 @tab   No set limit
21566 @sp 1
21568 @item  Maximum number of library  units and subunits in a compilation.
21569 @tab   4095
21570 @tab   No set limit
21571 @sp 1
21573 @item  Maximum number of library units and subunits in an execution.
21574 @tab   16383
21575 @tab   No set limit
21576 @sp 1
21578 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
21579        or @code{PSECT_OBJECT}
21580 @tab   32757
21581 @tab   No set limit
21582 @sp 1
21584 @item  Maximum number of enumeration literals in an enumeration type
21585        definition
21586 @tab   65535
21587 @tab   No set limit
21588 @sp 1
21590 @item  Maximum number of lines in a source file
21591 @tab   65534
21592 @tab   No set limit
21593 @sp 1
21595 @item  Maximum number of bits in any object
21596 @tab   2**31-1
21597 @tab   2**31-1
21598 @sp 1
21600 @item  Maximum size of the static portion of a stack frame (approximate)
21601 @tab   2**31-1
21602 @tab   2**31-1
21603 @end multitable
21605 @node  Tools
21606 @section Tools
21608 @end ifset
21610 @c **************************************
21611 @node Platform-Specific Information for the Run-Time Libraries
21612 @appendix Platform-Specific Information for the Run-Time Libraries
21613 @cindex Tasking and threads libraries
21614 @cindex Threads libraries and tasking
21615 @cindex Run-time libraries (platform-specific information)
21617 @noindent
21618 The GNAT run-time implementation may vary with respect to both the
21619 underlying threads library and the exception handling scheme.
21620 For threads support, one or more of the following are supplied:
21621 @itemize @bullet
21622 @item @b{native threads library}, a binding to the thread package from
21623 the underlying operating system
21625 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
21626 POSIX thread package
21627 @end itemize
21629 @noindent
21630 For exception handling, either or both of two models are supplied:
21631 @itemize @bullet
21632 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
21633 Most programs should experience a substantial speed improvement by
21634 being compiled with a ZCX run-time.
21635 This is especially true for
21636 tasking applications or applications with many exception handlers.}
21637 @cindex Zero-Cost Exceptions
21638 @cindex ZCX (Zero-Cost Exceptions)
21639 which uses binder-generated tables that
21640 are interrogated at run time to locate a handler
21642 @item @b{setjmp / longjmp} (``SJLJ''),
21643 @cindex setjmp/longjmp Exception Model
21644 @cindex SJLJ (setjmp/longjmp Exception Model)
21645 which uses dynamically-set data to establish
21646 the set of handlers
21647 @end itemize
21649 @noindent
21650 This appendix summarizes which combinations of threads and exception support
21651 are supplied on various GNAT platforms.
21652 It then shows how to select a particular library either
21653 permanently or temporarily,
21654 explains the properties of (and tradeoffs among) the various threads
21655 libraries, and provides some additional
21656 information about several specific platforms.
21658 @menu
21659 * Summary of Run-Time Configurations::
21660 * Specifying a Run-Time Library::
21661 * Choosing the Scheduling Policy::
21662 * Solaris-Specific Considerations::
21663 * IRIX-Specific Considerations::
21664 * Linux-Specific Considerations::
21665 * AIX-Specific Considerations::
21666 @end menu
21668 @node Summary of Run-Time Configurations
21669 @section Summary of Run-Time Configurations
21671 @multitable @columnfractions .30 .70
21672 @item @b{alpha-openvms}
21673 @item @code{@ @ }@i{rts-native (default)}
21674 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
21675 @item @code{@ @ @ @ }Exceptions @tab ZCX
21677 @item @b{pa-hpux}
21678 @item @code{@ @ }@i{rts-native (default)}
21679 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
21680 @item @code{@ @ @ @ }Exceptions @tab ZCX
21682 @item @code{@ @ }@i{rts-sjlj}
21683 @item @code{@ @ @ @ }Tasking    @tab native HP threads library
21684 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21686 @item @b{sparc-solaris}  @tab
21687 @item @code{@ @ }@i{rts-native (default)}
21688 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21689 @item @code{@ @ @ @ }Exceptions @tab ZCX
21691 @item @code{@ @ }@i{rts-m64}
21692 @item @code{@ @ @ @ }Tasking     @tab native Solaris threads library
21693 @item @code{@ @ @ @ }Exceptions  @tab ZCX
21694 @item @code{@ @ @ @ }Constraints @tab Use only when compiling in 64-bit mode;
21695 @item    @tab Use only on Solaris 8 or later.
21696 @item    @tab @xref{Building and Debugging 64-bit Applications}, for details.
21698 @item @code{@ @ }@i{rts-pthread}
21699 @item @code{@ @ @ @ }Tasking    @tab pthreads library
21700 @item @code{@ @ @ @ }Exceptions @tab ZCX
21702 @item @code{@ @ }@i{rts-sjlj}
21703 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
21704 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21706 @item @b{x86-linux}
21707 @item @code{@ @ }@i{rts-native (default)}
21708 @item @code{@ @ @ @ }Tasking    @tab pthread library
21709 @item @code{@ @ @ @ }Exceptions @tab ZCX
21711 @item @code{@ @ }@i{rts-sjlj}
21712 @item @code{@ @ @ @ }Tasking    @tab pthread library
21713 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21715 @item @b{x86-windows}
21716 @item @code{@ @ }@i{rts-native (default)}
21717 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
21718 @item @code{@ @ @ @ }Exceptions @tab SJLJ
21720 @end multitable
21722 @node Specifying a Run-Time Library
21723 @section Specifying a Run-Time Library
21725 @noindent
21726 The @file{adainclude} subdirectory containing the sources of the GNAT
21727 run-time library, and the @file{adalib} subdirectory containing the
21728 @file{ALI} files and the static and/or shared GNAT library, are located
21729 in the gcc target-dependent area:
21731 @smallexample
21732 target=$prefix/lib/gcc-lib/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
21733 @end smallexample
21735 @noindent
21736 As indicated above, on some platforms several run-time libraries are supplied.
21737 These libraries are installed in the target dependent area and
21738 contain a complete source and binary subdirectory. The detailed description
21739 below explains the differences between the different libraries in terms of
21740 their thread support.
21742 The default run-time library (when GNAT is installed) is @emph{rts-native}.
21743 This default run time is selected by the means of soft links.
21744 For example on x86-linux:
21746 @smallexample
21747 @group
21748  $(target-dir)
21749      |
21750      +--- adainclude----------+
21751      |                        |
21752      +--- adalib-----------+  |
21753      |                     |  |
21754      +--- rts-native       |  |
21755      |    |                |  |
21756      |    +--- adainclude <---+
21757      |    |                |
21758      |    +--- adalib <----+
21759      |
21760      +--- rts-sjlj
21761           |
21762           +--- adainclude
21763           |
21764           +--- adalib
21765 @end group
21766 @end smallexample
21768 @noindent
21769 If the @i{rts-sjlj} library is to be selected on a permanent basis,
21770 these soft links can be modified with the following commands:
21772 @smallexample
21773 $ cd $target
21774 $ rm -f adainclude adalib
21775 $ ln -s rts-sjlj/adainclude adainclude
21776 $ ln -s rts-sjlj/adalib adalib
21777 @end smallexample
21779 @noindent
21780 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
21781 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
21782 @file{$target/ada_object_path}.
21784 Selecting another run-time library temporarily can be
21785 achieved by the regular mechanism for GNAT object or source path selection:
21787 @itemize @bullet
21788 @item
21789 Set the environment variables:
21791 @smallexample
21792 $ ADA_INCLUDE_PATH=$target/rts-sjlj/adainclude:$ADA_INCLUDE_PATH
21793 $ ADA_OBJECTS_PATH=$target/rts-sjlj/adalib:$ADA_OBJECTS_PATH
21794 $ export ADA_INCLUDE_PATH ADA_OBJECTS_PATH
21795 @end smallexample
21797 @item
21798 Use @option{-aI$target/rts-sjlj/adainclude}
21799 and @option{-aO$target/rts-sjlj/adalib}
21800 on the @command{gnatmake} command line
21802 @item
21803 Use the switch @option{--RTS}; e.g., @option{--RTS=sjlj}
21804 @cindex @option{--RTS} option
21805 @end itemize
21807 @node Choosing the Scheduling Policy
21808 @section Choosing the Scheduling Policy
21810 @noindent
21811 When using a POSIX threads implementation, you have a choice of several
21812 scheduling policies: @code{SCHED_FIFO},
21813 @cindex @code{SCHED_FIFO} scheduling policy
21814 @code{SCHED_RR}
21815 @cindex @code{SCHED_RR} scheduling policy
21816 and @code{SCHED_OTHER}.
21817 @cindex @code{SCHED_OTHER} scheduling policy
21818 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
21819 or @code{SCHED_RR} requires special (e.g., root) privileges.
21821 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
21822 @code{SCHED_FIFO},
21823 @cindex @code{SCHED_FIFO} scheduling policy
21824 you can use one of the following:
21826 @itemize @bullet
21827 @item
21828 @code{pragma Time_Slice (0.0)}
21829 @cindex pragma Time_Slice
21830 @item
21831 the corresponding binder option @option{-T0}
21832 @cindex @option{-T0} option
21833 @item
21834 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
21835 @cindex pragma Task_Dispatching_Policy
21836 @end itemize
21838 @noindent
21839 To specify @code{SCHED_RR},
21840 @cindex @code{SCHED_RR} scheduling policy
21841 you should use @code{pragma Time_Slice} with a
21842 value greater than @code{0.0}, or else use the corresponding @option{-T}
21843 binder option.
21845 @node Solaris-Specific Considerations
21846 @section Solaris-Specific Considerations
21847 @cindex Solaris Sparc threads libraries
21849 @noindent
21850 This section addresses some topics related to the various threads libraries
21851 on Sparc Solaris and then provides some information on building and
21852 debugging 64-bit applications.
21854 @menu
21855 * Solaris Threads Issues::
21856 * Building and Debugging 64-bit Applications::
21857 @end menu
21859 @node Solaris Threads Issues
21860 @subsection Solaris Threads Issues
21862 @noindent
21863 GNAT under Solaris comes with an alternate tasking run-time library
21864 based on POSIX threads --- @emph{rts-pthread}.
21865 @cindex rts-pthread threads library
21866 This run-time library has the advantage of being mostly shared across all
21867 POSIX-compliant thread implementations, and it also provides under
21868 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
21869 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
21870 and @code{PTHREAD_PRIO_PROTECT}
21871 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
21872 semantics that can be selected using the predefined pragma
21873 @code{Locking_Policy}
21874 @cindex pragma Locking_Policy (under rts-pthread)
21875 with respectively
21876 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
21877 @cindex @code{Inheritance_Locking} (under rts-pthread)
21878 @cindex @code{Ceiling_Locking} (under rts-pthread)
21880 As explained above, the native run-time library is based on the Solaris thread
21881 library (@code{libthread}) and is the default library.
21883 When the Solaris threads library is used (this is the default), programs
21884 compiled with GNAT can automatically take advantage of
21885 and can thus execute on multiple processors.
21886 The user can alternatively specify a processor on which the program should run
21887 to emulate a single-processor system. The multiprocessor / uniprocessor choice
21888 is made by
21889 setting the environment variable @code{GNAT_PROCESSOR}
21890 @cindex @code{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
21891 to one of the following:
21893 @table @code
21894 @item -2
21895 Use the default configuration (run the program on all
21896          available processors) - this is the same as having
21897          @code{GNAT_PROCESSOR} unset
21899 @item -1
21900 Let the run-time implementation choose one processor and run the program on
21901          that processor
21903 @item 0 .. Last_Proc
21904 Run the program on the specified processor.
21905   @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
21906 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
21907 @end table
21909 @node Building and Debugging 64-bit Applications
21910 @subsection Building and Debugging 64-bit Applications
21912 @noindent
21913 In a 64-bit application, all the sources involved must be compiled with the
21914 @option{-m64} command-line option, and a specific GNAT library (compiled with
21915 this option) is required.
21916 The easiest way to build a 64bit application is to add
21917 @option{-m64 --RTS=m64} to the @command{gnatmake} flags.
21919 To debug these applications, dwarf-2 debug information is required, so you
21920 have to add @option{-gdwarf-2} to your gnatmake arguments.
21921 In addition, a special
21922 version of gdb, called @command{gdb64}, needs to be used.
21924 To summarize, building and debugging a ``Hello World'' program in 64-bit mode
21925 amounts to:
21927 @smallexample
21928      $ gnatmake -m64 -gdwarf-2 --RTS=m64 hello.adb
21929      $ gdb64 hello
21930 @end smallexample
21932 @node IRIX-Specific Considerations
21933 @section IRIX-Specific Considerations
21934 @cindex IRIX thread library
21936 @noindent
21937 On SGI IRIX, the thread library depends on which compiler is used.
21938 The @emph{o32 ABI} compiler comes with a run-time library based on the
21939 user-level @code{athread}
21940 library. Thus kernel-level capabilities such as nonblocking system
21941 calls or time slicing can only be achieved reliably by specifying different
21942 @code{sprocs} via the pragma @code{Task_Info}
21943 @cindex pragma Task_Info (and IRIX threads)
21944 and the
21945 @code{System.Task_Info} package.
21946 @cindex @code{System.Task_Info} package (and IRIX threads)
21947 See the @cite{GNAT Reference Manual} for further information.
21949 The @emph{n32 ABI} compiler comes with a run-time library based on the
21950 kernel POSIX threads and thus does not have the limitations mentioned above.
21952 @node Linux-Specific Considerations
21953 @section Linux-Specific Considerations
21954 @cindex Linux threads libraries
21956 @noindent
21957 The default thread library under GNU/Linux has the following disadvantages
21958 compared to other native thread libraries:
21960 @itemize @bullet
21961 @item The size of the task's stack is limited to 2 megabytes.
21962 @item  The signal model is not POSIX compliant, which means that to send a
21963   signal to the process, you need to send the signal to all threads,
21964   e.g. by using @code{killpg()}.
21965 @end itemize
21967 @node AIX-Specific Considerations
21968 @section AIX-Specific Considerations
21969 @cindex AIX resolver library
21971 @noindent
21972 On AIX, the resolver library initializes some internal structure on
21973 the first call to @code{get*by*} functions, which are used to implement
21974 @code{GNAT.Sockets.Get_Host_By_Name} and
21975 @code{GNAT.Sockets.Get_Host_By_Addrss}.
21976 If such initialization occurs within an Ada task, and the stack size for
21977 the task is the default size, a stack overflow may occur.
21979 To avoid this overflow, the user should either ensure that the first call
21980 to @code{GNAT.Sockets.Get_Host_By_Name} or
21981 @code{GNAT.Sockets.Get_Host_By_Addrss}
21982 occurs in the environment task, or use @code{pragma Storage_Size} to
21983 specify a sufficiently large size for the stack of the task that contains
21984 this call.
21986 @c *******************************
21987 @node Example of Binder Output File
21988 @appendix Example of Binder Output File
21990 @noindent
21991 This Appendix displays the source code for @command{gnatbind}'s output
21992 file generated for a simple ``Hello World'' program.
21993 Comments have been added for clarification purposes.
21995 @smallexample @c adanocomment
21996 @iftex
21997 @leftskip=0cm
21998 @end iftex
21999 --  The package is called Ada_Main unless this name is actually used
22000 --  as a unit name in the partition, in which case some other unique
22001 --  name is used.
22003 with System;
22004 package ada_main is
22006    Elab_Final_Code : Integer;
22007    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
22009    --  The main program saves the parameters (argument count,
22010    --  argument values, environment pointer) in global variables
22011    --  for later access by other units including
22012    --  Ada.Command_Line.
22014    gnat_argc : Integer;
22015    gnat_argv : System.Address;
22016    gnat_envp : System.Address;
22018    --  The actual variables are stored in a library routine. This
22019    --  is useful for some shared library situations, where there
22020    --  are problems if variables are not in the library.
22022    pragma Import (C, gnat_argc);
22023    pragma Import (C, gnat_argv);
22024    pragma Import (C, gnat_envp);
22026    --  The exit status is similarly an external location
22028    gnat_exit_status : Integer;
22029    pragma Import (C, gnat_exit_status);
22031    GNAT_Version : constant String :=
22032                     "GNAT Version: 3.15w (20010315)";
22033    pragma Export (C, GNAT_Version, "__gnat_version");
22035    --  This is the generated adafinal routine that performs
22036    --  finalization at the end of execution. In the case where
22037    --  Ada is the main program, this main program makes a call
22038    --  to adafinal at program termination.
22040    procedure adafinal;
22041    pragma Export (C, adafinal, "adafinal");
22043    --  This is the generated adainit routine that performs
22044    --  initialization at the start of execution. In the case
22045    --  where Ada is the main program, this main program makes
22046    --  a call to adainit at program startup.
22048    procedure adainit;
22049    pragma Export (C, adainit, "adainit");
22051    --  This routine is called at the start of execution. It is
22052    --  a dummy routine that is used by the debugger to breakpoint
22053    --  at the start of execution.
22055    procedure Break_Start;
22056    pragma Import (C, Break_Start, "__gnat_break_start");
22058    --  This is the actual generated main program (it would be
22059    --  suppressed if the no main program switch were used). As
22060    --  required by standard system conventions, this program has
22061    --  the external name main.
22063    function main
22064      (argc : Integer;
22065       argv : System.Address;
22066       envp : System.Address)
22067       return Integer;
22068    pragma Export (C, main, "main");
22070    --  The following set of constants give the version
22071    --  identification values for every unit in the bound
22072    --  partition. This identification is computed from all
22073    --  dependent semantic units, and corresponds to the
22074    --  string that would be returned by use of the
22075    --  Body_Version or Version attributes.
22077    type Version_32 is mod 2 ** 32;
22078    u00001 : constant Version_32 := 16#7880BEB3#;
22079    u00002 : constant Version_32 := 16#0D24CBD0#;
22080    u00003 : constant Version_32 := 16#3283DBEB#;
22081    u00004 : constant Version_32 := 16#2359F9ED#;
22082    u00005 : constant Version_32 := 16#664FB847#;
22083    u00006 : constant Version_32 := 16#68E803DF#;
22084    u00007 : constant Version_32 := 16#5572E604#;
22085    u00008 : constant Version_32 := 16#46B173D8#;
22086    u00009 : constant Version_32 := 16#156A40CF#;
22087    u00010 : constant Version_32 := 16#033DABE0#;
22088    u00011 : constant Version_32 := 16#6AB38FEA#;
22089    u00012 : constant Version_32 := 16#22B6217D#;
22090    u00013 : constant Version_32 := 16#68A22947#;
22091    u00014 : constant Version_32 := 16#18CC4A56#;
22092    u00015 : constant Version_32 := 16#08258E1B#;
22093    u00016 : constant Version_32 := 16#367D5222#;
22094    u00017 : constant Version_32 := 16#20C9ECA4#;
22095    u00018 : constant Version_32 := 16#50D32CB6#;
22096    u00019 : constant Version_32 := 16#39A8BB77#;
22097    u00020 : constant Version_32 := 16#5CF8FA2B#;
22098    u00021 : constant Version_32 := 16#2F1EB794#;
22099    u00022 : constant Version_32 := 16#31AB6444#;
22100    u00023 : constant Version_32 := 16#1574B6E9#;
22101    u00024 : constant Version_32 := 16#5109C189#;
22102    u00025 : constant Version_32 := 16#56D770CD#;
22103    u00026 : constant Version_32 := 16#02F9DE3D#;
22104    u00027 : constant Version_32 := 16#08AB6B2C#;
22105    u00028 : constant Version_32 := 16#3FA37670#;
22106    u00029 : constant Version_32 := 16#476457A0#;
22107    u00030 : constant Version_32 := 16#731E1B6E#;
22108    u00031 : constant Version_32 := 16#23C2E789#;
22109    u00032 : constant Version_32 := 16#0F1BD6A1#;
22110    u00033 : constant Version_32 := 16#7C25DE96#;
22111    u00034 : constant Version_32 := 16#39ADFFA2#;
22112    u00035 : constant Version_32 := 16#571DE3E7#;
22113    u00036 : constant Version_32 := 16#5EB646AB#;
22114    u00037 : constant Version_32 := 16#4249379B#;
22115    u00038 : constant Version_32 := 16#0357E00A#;
22116    u00039 : constant Version_32 := 16#3784FB72#;
22117    u00040 : constant Version_32 := 16#2E723019#;
22118    u00041 : constant Version_32 := 16#623358EA#;
22119    u00042 : constant Version_32 := 16#107F9465#;
22120    u00043 : constant Version_32 := 16#6843F68A#;
22121    u00044 : constant Version_32 := 16#63305874#;
22122    u00045 : constant Version_32 := 16#31E56CE1#;
22123    u00046 : constant Version_32 := 16#02917970#;
22124    u00047 : constant Version_32 := 16#6CCBA70E#;
22125    u00048 : constant Version_32 := 16#41CD4204#;
22126    u00049 : constant Version_32 := 16#572E3F58#;
22127    u00050 : constant Version_32 := 16#20729FF5#;
22128    u00051 : constant Version_32 := 16#1D4F93E8#;
22129    u00052 : constant Version_32 := 16#30B2EC3D#;
22130    u00053 : constant Version_32 := 16#34054F96#;
22131    u00054 : constant Version_32 := 16#5A199860#;
22132    u00055 : constant Version_32 := 16#0E7F912B#;
22133    u00056 : constant Version_32 := 16#5760634A#;
22134    u00057 : constant Version_32 := 16#5D851835#;
22136    --  The following Export pragmas export the version numbers
22137    --  with symbolic names ending in B (for body) or S
22138    --  (for spec) so that they can be located in a link. The
22139    --  information provided here is sufficient to track down
22140    --  the exact versions of units used in a given build.
22142    pragma Export (C, u00001, "helloB");
22143    pragma Export (C, u00002, "system__standard_libraryB");
22144    pragma Export (C, u00003, "system__standard_libraryS");
22145    pragma Export (C, u00004, "adaS");
22146    pragma Export (C, u00005, "ada__text_ioB");
22147    pragma Export (C, u00006, "ada__text_ioS");
22148    pragma Export (C, u00007, "ada__exceptionsB");
22149    pragma Export (C, u00008, "ada__exceptionsS");
22150    pragma Export (C, u00009, "gnatS");
22151    pragma Export (C, u00010, "gnat__heap_sort_aB");
22152    pragma Export (C, u00011, "gnat__heap_sort_aS");
22153    pragma Export (C, u00012, "systemS");
22154    pragma Export (C, u00013, "system__exception_tableB");
22155    pragma Export (C, u00014, "system__exception_tableS");
22156    pragma Export (C, u00015, "gnat__htableB");
22157    pragma Export (C, u00016, "gnat__htableS");
22158    pragma Export (C, u00017, "system__exceptionsS");
22159    pragma Export (C, u00018, "system__machine_state_operationsB");
22160    pragma Export (C, u00019, "system__machine_state_operationsS");
22161    pragma Export (C, u00020, "system__machine_codeS");
22162    pragma Export (C, u00021, "system__storage_elementsB");
22163    pragma Export (C, u00022, "system__storage_elementsS");
22164    pragma Export (C, u00023, "system__secondary_stackB");
22165    pragma Export (C, u00024, "system__secondary_stackS");
22166    pragma Export (C, u00025, "system__parametersB");
22167    pragma Export (C, u00026, "system__parametersS");
22168    pragma Export (C, u00027, "system__soft_linksB");
22169    pragma Export (C, u00028, "system__soft_linksS");
22170    pragma Export (C, u00029, "system__stack_checkingB");
22171    pragma Export (C, u00030, "system__stack_checkingS");
22172    pragma Export (C, u00031, "system__tracebackB");
22173    pragma Export (C, u00032, "system__tracebackS");
22174    pragma Export (C, u00033, "ada__streamsS");
22175    pragma Export (C, u00034, "ada__tagsB");
22176    pragma Export (C, u00035, "ada__tagsS");
22177    pragma Export (C, u00036, "system__string_opsB");
22178    pragma Export (C, u00037, "system__string_opsS");
22179    pragma Export (C, u00038, "interfacesS");
22180    pragma Export (C, u00039, "interfaces__c_streamsB");
22181    pragma Export (C, u00040, "interfaces__c_streamsS");
22182    pragma Export (C, u00041, "system__file_ioB");
22183    pragma Export (C, u00042, "system__file_ioS");
22184    pragma Export (C, u00043, "ada__finalizationB");
22185    pragma Export (C, u00044, "ada__finalizationS");
22186    pragma Export (C, u00045, "system__finalization_rootB");
22187    pragma Export (C, u00046, "system__finalization_rootS");
22188    pragma Export (C, u00047, "system__finalization_implementationB");
22189    pragma Export (C, u00048, "system__finalization_implementationS");
22190    pragma Export (C, u00049, "system__string_ops_concat_3B");
22191    pragma Export (C, u00050, "system__string_ops_concat_3S");
22192    pragma Export (C, u00051, "system__stream_attributesB");
22193    pragma Export (C, u00052, "system__stream_attributesS");
22194    pragma Export (C, u00053, "ada__io_exceptionsS");
22195    pragma Export (C, u00054, "system__unsigned_typesS");
22196    pragma Export (C, u00055, "system__file_control_blockS");
22197    pragma Export (C, u00056, "ada__finalization__list_controllerB");
22198    pragma Export (C, u00057, "ada__finalization__list_controllerS");
22200    -- BEGIN ELABORATION ORDER
22201    -- ada (spec)
22202    -- gnat (spec)
22203    -- gnat.heap_sort_a (spec)
22204    -- gnat.heap_sort_a (body)
22205    -- gnat.htable (spec)
22206    -- gnat.htable (body)
22207    -- interfaces (spec)
22208    -- system (spec)
22209    -- system.machine_code (spec)
22210    -- system.parameters (spec)
22211    -- system.parameters (body)
22212    -- interfaces.c_streams (spec)
22213    -- interfaces.c_streams (body)
22214    -- system.standard_library (spec)
22215    -- ada.exceptions (spec)
22216    -- system.exception_table (spec)
22217    -- system.exception_table (body)
22218    -- ada.io_exceptions (spec)
22219    -- system.exceptions (spec)
22220    -- system.storage_elements (spec)
22221    -- system.storage_elements (body)
22222    -- system.machine_state_operations (spec)
22223    -- system.machine_state_operations (body)
22224    -- system.secondary_stack (spec)
22225    -- system.stack_checking (spec)
22226    -- system.soft_links (spec)
22227    -- system.soft_links (body)
22228    -- system.stack_checking (body)
22229    -- system.secondary_stack (body)
22230    -- system.standard_library (body)
22231    -- system.string_ops (spec)
22232    -- system.string_ops (body)
22233    -- ada.tags (spec)
22234    -- ada.tags (body)
22235    -- ada.streams (spec)
22236    -- system.finalization_root (spec)
22237    -- system.finalization_root (body)
22238    -- system.string_ops_concat_3 (spec)
22239    -- system.string_ops_concat_3 (body)
22240    -- system.traceback (spec)
22241    -- system.traceback (body)
22242    -- ada.exceptions (body)
22243    -- system.unsigned_types (spec)
22244    -- system.stream_attributes (spec)
22245    -- system.stream_attributes (body)
22246    -- system.finalization_implementation (spec)
22247    -- system.finalization_implementation (body)
22248    -- ada.finalization (spec)
22249    -- ada.finalization (body)
22250    -- ada.finalization.list_controller (spec)
22251    -- ada.finalization.list_controller (body)
22252    -- system.file_control_block (spec)
22253    -- system.file_io (spec)
22254    -- system.file_io (body)
22255    -- ada.text_io (spec)
22256    -- ada.text_io (body)
22257    -- hello (body)
22258    -- END ELABORATION ORDER
22260 end ada_main;
22262 --  The following source file name pragmas allow the generated file
22263 --  names to be unique for different main programs. They are needed
22264 --  since the package name will always be Ada_Main.
22266 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
22267 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
22269 --  Generated package body for Ada_Main starts here
22271 package body ada_main is
22273    --  The actual finalization is performed by calling the
22274    --  library routine in System.Standard_Library.Adafinal
22276    procedure Do_Finalize;
22277    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
22279    -------------
22280    -- adainit --
22281    -------------
22283 @findex adainit
22284    procedure adainit is
22286       --  These booleans are set to True once the associated unit has
22287       --  been elaborated. It is also used to avoid elaborating the
22288       --  same unit twice.
22290       E040 : Boolean;
22291       pragma Import (Ada, E040, "interfaces__c_streams_E");
22293       E008 : Boolean;
22294       pragma Import (Ada, E008, "ada__exceptions_E");
22296       E014 : Boolean;
22297       pragma Import (Ada, E014, "system__exception_table_E");
22299       E053 : Boolean;
22300       pragma Import (Ada, E053, "ada__io_exceptions_E");
22302       E017 : Boolean;
22303       pragma Import (Ada, E017, "system__exceptions_E");
22305       E024 : Boolean;
22306       pragma Import (Ada, E024, "system__secondary_stack_E");
22308       E030 : Boolean;
22309       pragma Import (Ada, E030, "system__stack_checking_E");
22311       E028 : Boolean;
22312       pragma Import (Ada, E028, "system__soft_links_E");
22314       E035 : Boolean;
22315       pragma Import (Ada, E035, "ada__tags_E");
22317       E033 : Boolean;
22318       pragma Import (Ada, E033, "ada__streams_E");
22320       E046 : Boolean;
22321       pragma Import (Ada, E046, "system__finalization_root_E");
22323       E048 : Boolean;
22324       pragma Import (Ada, E048, "system__finalization_implementation_E");
22326       E044 : Boolean;
22327       pragma Import (Ada, E044, "ada__finalization_E");
22329       E057 : Boolean;
22330       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
22332       E055 : Boolean;
22333       pragma Import (Ada, E055, "system__file_control_block_E");
22335       E042 : Boolean;
22336       pragma Import (Ada, E042, "system__file_io_E");
22338       E006 : Boolean;
22339       pragma Import (Ada, E006, "ada__text_io_E");
22341       --  Set_Globals is a library routine that stores away the
22342       --  value of the indicated set of global values in global
22343       --  variables within the library.
22345       procedure Set_Globals
22346         (Main_Priority            : Integer;
22347          Time_Slice_Value         : Integer;
22348          WC_Encoding              : Character;
22349          Locking_Policy           : Character;
22350          Queuing_Policy           : Character;
22351          Task_Dispatching_Policy  : Character;
22352          Adafinal                 : System.Address;
22353          Unreserve_All_Interrupts : Integer;
22354          Exception_Tracebacks     : Integer);
22355 @findex __gnat_set_globals
22356       pragma Import (C, Set_Globals, "__gnat_set_globals");
22358       --  SDP_Table_Build is a library routine used to build the
22359       --  exception tables. See unit Ada.Exceptions in files
22360       --  a-except.ads/adb for full details of how zero cost
22361       --  exception handling works. This procedure, the call to
22362       --  it, and the two following tables are all omitted if the
22363       --  build is in longjmp/setjump exception mode.
22365 @findex SDP_Table_Build
22366 @findex Zero Cost Exceptions
22367       procedure SDP_Table_Build
22368         (SDP_Addresses   : System.Address;
22369          SDP_Count       : Natural;
22370          Elab_Addresses  : System.Address;
22371          Elab_Addr_Count : Natural);
22372       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
22374       --  Table of Unit_Exception_Table addresses. Used for zero
22375       --  cost exception handling to build the top level table.
22377       ST : aliased constant array (1 .. 23) of System.Address := (
22378         Hello'UET_Address,
22379         Ada.Text_Io'UET_Address,
22380         Ada.Exceptions'UET_Address,
22381         Gnat.Heap_Sort_A'UET_Address,
22382         System.Exception_Table'UET_Address,
22383         System.Machine_State_Operations'UET_Address,
22384         System.Secondary_Stack'UET_Address,
22385         System.Parameters'UET_Address,
22386         System.Soft_Links'UET_Address,
22387         System.Stack_Checking'UET_Address,
22388         System.Traceback'UET_Address,
22389         Ada.Streams'UET_Address,
22390         Ada.Tags'UET_Address,
22391         System.String_Ops'UET_Address,
22392         Interfaces.C_Streams'UET_Address,
22393         System.File_Io'UET_Address,
22394         Ada.Finalization'UET_Address,
22395         System.Finalization_Root'UET_Address,
22396         System.Finalization_Implementation'UET_Address,
22397         System.String_Ops_Concat_3'UET_Address,
22398         System.Stream_Attributes'UET_Address,
22399         System.File_Control_Block'UET_Address,
22400         Ada.Finalization.List_Controller'UET_Address);
22402       --  Table of addresses of elaboration routines. Used for
22403       --  zero cost exception handling to make sure these
22404       --  addresses are included in the top level procedure
22405       --  address table.
22407       EA : aliased constant array (1 .. 23) of System.Address := (
22408         adainit'Code_Address,
22409         Do_Finalize'Code_Address,
22410         Ada.Exceptions'Elab_Spec'Address,
22411         System.Exceptions'Elab_Spec'Address,
22412         Interfaces.C_Streams'Elab_Spec'Address,
22413         System.Exception_Table'Elab_Body'Address,
22414         Ada.Io_Exceptions'Elab_Spec'Address,
22415         System.Stack_Checking'Elab_Spec'Address,
22416         System.Soft_Links'Elab_Body'Address,
22417         System.Secondary_Stack'Elab_Body'Address,
22418         Ada.Tags'Elab_Spec'Address,
22419         Ada.Tags'Elab_Body'Address,
22420         Ada.Streams'Elab_Spec'Address,
22421         System.Finalization_Root'Elab_Spec'Address,
22422         Ada.Exceptions'Elab_Body'Address,
22423         System.Finalization_Implementation'Elab_Spec'Address,
22424         System.Finalization_Implementation'Elab_Body'Address,
22425         Ada.Finalization'Elab_Spec'Address,
22426         Ada.Finalization.List_Controller'Elab_Spec'Address,
22427         System.File_Control_Block'Elab_Spec'Address,
22428         System.File_Io'Elab_Body'Address,
22429         Ada.Text_Io'Elab_Spec'Address,
22430         Ada.Text_Io'Elab_Body'Address);
22432    --  Start of processing for adainit
22434    begin
22436       --  Call SDP_Table_Build to build the top level procedure
22437       --  table for zero cost exception handling (omitted in
22438       --  longjmp/setjump mode).
22440       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
22442       --  Call Set_Globals to record various information for
22443       --  this partition.  The values are derived by the binder
22444       --  from information stored in the ali files by the compiler.
22446 @findex __gnat_set_globals
22447       Set_Globals
22448         (Main_Priority            => -1,
22449          --  Priority of main program, -1 if no pragma Priority used
22451          Time_Slice_Value         => -1,
22452          --  Time slice from Time_Slice pragma, -1 if none used
22454          WC_Encoding              => 'b',
22455          --  Wide_Character encoding used, default is brackets
22457          Locking_Policy           => ' ',
22458          --  Locking_Policy used, default of space means not
22459          --  specified, otherwise it is the first character of
22460          --  the policy name.
22462          Queuing_Policy           => ' ',
22463          --  Queuing_Policy used, default of space means not
22464          --  specified, otherwise it is the first character of
22465          --  the policy name.
22467          Task_Dispatching_Policy  => ' ',
22468          --  Task_Dispatching_Policy used, default of space means
22469          --  not specified, otherwise first character of the
22470          --  policy name.
22472          Adafinal                 => System.Null_Address,
22473          --  Address of Adafinal routine, not used anymore
22475          Unreserve_All_Interrupts => 0,
22476          --  Set true if pragma Unreserve_All_Interrupts was used
22478          Exception_Tracebacks     => 0);
22479          --  Indicates if exception tracebacks are enabled
22481       Elab_Final_Code := 1;
22483       --  Now we have the elaboration calls for all units in the partition.
22484       --  The Elab_Spec and Elab_Body attributes generate references to the
22485       --  implicit elaboration procedures generated by the compiler for
22486       --  each unit that requires elaboration.
22488       if not E040 then
22489          Interfaces.C_Streams'Elab_Spec;
22490       end if;
22491       E040 := True;
22492       if not E008 then
22493          Ada.Exceptions'Elab_Spec;
22494       end if;
22495       if not E014 then
22496          System.Exception_Table'Elab_Body;
22497          E014 := True;
22498       end if;
22499       if not E053 then
22500          Ada.Io_Exceptions'Elab_Spec;
22501          E053 := True;
22502       end if;
22503       if not E017 then
22504          System.Exceptions'Elab_Spec;
22505          E017 := True;
22506       end if;
22507       if not E030 then
22508          System.Stack_Checking'Elab_Spec;
22509       end if;
22510       if not E028 then
22511          System.Soft_Links'Elab_Body;
22512          E028 := True;
22513       end if;
22514       E030 := True;
22515       if not E024 then
22516          System.Secondary_Stack'Elab_Body;
22517          E024 := True;
22518       end if;
22519       if not E035 then
22520          Ada.Tags'Elab_Spec;
22521       end if;
22522       if not E035 then
22523          Ada.Tags'Elab_Body;
22524          E035 := True;
22525       end if;
22526       if not E033 then
22527          Ada.Streams'Elab_Spec;
22528          E033 := True;
22529       end if;
22530       if not E046 then
22531          System.Finalization_Root'Elab_Spec;
22532       end if;
22533       E046 := True;
22534       if not E008 then
22535          Ada.Exceptions'Elab_Body;
22536          E008 := True;
22537       end if;
22538       if not E048 then
22539          System.Finalization_Implementation'Elab_Spec;
22540       end if;
22541       if not E048 then
22542          System.Finalization_Implementation'Elab_Body;
22543          E048 := True;
22544       end if;
22545       if not E044 then
22546          Ada.Finalization'Elab_Spec;
22547       end if;
22548       E044 := True;
22549       if not E057 then
22550          Ada.Finalization.List_Controller'Elab_Spec;
22551       end if;
22552       E057 := True;
22553       if not E055 then
22554          System.File_Control_Block'Elab_Spec;
22555          E055 := True;
22556       end if;
22557       if not E042 then
22558          System.File_Io'Elab_Body;
22559          E042 := True;
22560       end if;
22561       if not E006 then
22562          Ada.Text_Io'Elab_Spec;
22563       end if;
22564       if not E006 then
22565          Ada.Text_Io'Elab_Body;
22566          E006 := True;
22567       end if;
22569       Elab_Final_Code := 0;
22570    end adainit;
22572    --------------
22573    -- adafinal --
22574    --------------
22576 @findex adafinal
22577    procedure adafinal is
22578    begin
22579       Do_Finalize;
22580    end adafinal;
22582    ----------
22583    -- main --
22584    ----------
22586    --  main is actually a function, as in the ANSI C standard,
22587    --  defined to return the exit status. The three parameters
22588    --  are the argument count, argument values and environment
22589    --  pointer.
22591 @findex Main Program
22592    function main
22593      (argc : Integer;
22594       argv : System.Address;
22595       envp : System.Address)
22596       return Integer
22597    is
22598       --  The initialize routine performs low level system
22599       --  initialization using a standard library routine which
22600       --  sets up signal handling and performs any other
22601       --  required setup. The routine can be found in file
22602       --  a-init.c.
22604 @findex __gnat_initialize
22605       procedure initialize;
22606       pragma Import (C, initialize, "__gnat_initialize");
22608       --  The finalize routine performs low level system
22609       --  finalization using a standard library routine. The
22610       --  routine is found in file a-final.c and in the standard
22611       --  distribution is a dummy routine that does nothing, so
22612       --  really this is a hook for special user finalization.
22614 @findex __gnat_finalize
22615       procedure finalize;
22616       pragma Import (C, finalize, "__gnat_finalize");
22618       --  We get to the main program of the partition by using
22619       --  pragma Import because if we try to with the unit and
22620       --  call it Ada style, then not only do we waste time
22621       --  recompiling it, but also, we don't really know the right
22622       --  switches (e.g. identifier character set) to be used
22623       --  to compile it.
22625       procedure Ada_Main_Program;
22626       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
22628    --  Start of processing for main
22630    begin
22631       --  Save global variables
22633       gnat_argc := argc;
22634       gnat_argv := argv;
22635       gnat_envp := envp;
22637       --  Call low level system initialization
22639       Initialize;
22641       --  Call our generated Ada initialization routine
22643       adainit;
22645       --  This is the point at which we want the debugger to get
22646       --  control
22648       Break_Start;
22650       --  Now we call the main program of the partition
22652       Ada_Main_Program;
22654       --  Perform Ada finalization
22656       adafinal;
22658       --  Perform low level system finalization
22660       Finalize;
22662       --  Return the proper exit status
22663       return (gnat_exit_status);
22664    end;
22666 --  This section is entirely comments, so it has no effect on the
22667 --  compilation of the Ada_Main package. It provides the list of
22668 --  object files and linker options, as well as some standard
22669 --  libraries needed for the link. The gnatlink utility parses
22670 --  this b~hello.adb file to read these comment lines to generate
22671 --  the appropriate command line arguments for the call to the
22672 --  system linker. The BEGIN/END lines are used for sentinels for
22673 --  this parsing operation.
22675 --  The exact file names will of course depend on the environment,
22676 --  host/target and location of files on the host system.
22678 @findex Object file list
22679 -- BEGIN Object file/option list
22680    --   ./hello.o
22681    --   -L./
22682    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
22683    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
22684 -- END Object file/option list
22686 end ada_main;
22687 @end smallexample
22689 @noindent
22690 The Ada code in the above example is exactly what is generated by the
22691 binder. We have added comments to more clearly indicate the function
22692 of each part of the generated @code{Ada_Main} package.
22694 The code is standard Ada in all respects, and can be processed by any
22695 tools that handle Ada. In particular, it is possible to use the debugger
22696 in Ada mode to debug the generated @code{Ada_Main} package. For example,
22697 suppose that for reasons that you do not understand, your program is crashing
22698 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
22699 you can place a breakpoint on the call:
22701 @smallexample @c ada
22702 Ada.Text_Io'Elab_Body;
22703 @end smallexample
22705 @noindent
22706 and trace the elaboration routine for this package to find out where
22707 the problem might be (more usually of course you would be debugging
22708 elaboration code in your own application).
22710 @node Elaboration Order Handling in GNAT
22711 @appendix Elaboration Order Handling in GNAT
22712 @cindex Order of elaboration
22713 @cindex Elaboration control
22715 @menu
22716 * Elaboration Code in Ada 95::
22717 * Checking the Elaboration Order in Ada 95::
22718 * Controlling the Elaboration Order in Ada 95::
22719 * Controlling Elaboration in GNAT - Internal Calls::
22720 * Controlling Elaboration in GNAT - External Calls::
22721 * Default Behavior in GNAT - Ensuring Safety::
22722 * Treatment of Pragma Elaborate::
22723 * Elaboration Issues for Library Tasks::
22724 * Mixing Elaboration Models::
22725 * What to Do If the Default Elaboration Behavior Fails::
22726 * Elaboration for Access-to-Subprogram Values::
22727 * Summary of Procedures for Elaboration Control::
22728 * Other Elaboration Order Considerations::
22729 @end menu
22731 @noindent
22732 This chapter describes the handling of elaboration code in Ada 95 and
22733 in GNAT, and discusses how the order of elaboration of program units can
22734 be controlled in GNAT, either automatically or with explicit programming
22735 features.
22737 @node Elaboration Code in Ada 95
22738 @section Elaboration Code in Ada 95
22740 @noindent
22741 Ada 95 provides rather general mechanisms for executing code at elaboration
22742 time, that is to say before the main program starts executing. Such code arises
22743 in three contexts:
22745 @table @asis
22746 @item Initializers for variables.
22747 Variables declared at the library level, in package specs or bodies, can
22748 require initialization that is performed at elaboration time, as in:
22749 @smallexample @c ada
22750 @cartouche
22751 Sqrt_Half : Float := Sqrt (0.5);
22752 @end cartouche
22753 @end smallexample
22755 @item Package initialization code
22756 Code in a @code{BEGIN-END} section at the outer level of a package body is
22757 executed as part of the package body elaboration code.
22759 @item Library level task allocators
22760 Tasks that are declared using task allocators at the library level
22761 start executing immediately and hence can execute at elaboration time.
22762 @end table
22764 @noindent
22765 Subprogram calls are possible in any of these contexts, which means that
22766 any arbitrary part of the program may be executed as part of the elaboration
22767 code. It is even possible to write a program which does all its work at
22768 elaboration time, with a null main program, although stylistically this
22769 would usually be considered an inappropriate way to structure
22770 a program.
22772 An important concern arises in the context of elaboration code:
22773 we have to be sure that it is executed in an appropriate order. What we
22774 have is a series of elaboration code sections, potentially one section
22775 for each unit in the program. It is important that these execute
22776 in the correct order. Correctness here means that, taking the above
22777 example of the declaration of @code{Sqrt_Half},
22778 if some other piece of
22779 elaboration code references @code{Sqrt_Half},
22780 then it must run after the
22781 section of elaboration code that contains the declaration of
22782 @code{Sqrt_Half}.
22784 There would never be any order of elaboration problem if we made a rule
22785 that whenever you @code{with} a unit, you must elaborate both the spec and body
22786 of that unit before elaborating the unit doing the @code{with}'ing:
22788 @smallexample @c ada
22789 @group
22790 @cartouche
22791 with Unit_1;
22792 package Unit_2 is ...
22793 @end cartouche
22794 @end group
22795 @end smallexample
22797 @noindent
22798 would require that both the body and spec of @code{Unit_1} be elaborated
22799 before the spec of @code{Unit_2}. However, a rule like that would be far too
22800 restrictive. In particular, it would make it impossible to have routines
22801 in separate packages that were mutually recursive.
22803 You might think that a clever enough compiler could look at the actual
22804 elaboration code and determine an appropriate correct order of elaboration,
22805 but in the general case, this is not possible. Consider the following
22806 example.
22808 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
22809 that references
22810 the variable @code{Sqrt_1}, which is declared in the elaboration code
22811 of the body of @code{Unit_1}:
22813 @smallexample @c ada
22814 @cartouche
22815 Sqrt_1 : Float := Sqrt (0.1);
22816 @end cartouche
22817 @end smallexample
22819 @noindent
22820 The elaboration code of the body of @code{Unit_1} also contains:
22822 @smallexample @c ada
22823 @group
22824 @cartouche
22825 if expression_1 = 1 then
22826    Q := Unit_2.Func_2;
22827 end if;
22828 @end cartouche
22829 @end group
22830 @end smallexample
22832 @noindent
22833 @code{Unit_2} is exactly parallel,
22834 it has a procedure @code{Func_2} that references
22835 the variable @code{Sqrt_2}, which is declared in the elaboration code of
22836 the body @code{Unit_2}:
22838 @smallexample @c ada
22839 @cartouche
22840 Sqrt_2 : Float := Sqrt (0.1);
22841 @end cartouche
22842 @end smallexample
22844 @noindent
22845 The elaboration code of the body of @code{Unit_2} also contains:
22847 @smallexample @c ada
22848 @group
22849 @cartouche
22850 if expression_2 = 2 then
22851    Q := Unit_1.Func_1;
22852 end if;
22853 @end cartouche
22854 @end group
22855 @end smallexample
22857 @noindent
22858 Now the question is, which of the following orders of elaboration is
22859 acceptable:
22861 @smallexample
22862 @group
22863 Spec of Unit_1
22864 Spec of Unit_2
22865 Body of Unit_1
22866 Body of Unit_2
22867 @end group
22868 @end smallexample
22870 @noindent
22873 @smallexample
22874 @group
22875 Spec of Unit_2
22876 Spec of Unit_1
22877 Body of Unit_2
22878 Body of Unit_1
22879 @end group
22880 @end smallexample
22882 @noindent
22883 If you carefully analyze the flow here, you will see that you cannot tell
22884 at compile time the answer to this question.
22885 If @code{expression_1} is not equal to 1,
22886 and @code{expression_2} is not equal to 2,
22887 then either order is acceptable, because neither of the function calls is
22888 executed. If both tests evaluate to true, then neither order is acceptable
22889 and in fact there is no correct order.
22891 If one of the two expressions is true, and the other is false, then one
22892 of the above orders is correct, and the other is incorrect. For example,
22893 if @code{expression_1} = 1 and @code{expression_2} /= 2,
22894 then the call to @code{Func_2}
22895 will occur, but not the call to @code{Func_1.}
22896 This means that it is essential
22897 to elaborate the body of @code{Unit_1} before
22898 the body of @code{Unit_2}, so the first
22899 order of elaboration is correct and the second is wrong.
22901 By making @code{expression_1} and @code{expression_2}
22902 depend on input data, or perhaps
22903 the time of day, we can make it impossible for the compiler or binder
22904 to figure out which of these expressions will be true, and hence it
22905 is impossible to guarantee a safe order of elaboration at run time.
22907 @node Checking the Elaboration Order in Ada 95
22908 @section Checking the Elaboration Order in Ada 95
22910 @noindent
22911 In some languages that involve the same kind of elaboration problems,
22912 e.g. Java and C++, the programmer is expected to worry about these
22913 ordering problems himself, and it is common to
22914 write a program in which an incorrect elaboration order  gives
22915 surprising results, because it references variables before they
22916 are initialized.
22917 Ada 95 is designed to be a safe language, and a programmer-beware approach is
22918 clearly not sufficient. Consequently, the language provides three lines
22919 of defense:
22921 @table @asis
22922 @item Standard rules
22923 Some standard rules restrict the possible choice of elaboration
22924 order. In particular, if you @code{with} a unit, then its spec is always
22925 elaborated before the unit doing the @code{with}. Similarly, a parent
22926 spec is always elaborated before the child spec, and finally
22927 a spec is always elaborated before its corresponding body.
22929 @item Dynamic elaboration checks
22930 @cindex Elaboration checks
22931 @cindex Checks, elaboration
22932 Dynamic checks are made at run time, so that if some entity is accessed
22933 before it is elaborated (typically  by means of a subprogram call)
22934 then the exception (@code{Program_Error}) is raised.
22936 @item Elaboration control
22937 Facilities are provided for the programmer to specify the desired order
22938 of elaboration.
22939 @end table
22941 Let's look at these facilities in more detail. First, the rules for
22942 dynamic checking. One possible rule would be simply to say that the
22943 exception is raised if you access a variable which has not yet been
22944 elaborated. The trouble with this approach is that it could require
22945 expensive checks on every variable reference. Instead Ada 95 has two
22946 rules which are a little more restrictive, but easier to check, and
22947 easier to state:
22949 @table @asis
22950 @item Restrictions on calls
22951 A subprogram can only be called at elaboration time if its body
22952 has been elaborated. The rules for elaboration given above guarantee
22953 that the spec of the subprogram has been elaborated before the
22954 call, but not the body. If this rule is violated, then the
22955 exception @code{Program_Error} is raised.
22957 @item Restrictions on instantiations
22958 A generic unit can only be instantiated if the body of the generic
22959 unit has been elaborated. Again, the rules for elaboration given above
22960 guarantee that the spec of the generic unit has been elaborated
22961 before the instantiation, but not the body. If this rule is
22962 violated, then the exception @code{Program_Error} is raised.
22963 @end table
22965 @noindent
22966 The idea is that if the body has been elaborated, then any variables
22967 it references must have been elaborated; by checking for the body being
22968 elaborated we guarantee that none of its references causes any
22969 trouble. As we noted above, this is a little too restrictive, because a
22970 subprogram that has no non-local references in its body may in fact be safe
22971 to call. However, it really would be unsafe to rely on this, because
22972 it would mean that the caller was aware of details of the implementation
22973 in the body. This goes against the basic tenets of Ada.
22975 A plausible implementation can be described as follows.
22976 A Boolean variable is associated with each subprogram
22977 and each generic unit. This variable is initialized to False, and is set to
22978 True at the point body is elaborated. Every call or instantiation checks the
22979 variable, and raises @code{Program_Error} if the variable is False.
22981 Note that one might think that it would be good enough to have one Boolean
22982 variable for each package, but that would not deal with cases of trying
22983 to call a body in the same package as the call
22984 that has not been elaborated yet.
22985 Of course a compiler may be able to do enough analysis to optimize away
22986 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
22987 does such optimizations, but still the easiest conceptual model is to
22988 think of there being one variable per subprogram.
22990 @node Controlling the Elaboration Order in Ada 95
22991 @section Controlling the Elaboration Order in Ada 95
22993 @noindent
22994 In the previous section we discussed the rules in Ada 95 which ensure
22995 that @code{Program_Error} is raised if an incorrect elaboration order is
22996 chosen. This prevents erroneous executions, but we need mechanisms to
22997 specify a correct execution and avoid the exception altogether.
22998 To achieve this, Ada 95 provides a number of features for controlling
22999 the order of elaboration. We discuss these features in this section.
23001 First, there are several ways of indicating to the compiler that a given
23002 unit has no elaboration problems:
23004 @table @asis
23005 @item packages that do not require a body
23006 In Ada 95, a library package that does not require a body does not permit
23007 a body. This means that if we have a such a package, as in:
23009 @smallexample @c ada
23010 @group
23011 @cartouche
23012 package Definitions is
23013    generic
23014       type m is new integer;
23015    package Subp is
23016       type a is array (1 .. 10) of m;
23017       type b is array (1 .. 20) of m;
23018    end Subp;
23019 end Definitions;
23020 @end cartouche
23021 @end group
23022 @end smallexample
23024 @noindent
23025 A package that @code{with}'s @code{Definitions} may safely instantiate
23026 @code{Definitions.Subp} because the compiler can determine that there
23027 definitely is no package body to worry about in this case
23029 @item pragma Pure
23030 @cindex pragma Pure
23031 @findex Pure
23032 Places sufficient restrictions on a unit to guarantee that
23033 no call to any subprogram in the unit can result in an
23034 elaboration problem. This means that the compiler does not need
23035 to worry about the point of elaboration of such units, and in
23036 particular, does not need to check any calls to any subprograms
23037 in this unit.
23039 @item pragma Preelaborate
23040 @findex Preelaborate
23041 @cindex pragma Preelaborate
23042 This pragma places slightly less stringent restrictions on a unit than
23043 does pragma Pure,
23044 but these restrictions are still sufficient to ensure that there
23045 are no elaboration problems with any calls to the unit.
23047 @item pragma Elaborate_Body
23048 @findex Elaborate_Body
23049 @cindex pragma Elaborate_Body
23050 This pragma requires that the body of a unit be elaborated immediately
23051 after its spec. Suppose a unit @code{A} has such a pragma,
23052 and unit @code{B} does
23053 a @code{with} of unit @code{A}. Recall that the standard rules require
23054 the spec of unit @code{A}
23055 to be elaborated before the @code{with}'ing unit; given the pragma in
23056 @code{A}, we also know that the body of @code{A}
23057 will be elaborated before @code{B}, so
23058 that calls to @code{A} are safe and do not need a check.
23059 @end table
23061 @noindent
23062 Note that,
23063 unlike pragma @code{Pure} and pragma @code{Preelaborate},
23064 the use of
23065 @code{Elaborate_Body} does not guarantee that the program is
23066 free of elaboration problems, because it may not be possible
23067 to satisfy the requested elaboration order.
23068 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
23069 If a programmer
23070 marks @code{Unit_1} as @code{Elaborate_Body},
23071 and not @code{Unit_2,} then the order of
23072 elaboration will be:
23074 @smallexample
23075 @group
23076 Spec of Unit_2
23077 Spec of Unit_1
23078 Body of Unit_1
23079 Body of Unit_2
23080 @end group
23081 @end smallexample
23083 @noindent
23084 Now that means that the call to @code{Func_1} in @code{Unit_2}
23085 need not be checked,
23086 it must be safe. But the call to @code{Func_2} in
23087 @code{Unit_1} may still fail if
23088 @code{Expression_1} is equal to 1,
23089 and the programmer must still take
23090 responsibility for this not being the case.
23092 If all units carry a pragma @code{Elaborate_Body}, then all problems are
23093 eliminated, except for calls entirely within a body, which are
23094 in any case fully under programmer control. However, using the pragma
23095 everywhere is not always possible.
23096 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
23097 we marked both of them as having pragma @code{Elaborate_Body}, then
23098 clearly there would be no possible elaboration order.
23100 The above pragmas allow a server to guarantee safe use by clients, and
23101 clearly this is the preferable approach. Consequently a good rule in
23102 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
23103 and if this is not possible,
23104 mark them as @code{Elaborate_Body} if possible.
23105 As we have seen, there are situations where neither of these
23106 three pragmas can be used.
23107 So we also provide methods for clients to control the
23108 order of elaboration of the servers on which they depend:
23110 @table @asis
23111 @item pragma Elaborate (unit)
23112 @findex Elaborate
23113 @cindex pragma Elaborate
23114 This pragma is placed in the context clause, after a @code{with} clause,
23115 and it requires that the body of the named unit be elaborated before
23116 the unit in which the pragma occurs. The idea is to use this pragma
23117 if the current unit calls at elaboration time, directly or indirectly,
23118 some subprogram in the named unit.
23120 @item pragma Elaborate_All (unit)
23121 @findex Elaborate_All
23122 @cindex pragma Elaborate_All
23123 This is a stronger version of the Elaborate pragma. Consider the
23124 following example:
23126 @smallexample
23127 Unit A @code{with}'s unit B and calls B.Func in elab code
23128 Unit B @code{with}'s unit C, and B.Func calls C.Func
23129 @end smallexample
23131 @noindent
23132 Now if we put a pragma @code{Elaborate (B)}
23133 in unit @code{A}, this ensures that the
23134 body of @code{B} is elaborated before the call, but not the
23135 body of @code{C}, so
23136 the call to @code{C.Func} could still cause @code{Program_Error} to
23137 be raised.
23139 The effect of a pragma @code{Elaborate_All} is stronger, it requires
23140 not only that the body of the named unit be elaborated before the
23141 unit doing the @code{with}, but also the bodies of all units that the
23142 named unit uses, following @code{with} links transitively. For example,
23143 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
23144 then it requires
23145 not only that the body of @code{B} be elaborated before @code{A},
23146 but also the
23147 body of @code{C}, because @code{B} @code{with}'s @code{C}.
23148 @end table
23150 @noindent
23151 We are now in a position to give a usage rule in Ada 95 for avoiding
23152 elaboration problems, at least if dynamic dispatching and access to
23153 subprogram values are not used. We will handle these cases separately
23154 later.
23156 The rule is simple. If a unit has elaboration code that can directly or
23157 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
23158 a generic unit in a @code{with}'ed unit,
23159 then if the @code{with}'ed unit does not have
23160 pragma @code{Pure} or @code{Preelaborate}, then the client should have
23161 a pragma @code{Elaborate_All}
23162 for the @code{with}'ed unit. By following this rule a client is
23163 assured that calls can be made without risk of an exception.
23164 If this rule is not followed, then a program may be in one of four
23165 states:
23167 @table @asis
23168 @item No order exists
23169 No order of elaboration exists which follows the rules, taking into
23170 account any @code{Elaborate}, @code{Elaborate_All},
23171 or @code{Elaborate_Body} pragmas. In
23172 this case, an Ada 95 compiler must diagnose the situation at bind
23173 time, and refuse to build an executable program.
23175 @item One or more orders exist, all incorrect
23176 One or more acceptable elaboration orders exists, and all of them
23177 generate an elaboration order problem. In this case, the binder
23178 can build an executable program, but @code{Program_Error} will be raised
23179 when the program is run.
23181 @item Several orders exist, some right, some incorrect
23182 One or more acceptable elaboration orders exists, and some of them
23183 work, and some do not. The programmer has not controlled
23184 the order of elaboration, so the binder may or may not pick one of
23185 the correct orders, and the program may or may not raise an
23186 exception when it is run. This is the worst case, because it means
23187 that the program may fail when moved to another compiler, or even
23188 another version of the same compiler.
23190 @item One or more orders exists, all correct
23191 One ore more acceptable elaboration orders exist, and all of them
23192 work. In this case the program runs successfully. This state of
23193 affairs can be guaranteed by following the rule we gave above, but
23194 may be true even if the rule is not followed.
23195 @end table
23197 @noindent
23198 Note that one additional advantage of following our Elaborate_All rule
23199 is that the program continues to stay in the ideal (all orders OK) state
23200 even if maintenance
23201 changes some bodies of some subprograms. Conversely, if a program that does
23202 not follow this rule happens to be safe at some point, this state of affairs
23203 may deteriorate silently as a result of maintenance changes.
23205 You may have noticed that the above discussion did not mention
23206 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
23207 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
23208 code in the body makes calls to some other unit, so it is still necessary
23209 to use @code{Elaborate_All} on such units.
23211 @node Controlling Elaboration in GNAT - Internal Calls
23212 @section Controlling Elaboration in GNAT - Internal Calls
23214 @noindent
23215 In the case of internal calls, i.e. calls within a single package, the
23216 programmer has full control over the order of elaboration, and it is up
23217 to the programmer to elaborate declarations in an appropriate order. For
23218 example writing:
23220 @smallexample @c ada
23221 @group
23222 @cartouche
23223 function One return Float;
23225 Q : Float := One;
23227 function One return Float is
23228 begin
23229      return 1.0;
23230 end One;
23231 @end cartouche
23232 @end group
23233 @end smallexample
23235 @noindent
23236 will obviously raise @code{Program_Error} at run time, because function
23237 One will be called before its body is elaborated. In this case GNAT will
23238 generate a warning that the call will raise @code{Program_Error}:
23240 @smallexample
23241 @group
23242 @cartouche
23243  1. procedure y is
23244  2.    function One return Float;
23245  3.
23246  4.    Q : Float := One;
23247                     |
23248     >>> warning: cannot call "One" before body is elaborated
23249     >>> warning: Program_Error will be raised at run time
23251  5.
23252  6.    function One return Float is
23253  7.    begin
23254  8.         return 1.0;
23255  9.    end One;
23257 11. begin
23258 12.    null;
23259 13. end;
23260 @end cartouche
23261 @end group
23262 @end smallexample
23264 @noindent
23265 Note that in this particular case, it is likely that the call is safe, because
23266 the function @code{One} does not access any global variables.
23267 Nevertheless in Ada 95, we do not want the validity of the check to depend on
23268 the contents of the body (think about the separate compilation case), so this
23269 is still wrong, as we discussed in the previous sections.
23271 The error is easily corrected by rearranging the declarations so that the
23272 body of One appears before the declaration containing the call
23273 (note that in Ada 95,
23274 declarations can appear in any order, so there is no restriction that
23275 would prevent this reordering, and if we write:
23277 @smallexample @c ada
23278 @group
23279 @cartouche
23280 function One return Float;
23282 function One return Float is
23283 begin
23284      return 1.0;
23285 end One;
23287 Q : Float := One;
23288 @end cartouche
23289 @end group
23290 @end smallexample
23292 @noindent
23293 then all is well, no warning is generated, and no
23294 @code{Program_Error} exception
23295 will be raised.
23296 Things are more complicated when a chain of subprograms is executed:
23298 @smallexample @c ada
23299 @group
23300 @cartouche
23301 function A return Integer;
23302 function B return Integer;
23303 function C return Integer;
23305 function B return Integer is begin return A; end;
23306 function C return Integer is begin return B; end;
23308 X : Integer := C;
23310 function A return Integer is begin return 1; end;
23311 @end cartouche
23312 @end group
23313 @end smallexample
23315 @noindent
23316 Now the call to @code{C}
23317 at elaboration time in the declaration of @code{X} is correct, because
23318 the body of @code{C} is already elaborated,
23319 and the call to @code{B} within the body of
23320 @code{C} is correct, but the call
23321 to @code{A} within the body of @code{B} is incorrect, because the body
23322 of @code{A} has not been elaborated, so @code{Program_Error}
23323 will be raised on the call to @code{A}.
23324 In this case GNAT will generate a
23325 warning that @code{Program_Error} may be
23326 raised at the point of the call. Let's look at the warning:
23328 @smallexample
23329 @group
23330 @cartouche
23331  1. procedure x is
23332  2.    function A return Integer;
23333  3.    function B return Integer;
23334  4.    function C return Integer;
23335  5.
23336  6.    function B return Integer is begin return A; end;
23337                                                     |
23338     >>> warning: call to "A" before body is elaborated may
23339                  raise Program_Error
23340     >>> warning: "B" called at line 7
23341     >>> warning: "C" called at line 9
23343  7.    function C return Integer is begin return B; end;
23344  8.
23345  9.    X : Integer := C;
23347 11.    function A return Integer is begin return 1; end;
23349 13. begin
23350 14.    null;
23351 15. end;
23352 @end cartouche
23353 @end group
23354 @end smallexample
23356 @noindent
23357 Note that the message here says ``may raise'', instead of the direct case,
23358 where the message says ``will be raised''. That's because whether
23359 @code{A} is
23360 actually called depends in general on run-time flow of control.
23361 For example, if the body of @code{B} said
23363 @smallexample @c ada
23364 @group
23365 @cartouche
23366 function B return Integer is
23367 begin
23368    if some-condition-depending-on-input-data then
23369       return A;
23370    else
23371       return 1;
23372    end if;
23373 end B;
23374 @end cartouche
23375 @end group
23376 @end smallexample
23378 @noindent
23379 then we could not know until run time whether the incorrect call to A would
23380 actually occur, so @code{Program_Error} might
23381 or might not be raised. It is possible for a compiler to
23382 do a better job of analyzing bodies, to
23383 determine whether or not @code{Program_Error}
23384 might be raised, but it certainly
23385 couldn't do a perfect job (that would require solving the halting problem
23386 and is provably impossible), and because this is a warning anyway, it does
23387 not seem worth the effort to do the analysis. Cases in which it
23388 would be relevant are rare.
23390 In practice, warnings of either of the forms given
23391 above will usually correspond to
23392 real errors, and should be examined carefully and eliminated.
23393 In the rare case where a warning is bogus, it can be suppressed by any of
23394 the following methods:
23396 @itemize @bullet
23397 @item
23398 Compile with the @option{-gnatws} switch set
23400 @item
23401 Suppress @code{Elaboration_Check} for the called subprogram
23403 @item
23404 Use pragma @code{Warnings_Off} to turn warnings off for the call
23405 @end itemize
23407 @noindent
23408 For the internal elaboration check case,
23409 GNAT by default generates the
23410 necessary run-time checks to ensure
23411 that @code{Program_Error} is raised if any
23412 call fails an elaboration check. Of course this can only happen if a
23413 warning has been issued as described above. The use of pragma
23414 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
23415 some of these checks, meaning that it may be possible (but is not
23416 guaranteed) for a program to be able to call a subprogram whose body
23417 is not yet elaborated, without raising a @code{Program_Error} exception.
23419 @node Controlling Elaboration in GNAT - External Calls
23420 @section Controlling Elaboration in GNAT - External Calls
23422 @noindent
23423 The previous section discussed the case in which the execution of a
23424 particular thread of elaboration code occurred entirely within a
23425 single unit. This is the easy case to handle, because a programmer
23426 has direct and total control over the order of elaboration, and
23427 furthermore, checks need only be generated in cases which are rare
23428 and which the compiler can easily detect.
23429 The situation is more complex when separate compilation is taken into account.
23430 Consider the following:
23432 @smallexample @c ada
23433 @cartouche
23434 @group
23435 package Math is
23436    function Sqrt (Arg : Float) return Float;
23437 end Math;
23439 package body Math is
23440    function Sqrt (Arg : Float) return Float is
23441    begin
23442          ...
23443    end Sqrt;
23444 end Math;
23445 @end group
23446 @group
23447 with Math;
23448 package Stuff is
23449    X : Float := Math.Sqrt (0.5);
23450 end Stuff;
23452 with Stuff;
23453 procedure Main is
23454 begin
23455    ...
23456 end Main;
23457 @end group
23458 @end cartouche
23459 @end smallexample
23461 @noindent
23462 where @code{Main} is the main program. When this program is executed, the
23463 elaboration code must first be executed, and one of the jobs of the
23464 binder is to determine the order in which the units of a program are
23465 to be elaborated. In this case we have four units: the spec and body
23466 of @code{Math},
23467 the spec of @code{Stuff} and the body of @code{Main}).
23468 In what order should the four separate sections of elaboration code
23469 be executed?
23471 There are some restrictions in the order of elaboration that the binder
23472 can choose. In particular, if unit U has a @code{with}
23473 for a package @code{X}, then you
23474 are assured that the spec of @code{X}
23475 is elaborated before U , but you are
23476 not assured that the body of @code{X}
23477 is elaborated before U.
23478 This means that in the above case, the binder is allowed to choose the
23479 order:
23481 @smallexample
23482 spec of Math
23483 spec of Stuff
23484 body of Math
23485 body of Main
23486 @end smallexample
23488 @noindent
23489 but that's not good, because now the call to @code{Math.Sqrt}
23490 that happens during
23491 the elaboration of the @code{Stuff}
23492 spec happens before the body of @code{Math.Sqrt} is
23493 elaborated, and hence causes @code{Program_Error} exception to be raised.
23494 At first glance, one might say that the binder is misbehaving, because
23495 obviously you want to elaborate the body of something you @code{with}
23496 first, but
23497 that is not a general rule that can be followed in all cases. Consider
23499 @smallexample @c ada
23500 @group
23501 @cartouche
23502 package X is ...
23504 package Y is ...
23506 with X;
23507 package body Y is ...
23509 with Y;
23510 package body X is ...
23511 @end cartouche
23512 @end group
23513 @end smallexample
23515 @noindent
23516 This is a common arrangement, and, apart from the order of elaboration
23517 problems that might arise in connection with elaboration code, this works fine.
23518 A rule that says that you must first elaborate the body of anything you
23519 @code{with} cannot work in this case:
23520 the body of @code{X} @code{with}'s @code{Y},
23521 which means you would have to
23522 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
23523 which means
23524 you have to elaborate the body of @code{X} first, but ... and we have a
23525 loop that cannot be broken.
23527 It is true that the binder can in many cases guess an order of elaboration
23528 that is unlikely to cause a @code{Program_Error}
23529 exception to be raised, and it tries to do so (in the
23530 above example of @code{Math/Stuff/Spec}, the GNAT binder will
23531 by default
23532 elaborate the body of @code{Math} right after its spec, so all will be well).
23534 However, a program that blindly relies on the binder to be helpful can
23535 get into trouble, as we discussed in the previous sections, so
23536 GNAT
23537 provides a number of facilities for assisting the programmer in
23538 developing programs that are robust with respect to elaboration order.
23540 @node Default Behavior in GNAT - Ensuring Safety
23541 @section Default Behavior in GNAT - Ensuring Safety
23543 @noindent
23544 The default behavior in GNAT ensures elaboration safety. In its
23545 default mode GNAT implements the
23546 rule we previously described as the right approach. Let's restate it:
23548 @itemize
23549 @item
23550 @emph{If a unit has elaboration code that can directly or indirectly make a
23551 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
23552 in a @code{with}'ed unit, then if the @code{with}'ed unit
23553 does not have pragma @code{Pure} or
23554 @code{Preelaborate}, then the client should have an
23555 @code{Elaborate_All} for the @code{with}'ed unit.}
23556 @end itemize
23558 @noindent
23559 By following this rule a client is assured that calls and instantiations
23560 can be made without risk of an exception.
23562 In this mode GNAT traces all calls that are potentially made from
23563 elaboration code, and puts in any missing implicit @code{Elaborate_All}
23564 pragmas.
23565 The advantage of this approach is that no elaboration problems
23566 are possible if the binder can find an elaboration order that is
23567 consistent with these implicit @code{Elaborate_All} pragmas. The
23568 disadvantage of this approach is that no such order may exist.
23570 If the binder does not generate any diagnostics, then it means that it
23571 has found an elaboration order that is guaranteed to be safe. However,
23572 the binder may still be relying on implicitly generated
23573 @code{Elaborate_All} pragmas so portability to other compilers than
23574 GNAT is not guaranteed.
23576 If it is important to guarantee portability, then the compilations should
23577 use the
23578 @option{-gnatwl}
23579 (warn on elaboration problems) switch. This will cause warning messages
23580 to be generated indicating the missing @code{Elaborate_All} pragmas.
23581 Consider the following source program:
23583 @smallexample @c ada
23584 @group
23585 @cartouche
23586 with k;
23587 package j is
23588   m : integer := k.r;
23589 end;
23590 @end cartouche
23591 @end group
23592 @end smallexample
23594 @noindent
23595 where it is clear that there
23596 should be a pragma @code{Elaborate_All}
23597 for unit @code{k}. An implicit pragma will be generated, and it is
23598 likely that the binder will be able to honor it. However, if you want
23599 to port this program to some other Ada compiler than GNAT.
23600 it is safer to include the pragma explicitly in the source. If this
23601 unit is compiled with the
23602 @option{-gnatwl}
23603 switch, then the compiler outputs a warning:
23605 @smallexample
23606 @group
23607 @cartouche
23608 1. with k;
23609 2. package j is
23610 3.   m : integer := k.r;
23611                      |
23612    >>> warning: call to "r" may raise Program_Error
23613    >>> warning: missing pragma Elaborate_All for "k"
23615 4. end;
23616 @end cartouche
23617 @end group
23618 @end smallexample
23620 @noindent
23621 and these warnings can be used as a guide for supplying manually
23622 the missing pragmas. It is usually a bad idea to use this warning
23623 option during development. That's because it will warn you when
23624 you need to put in a pragma, but cannot warn you when it is time
23625 to take it out. So the use of pragma Elaborate_All may lead to
23626 unnecessary dependencies and even false circularities.
23628 This default mode is more restrictive than the Ada Reference
23629 Manual, and it is possible to construct programs which will compile
23630 using the dynamic model described there, but will run into a
23631 circularity using the safer static model we have described.
23633 Of course any Ada compiler must be able to operate in a mode
23634 consistent with the requirements of the Ada Reference Manual,
23635 and in particular must have the capability of implementing the
23636 standard dynamic model of elaboration with run-time checks.
23638 In GNAT, this standard mode can be achieved either by the use of
23639 the @option{-gnatE} switch on the compiler (@command{gcc} or
23640 @command{gnatmake}) command, or by the use of the configuration pragma:
23642 @smallexample @c ada
23643 pragma Elaboration_Checks (RM);
23644 @end smallexample
23646 @noindent
23647 Either approach will cause the unit affected to be compiled using the
23648 standard dynamic run-time elaboration checks described in the Ada
23649 Reference Manual. The static model is generally preferable, since it
23650 is clearly safer to rely on compile and link time checks rather than
23651 run-time checks. However, in the case of legacy code, it may be
23652 difficult to meet the requirements of the static model. This
23653 issue is further discussed in
23654 @ref{What to Do If the Default Elaboration Behavior Fails}.
23656 Note that the static model provides a strict subset of the allowed
23657 behavior and programs of the Ada Reference Manual, so if you do
23658 adhere to the static model and no circularities exist,
23659 then you are assured that your program will
23660 work using the dynamic model, providing that you remove any
23661 pragma Elaborate statements from the source.
23663 @node Treatment of Pragma Elaborate
23664 @section Treatment of Pragma Elaborate
23665 @cindex Pragma Elaborate
23667 @noindent
23668 The use of @code{pragma Elaborate}
23669 should generally be avoided in Ada 95 programs.
23670 The reason for this is that there is no guarantee that transitive calls
23671 will be properly handled. Indeed at one point, this pragma was placed
23672 in Annex J (Obsolescent Features), on the grounds that it is never useful.
23674 Now that's a bit restrictive. In practice, the case in which
23675 @code{pragma Elaborate} is useful is when the caller knows that there
23676 are no transitive calls, or that the called unit contains all necessary
23677 transitive @code{pragma Elaborate} statements, and legacy code often
23678 contains such uses.
23680 Strictly speaking the static mode in GNAT should ignore such pragmas,
23681 since there is no assurance at compile time that the necessary safety
23682 conditions are met. In practice, this would cause GNAT to be incompatible
23683 with correctly written Ada 83 code that had all necessary
23684 @code{pragma Elaborate} statements in place. Consequently, we made the
23685 decision that GNAT in its default mode will believe that if it encounters
23686 a @code{pragma Elaborate} then the programmer knows what they are doing,
23687 and it will trust that no elaboration errors can occur.
23689 The result of this decision is two-fold. First to be safe using the
23690 static mode, you should remove all @code{pragma Elaborate} statements.
23691 Second, when fixing circularities in existing code, you can selectively
23692 use @code{pragma Elaborate} statements to convince the static mode of
23693 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
23694 statement.
23696 When using the static mode with @option{-gnatwl}, any use of
23697 @code{pragma Elaborate} will generate a warning about possible
23698 problems.
23700 @node Elaboration Issues for Library Tasks
23701 @section Elaboration Issues for Library Tasks
23702 @cindex Library tasks, elaboration issues
23703 @cindex Elaboration of library tasks
23705 @noindent
23706 In this section we examine special elaboration issues that arise for
23707 programs that declare library level tasks.
23709 Generally the model of execution of an Ada program is that all units are
23710 elaborated, and then execution of the program starts. However, the
23711 declaration of library tasks definitely does not fit this model. The
23712 reason for this is that library tasks start as soon as they are declared
23713 (more precisely, as soon as the statement part of the enclosing package
23714 body is reached), that is to say before elaboration
23715 of the program is complete. This means that if such a task calls a
23716 subprogram, or an entry in another task, the callee may or may not be
23717 elaborated yet, and in the standard
23718 Reference Manual model of dynamic elaboration checks, you can even
23719 get timing dependent Program_Error exceptions, since there can be
23720 a race between the elaboration code and the task code.
23722 The static model of elaboration in GNAT seeks to avoid all such
23723 dynamic behavior, by being conservative, and the conservative
23724 approach in this particular case is to assume that all the code
23725 in a task body is potentially executed at elaboration time if
23726 a task is declared at the library level.
23728 This can definitely result in unexpected circularities. Consider
23729 the following example
23731 @smallexample @c ada
23732 package Decls is
23733   task Lib_Task is
23734      entry Start;
23735   end Lib_Task;
23737   type My_Int is new Integer;
23739   function Ident (M : My_Int) return My_Int;
23740 end Decls;
23742 with Utils;
23743 package body Decls is
23744   task body Lib_Task is
23745   begin
23746      accept Start;
23747      Utils.Put_Val (2);
23748   end Lib_Task;
23750   function Ident (M : My_Int) return My_Int is
23751   begin
23752      return M;
23753   end Ident;
23754 end Decls;
23756 with Decls;
23757 package Utils is
23758   procedure Put_Val (Arg : Decls.My_Int);
23759 end Utils;
23761 with Text_IO;
23762 package body Utils is
23763   procedure Put_Val (Arg : Decls.My_Int) is
23764   begin
23765      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23766   end Put_Val;
23767 end Utils;
23769 with Decls;
23770 procedure Main is
23771 begin
23772    Decls.Lib_Task.Start;
23773 end;
23774 @end smallexample
23776 @noindent
23777 If the above example is compiled in the default static elaboration
23778 mode, then a circularity occurs. The circularity comes from the call
23779 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
23780 this call occurs in elaboration code, we need an implicit pragma
23781 @code{Elaborate_All} for @code{Utils}. This means that not only must
23782 the spec and body of @code{Utils} be elaborated before the body
23783 of @code{Decls}, but also the spec and body of any unit that is
23784 @code{with'ed} by the body of @code{Utils} must also be elaborated before
23785 the body of @code{Decls}. This is the transitive implication of
23786 pragma @code{Elaborate_All} and it makes sense, because in general
23787 the body of @code{Put_Val} might have a call to something in a
23788 @code{with'ed} unit.
23790 In this case, the body of Utils (actually its spec) @code{with's}
23791 @code{Decls}. Unfortunately this means that the body of @code{Decls}
23792 must be elaborated before itself, in case there is a call from the
23793 body of @code{Utils}.
23795 Here is the exact chain of events we are worrying about:
23797 @enumerate
23798 @item
23799 In the body of @code{Decls} a call is made from within the body of a library
23800 task to a subprogram in the package @code{Utils}. Since this call may
23801 occur at elaboration time (given that the task is activated at elaboration
23802 time), we have to assume the worst, i.e. that the
23803 call does happen at elaboration time.
23805 @item
23806 This means that the body and spec of @code{Util} must be elaborated before
23807 the body of @code{Decls} so that this call does not cause an access before
23808 elaboration.
23810 @item
23811 Within the body of @code{Util}, specifically within the body of
23812 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
23813 by this package.
23815 @item
23816 One such @code{with}'ed package is package @code{Decls}, so there
23817 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
23818 In fact there is such a call in this example, but we would have to
23819 assume that there was such a call even if it were not there, since
23820 we are not supposed to write the body of @code{Decls} knowing what
23821 is in the body of @code{Utils}; certainly in the case of the
23822 static elaboration model, the compiler does not know what is in
23823 other bodies and must assume the worst.
23825 @item
23826 This means that the spec and body of @code{Decls} must also be
23827 elaborated before we elaborate the unit containing the call, but
23828 that unit is @code{Decls}! This means that the body of @code{Decls}
23829 must be elaborated before itself, and that's a circularity.
23830 @end enumerate
23832 @noindent
23833 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
23834 the body of @code{Decls} you will get a true Ada Reference Manual
23835 circularity that makes the program illegal.
23837 In practice, we have found that problems with the static model of
23838 elaboration in existing code often arise from library tasks, so
23839 we must address this particular situation.
23841 Note that if we compile and run the program above, using the dynamic model of
23842 elaboration (that is to say use the @option{-gnatE} switch),
23843 then it compiles, binds,
23844 links, and runs, printing the expected result of 2. Therefore in some sense
23845 the circularity here is only apparent, and we need to capture
23846 the properties of this program that  distinguish it from other library-level
23847 tasks that have real elaboration problems.
23849 We have four possible answers to this question:
23851 @itemize @bullet
23853 @item
23854 Use the dynamic model of elaboration.
23856 If we use the @option{-gnatE} switch, then as noted above, the program works.
23857 Why is this? If we examine the task body, it is apparent that the task cannot
23858 proceed past the
23859 @code{accept} statement until after elaboration has been completed, because
23860 the corresponding entry call comes from the main program, not earlier.
23861 This is why the dynamic model works here. But that's really giving
23862 up on a precise analysis, and we prefer to take this approach only if we cannot
23863 solve the
23864 problem in any other manner. So let us examine two ways to reorganize
23865 the program to avoid the potential elaboration problem.
23867 @item
23868 Split library tasks into separate packages.
23870 Write separate packages, so that library tasks are isolated from
23871 other declarations as much as possible. Let us look at a variation on
23872 the above program.
23874 @smallexample @c ada
23875 package Decls1 is
23876   task Lib_Task is
23877      entry Start;
23878   end Lib_Task;
23879 end Decls1;
23881 with Utils;
23882 package body Decls1 is
23883   task body Lib_Task is
23884   begin
23885      accept Start;
23886      Utils.Put_Val (2);
23887   end Lib_Task;
23888 end Decls1;
23890 package Decls2 is
23891   type My_Int is new Integer;
23892   function Ident (M : My_Int) return My_Int;
23893 end Decls2;
23895 with Utils;
23896 package body Decls2 is
23897   function Ident (M : My_Int) return My_Int is
23898   begin
23899      return M;
23900   end Ident;
23901 end Decls2;
23903 with Decls2;
23904 package Utils is
23905   procedure Put_Val (Arg : Decls2.My_Int);
23906 end Utils;
23908 with Text_IO;
23909 package body Utils is
23910   procedure Put_Val (Arg : Decls2.My_Int) is
23911   begin
23912      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
23913   end Put_Val;
23914 end Utils;
23916 with Decls1;
23917 procedure Main is
23918 begin
23919    Decls1.Lib_Task.Start;
23920 end;
23921 @end smallexample
23923 @noindent
23924 All we have done is to split @code{Decls} into two packages, one
23925 containing the library task, and one containing everything else. Now
23926 there is no cycle, and the program compiles, binds, links and executes
23927 using the default static model of elaboration.
23929 @item
23930 Declare separate task types.
23932 A significant part of the problem arises because of the use of the
23933 single task declaration form. This means that the elaboration of
23934 the task type, and the elaboration of the task itself (i.e. the
23935 creation of the task) happen at the same time. A good rule
23936 of style in Ada 95 is to always create explicit task types. By
23937 following the additional step of placing task objects in separate
23938 packages from the task type declaration, many elaboration problems
23939 are avoided. Here is another modified example of the example program:
23941 @smallexample @c ada
23942 package Decls is
23943   task type Lib_Task_Type is
23944      entry Start;
23945   end Lib_Task_Type;
23947   type My_Int is new Integer;
23949   function Ident (M : My_Int) return My_Int;
23950 end Decls;
23952 with Utils;
23953 package body Decls is
23954   task body Lib_Task_Type is
23955   begin
23956      accept Start;
23957      Utils.Put_Val (2);
23958   end Lib_Task_Type;
23960   function Ident (M : My_Int) return My_Int is
23961   begin
23962      return M;
23963   end Ident;
23964 end Decls;
23966 with Decls;
23967 package Utils is
23968   procedure Put_Val (Arg : Decls.My_Int);
23969 end Utils;
23971 with Text_IO;
23972 package body Utils is
23973   procedure Put_Val (Arg : Decls.My_Int) is
23974   begin
23975      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
23976   end Put_Val;
23977 end Utils;
23979 with Decls;
23980 package Declst is
23981    Lib_Task : Decls.Lib_Task_Type;
23982 end Declst;
23984 with Declst;
23985 procedure Main is
23986 begin
23987    Declst.Lib_Task.Start;
23988 end;
23989 @end smallexample
23991 @noindent
23992 What we have done here is to replace the @code{task} declaration in
23993 package @code{Decls} with a @code{task type} declaration. Then we
23994 introduce a separate package @code{Declst} to contain the actual
23995 task object. This separates the elaboration issues for
23996 the @code{task type}
23997 declaration, which causes no trouble, from the elaboration issues
23998 of the task object, which is also unproblematic, since it is now independent
23999 of the elaboration of  @code{Utils}.
24000 This separation of concerns also corresponds to
24001 a generally sound engineering principle of separating declarations
24002 from instances. This version of the program also compiles, binds, links,
24003 and executes, generating the expected output.
24005 @item
24006 Use No_Entry_Calls_In_Elaboration_Code restriction.
24007 @cindex No_Entry_Calls_In_Elaboration_Code
24009 The previous two approaches described how a program can be restructured
24010 to avoid the special problems caused by library task bodies. in practice,
24011 however, such restructuring may be difficult to apply to existing legacy code,
24012 so we must consider solutions that do not require massive rewriting.
24014 Let us consider more carefully why our original sample program works
24015 under the dynamic model of elaboration. The reason is that the code
24016 in the task body blocks immediately on the @code{accept}
24017 statement. Now of course there is nothing to prohibit elaboration
24018 code from making entry calls (for example from another library level task),
24019 so we cannot tell in isolation that
24020 the task will not execute the accept statement  during elaboration.
24022 However, in practice it is very unusual to see elaboration code
24023 make any entry calls, and the pattern of tasks starting
24024 at elaboration time and then immediately blocking on @code{accept} or
24025 @code{select} statements is very common. What this means is that
24026 the compiler is being too pessimistic when it analyzes the
24027 whole package body as though it might be executed at elaboration
24028 time.
24030 If we know that the elaboration code contains no entry calls, (a very safe
24031 assumption most of the time, that could almost be made the default
24032 behavior), then we can compile all units of the program under control
24033 of the following configuration pragma:
24035 @smallexample
24036 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
24037 @end smallexample
24039 @noindent
24040 This pragma can be placed in the @file{gnat.adc} file in the usual
24041 manner. If we take our original unmodified program and compile it
24042 in the presence of a @file{gnat.adc} containing the above pragma,
24043 then once again, we can compile, bind, link, and execute, obtaining
24044 the expected result. In the presence of this pragma, the compiler does
24045 not trace calls in a task body, that appear after the first @code{accept}
24046 or @code{select} statement, and therefore does not report a potential
24047 circularity in the original program.
24049 The compiler will check to the extent it can that the above
24050 restriction is not violated, but it is not always possible to do a
24051 complete check at compile time, so it is important to use this
24052 pragma only if the stated restriction is in fact met, that is to say
24053 no task receives an entry call before elaboration of all units is completed.
24055 @end itemize
24057 @node Mixing Elaboration Models
24058 @section Mixing Elaboration Models
24059 @noindent
24060 So far, we have assumed that the entire program is either compiled
24061 using the dynamic model or static model, ensuring consistency. It
24062 is possible to mix the two models, but rules have to be followed
24063 if this mixing is done to ensure that elaboration checks are not
24064 omitted.
24066 The basic rule is that @emph{a unit compiled with the static model cannot
24067 be @code{with'ed} by a unit compiled with the dynamic model}. The
24068 reason for this is that in the static model, a unit assumes that
24069 its clients guarantee to use (the equivalent of) pragma
24070 @code{Elaborate_All} so that no elaboration checks are required
24071 in inner subprograms, and this assumption is violated if the
24072 client is compiled with dynamic checks.
24074 The precise rule is as follows. A unit that is compiled with dynamic
24075 checks can only @code{with} a unit that meets at least one of the
24076 following criteria:
24078 @itemize @bullet
24080 @item
24081 The @code{with'ed} unit is itself compiled with dynamic elaboration
24082 checks (that is with the @option{-gnatE} switch.
24084 @item
24085 The @code{with'ed} unit is an internal GNAT implementation unit from
24086 the System, Interfaces, Ada, or GNAT hierarchies.
24088 @item
24089 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
24091 @item
24092 The @code{with'ing} unit (that is the client) has an explicit pragma
24093 @code{Elaborate_All} for the @code{with'ed} unit.
24095 @end itemize
24097 @noindent
24098 If this rule is violated, that is if a unit with dynamic elaboration
24099 checks @code{with's} a unit that does not meet one of the above four
24100 criteria, then the binder (@code{gnatbind}) will issue a warning
24101 similar to that in the following example:
24103 @smallexample
24104 warning: "x.ads" has dynamic elaboration checks and with's
24105 warning:   "y.ads" which has static elaboration checks
24106 @end smallexample
24108 @noindent
24109 These warnings indicate that the rule has been violated, and that as a result
24110 elaboration checks may be missed in the resulting executable file.
24111 This warning may be suppressed using the @option{-ws} binder switch
24112 in the usual manner.
24114 One useful application of this mixing rule is in the case of a subsystem
24115 which does not itself @code{with} units from the remainder of the
24116 application. In this case, the entire subsystem can be compiled with
24117 dynamic checks to resolve a circularity in the subsystem, while
24118 allowing the main application that uses this subsystem to be compiled
24119 using the more reliable default static model.
24121 @node What to Do If the Default Elaboration Behavior Fails
24122 @section What to Do If the Default Elaboration Behavior Fails
24124 @noindent
24125 If the binder cannot find an acceptable order, it outputs detailed
24126 diagnostics. For example:
24127 @smallexample
24128 @group
24129 @iftex
24130 @leftskip=0cm
24131 @end iftex
24132 error: elaboration circularity detected
24133 info:   "proc (body)" must be elaborated before "pack (body)"
24134 info:     reason: Elaborate_All probably needed in unit "pack (body)"
24135 info:     recompile "pack (body)" with -gnatwl
24136 info:                             for full details
24137 info:       "proc (body)"
24138 info:         is needed by its spec:
24139 info:       "proc (spec)"
24140 info:         which is withed by:
24141 info:       "pack (body)"
24142 info:  "pack (body)" must be elaborated before "proc (body)"
24143 info:     reason: pragma Elaborate in unit "proc (body)"
24144 @end group
24146 @end smallexample
24148 @noindent
24149 In this case we have a cycle that the binder cannot break. On the one
24150 hand, there is an explicit pragma Elaborate in @code{proc} for
24151 @code{pack}. This means that the body of @code{pack} must be elaborated
24152 before the body of @code{proc}. On the other hand, there is elaboration
24153 code in @code{pack} that calls a subprogram in @code{proc}. This means
24154 that for maximum safety, there should really be a pragma
24155 Elaborate_All in @code{pack} for @code{proc} which would require that
24156 the body of @code{proc} be elaborated before the body of
24157 @code{pack}. Clearly both requirements cannot be satisfied.
24158 Faced with a circularity of this kind, you have three different options.
24160 @table @asis
24161 @item Fix the program
24162 The most desirable option from the point of view of long-term maintenance
24163 is to rearrange the program so that the elaboration problems are avoided.
24164 One useful technique is to place the elaboration code into separate
24165 child packages. Another is to move some of the initialization code to
24166 explicitly called subprograms, where the program controls the order
24167 of initialization explicitly. Although this is the most desirable option,
24168 it may be impractical and involve too much modification, especially in
24169 the case of complex legacy code.
24171 @item Perform dynamic checks
24172 If the compilations are done using the
24173 @option{-gnatE}
24174 (dynamic elaboration check) switch, then GNAT behaves in
24175 a quite different manner. Dynamic checks are generated for all calls
24176 that could possibly result in raising an exception. With this switch,
24177 the compiler does not generate implicit @code{Elaborate_All} pragmas.
24178 The behavior then is exactly as specified in the Ada 95 Reference Manual.
24179 The binder will generate an executable program that may or may not
24180 raise @code{Program_Error}, and then it is the programmer's job to ensure
24181 that it does not raise an exception. Note that it is important to
24182 compile all units with the switch, it cannot be used selectively.
24184 @item Suppress checks
24185 The drawback of dynamic checks is that they generate a
24186 significant overhead at run time, both in space and time. If you
24187 are absolutely sure that your program cannot raise any elaboration
24188 exceptions, and you still want to use the dynamic elaboration model,
24189 then you can use the configuration pragma
24190 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
24191 example this pragma could be placed in the @file{gnat.adc} file.
24193 @item Suppress checks selectively
24194 When you know that certain calls in elaboration code cannot possibly
24195 lead to an elaboration error, and the binder nevertheless generates warnings
24196 on those calls and inserts Elaborate_All pragmas that lead to elaboration
24197 circularities, it is possible to remove those warnings locally and obtain
24198 a program that will bind. Clearly this can be unsafe, and it is the
24199 responsibility of the programmer to make sure that the resulting program has
24200 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
24201 be used with different granularity to suppress warnings and break
24202 elaboration circularities:
24204 @itemize @bullet
24205 @item
24206 Place the pragma that names the called subprogram in the declarative part
24207 that contains the call.
24209 @item
24210 Place the pragma in the declarative part, without naming an entity. This
24211 disables warnings on all calls in the corresponding  declarative region.
24213 @item
24214 Place the pragma in the package spec that declares the called subprogram,
24215 and name the subprogram. This disables warnings on all elaboration calls to
24216 that subprogram.
24218 @item
24219 Place the pragma in the package spec that declares the called subprogram,
24220 without naming any entity. This disables warnings on all elaboration calls to
24221 all subprograms declared in this spec.
24223 @item Use Pragma Elaborate
24224 As previously described in section @xref{Treatment of Pragma Elaborate},
24225 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
24226 that no elaboration checks are required on calls to the designated unit.
24227 There may be cases in which the caller knows that no transitive calls
24228 can occur, so that a @code{pragma Elaborate} will be sufficient in a
24229 case where @code{pragma Elaborate_All} would cause a circularity.
24230 @end itemize
24232 @noindent
24233 These five cases are listed in order of decreasing safety, and therefore
24234 require increasing programmer care in their application. Consider the
24235 following program:
24237 @smallexample @c adanocomment
24238 package Pack1 is
24239   function F1 return Integer;
24240   X1 : Integer;
24241 end Pack1;
24243 package Pack2 is
24244   function F2 return Integer;
24245   function Pure (x : integer) return integer;
24246   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
24247   --  pragma Suppress (Elaboration_Check);              -- (4)
24248 end Pack2;
24250 with Pack2;
24251 package body Pack1 is
24252   function F1 return Integer is
24253   begin
24254     return 100;
24255   end F1;
24256   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
24257 begin
24258   declare
24259     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
24260     --  pragma Suppress(Elaboration_Check);             -- (2)
24261   begin
24262     X1 := Pack2.F2 + 1;                --  Elab. call (2)
24263   end;
24264 end Pack1;
24266 with Pack1;
24267 package body Pack2 is
24268   function F2 return Integer is
24269   begin
24270      return Pack1.F1;
24271   end F2;
24272   function Pure (x : integer) return integer is
24273   begin
24274      return x ** 3 - 3 * x;
24275   end;
24276 end Pack2;
24278 with Pack1, Ada.Text_IO;
24279 procedure Proc3 is
24280 begin
24281   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
24282 end Proc3;
24283 @end smallexample
24284 In the absence of any pragmas, an attempt to bind this program produces
24285 the following diagnostics:
24286 @smallexample
24287 @group
24288 @iftex
24289 @leftskip=.5cm
24290 @end iftex
24291 error: elaboration circularity detected
24292 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
24293 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
24294 info:       recompile "pack1 (body)" with -gnatwl for full details
24295 info:          "pack1 (body)"
24296 info:             must be elaborated along with its spec:
24297 info:          "pack1 (spec)"
24298 info:             which is withed by:
24299 info:          "pack2 (body)"
24300 info:             which must be elaborated along with its spec:
24301 info:          "pack2 (spec)"
24302 info:             which is withed by:
24303 info:          "pack1 (body)"
24304 @end group
24305 @end smallexample
24306 The sources of the circularity are the two calls to @code{Pack2.Pure} and
24307 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
24308 F2 is safe, even though F2 calls F1, because the call appears after the
24309 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
24310 remove the warning on the call. It is also possible to use pragma (2)
24311 because there are no other potentially unsafe calls in the block.
24313 @noindent
24314 The call to @code{Pure} is safe because this function does not depend on the
24315 state of @code{Pack2}. Therefore any call to this function is safe, and it
24316 is correct to place pragma (3) in the corresponding package spec.
24318 @noindent
24319 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
24320 warnings on all calls to functions declared therein. Note that this is not
24321 necessarily safe, and requires more detailed examination of the subprogram
24322 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
24323 be already elaborated.
24324 @end table
24326 @noindent
24327 It is hard to generalize on which of these four approaches should be
24328 taken. Obviously if it is possible to fix the program so that the default
24329 treatment works, this is preferable, but this may not always be practical.
24330 It is certainly simple enough to use
24331 @option{-gnatE}
24332 but the danger in this case is that, even if the GNAT binder
24333 finds a correct elaboration order, it may not always do so,
24334 and certainly a binder from another Ada compiler might not. A
24335 combination of testing and analysis (for which the warnings generated
24336 with the
24337 @option{-gnatwl}
24338 switch can be useful) must be used to ensure that the program is free
24339 of errors. One switch that is useful in this testing is the
24340 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
24341 switch for
24342 @code{gnatbind}.
24343 Normally the binder tries to find an order that has the best chance of
24344 of avoiding elaboration problems. With this switch, the binder
24345 plays a devil's advocate role, and tries to choose the order that
24346 has the best chance of failing. If your program works even with this
24347 switch, then it has a better chance of being error free, but this is still
24348 not a guarantee.
24350 For an example of this approach in action, consider the C-tests (executable
24351 tests) from the ACVC suite. If these are compiled and run with the default
24352 treatment, then all but one of them succeed without generating any error
24353 diagnostics from the binder. However, there is one test that fails, and
24354 this is not surprising, because the whole point of this test is to ensure
24355 that the compiler can handle cases where it is impossible to determine
24356 a correct order statically, and it checks that an exception is indeed
24357 raised at run time.
24359 This one test must be compiled and run using the
24360 @option{-gnatE}
24361 switch, and then it passes. Alternatively, the entire suite can
24362 be run using this switch. It is never wrong to run with the dynamic
24363 elaboration switch if your code is correct, and we assume that the
24364 C-tests are indeed correct (it is less efficient, but efficiency is
24365 not a factor in running the ACVC tests.)
24367 @node Elaboration for Access-to-Subprogram Values
24368 @section Elaboration for Access-to-Subprogram Values
24369 @cindex Access-to-subprogram
24371 @noindent
24372 The introduction of access-to-subprogram types in Ada 95 complicates
24373 the handling of elaboration. The trouble is that it becomes
24374 impossible to tell at compile time which procedure
24375 is being called. This means that it is not possible for the binder
24376 to analyze the elaboration requirements in this case.
24378 If at the point at which the access value is created
24379 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
24380 the body of the subprogram is
24381 known to have been elaborated, then the access value is safe, and its use
24382 does not require a check. This may be achieved by appropriate arrangement
24383 of the order of declarations if the subprogram is in the current unit,
24384 or, if the subprogram is in another unit, by using pragma
24385 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
24386 on the referenced unit.
24388 If the referenced body is not known to have been elaborated at the point
24389 the access value is created, then any use of the access value must do a
24390 dynamic check, and this dynamic check will fail and raise a
24391 @code{Program_Error} exception if the body has not been elaborated yet.
24392 GNAT will generate the necessary checks, and in addition, if the
24393 @option{-gnatwl}
24394 switch is set, will generate warnings that such checks are required.
24396 The use of dynamic dispatching for tagged types similarly generates
24397 a requirement for dynamic checks, and premature calls to any primitive
24398 operation of a tagged type before the body of the operation has been
24399 elaborated, will result in the raising of @code{Program_Error}.
24401 @node Summary of Procedures for Elaboration Control
24402 @section Summary of Procedures for Elaboration Control
24403 @cindex Elaboration control
24405 @noindent
24406 First, compile your program with the default options, using none of
24407 the special elaboration control switches. If the binder successfully
24408 binds your program, then you can be confident that, apart from issues
24409 raised by the use of access-to-subprogram types and dynamic dispatching,
24410 the program is free of elaboration errors. If it is important that the
24411 program be portable, then use the
24412 @option{-gnatwl}
24413 switch to generate warnings about missing @code{Elaborate_All}
24414 pragmas, and supply the missing pragmas.
24416 If the program fails to bind using the default static elaboration
24417 handling, then you can fix the program to eliminate the binder
24418 message, or recompile the entire program with the
24419 @option{-gnatE} switch to generate dynamic elaboration checks,
24420 and, if you are sure there really are no elaboration problems,
24421 use a global pragma @code{Suppress (Elaboration_Check)}.
24423 @node Other Elaboration Order Considerations
24424 @section Other Elaboration Order Considerations
24425 @noindent
24426 This section has been entirely concerned with the issue of finding a valid
24427 elaboration order, as defined by the Ada Reference Manual. In a case
24428 where several elaboration orders are valid, the task is to find one
24429 of the possible valid elaboration orders (and the static model in GNAT
24430 will ensure that this is achieved).
24432 The purpose of the elaboration rules in the Ada Reference Manual is to
24433 make sure that no entity is accessed before it has been elaborated. For
24434 a subprogram, this means that the spec and body must have been elaborated
24435 before the subprogram is called. For an object, this means that the object
24436 must have been elaborated before its value is read or written. A violation
24437 of either of these two requirements is an access before elaboration order,
24438 and this section has been all about avoiding such errors.
24440 In the case where more than one order of elaboration is possible, in the
24441 sense that access before elaboration errors are avoided, then any one of
24442 the orders is ``correct'' in the sense that it meets the requirements of
24443 the Ada Reference Manual, and no such error occurs.
24445 However, it may be the case for a given program, that there are
24446 constraints on the order of elaboration that come not from consideration
24447 of avoiding elaboration errors, but rather from extra-lingual logic
24448 requirements. Consider this example:
24450 @smallexample @c ada
24451 with Init_Constants;
24452 package Constants is
24453    X : Integer := 0;
24454    Y : Integer := 0;
24455 end Constants;
24457 package Init_Constants is
24458    procedure P; -- require a body
24459 end Init_Constants;
24461 with Constants;
24462 package body Init_Constants is
24463    procedure P is begin null; end;
24464 begin
24465    Constants.X := 3;
24466    Constants.Y := 4;
24467 end Init_Constants;
24469 with Constants;
24470 package Calc is
24471    Z : Integer := Constants.X + Constants.Y;
24472 end Calc;
24474 with Calc;
24475 with Text_IO; use Text_IO;
24476 procedure Main is
24477 begin
24478    Put_Line (Calc.Z'Img);
24479 end Main;
24480 @end smallexample
24482 @noindent
24483 In this example, there is more than one valid order of elaboration. For
24484 example both the following are correct orders:
24486 @smallexample
24487 Init_Constants spec
24488 Constants spec
24489 Calc spec
24490 Init_Constants body
24491 Main body
24493   and
24495 Init_Constants spec
24496 Init_Constants body
24497 Constants spec
24498 Calc spec
24499 Main body
24500 @end smallexample
24502 @noindent
24503 There is no language rule to prefer one or the other, both are correct
24504 from an order of elaboration point of view. But the programmatic effects
24505 of the two orders are very different. In the first, the elaboration routine
24506 of @code{Calc} initializes @code{Z} to zero, and then the main program
24507 runs with this value of zero. But in the second order, the elaboration
24508 routine of @code{Calc} runs after the body of Init_Constants has set
24509 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
24510 runs.
24512 One could perhaps by applying pretty clever non-artificial intelligence
24513 to the situation guess that it is more likely that the second order of
24514 elaboration is the one desired, but there is no formal linguistic reason
24515 to prefer one over the other. In fact in this particular case, GNAT will
24516 prefer the second order, because of the rule that bodies are elaborated
24517 as soon as possible, but it's just luck that this is what was wanted
24518 (if indeed the second order was preferred).
24520 If the program cares about the order of elaboration routines in a case like
24521 this, it is important to specify the order required. In this particular
24522 case, that could have been achieved by adding to the spec of Calc:
24524 @smallexample @c ada
24525 pragma Elaborate_All (Constants);
24526 @end smallexample
24528 @noindent
24529 which requires that the body (if any) and spec of @code{Constants},
24530 as well as the body and spec of any unit @code{with}'ed by
24531 @code{Constants} be elaborated before @code{Calc} is elaborated.
24533 Clearly no automatic method can always guess which alternative you require,
24534 and if you are working with legacy code that had constraints of this kind
24535 which were not properly specified by adding @code{Elaborate} or
24536 @code{Elaborate_All} pragmas, then indeed it is possible that two different
24537 compilers can choose different orders.
24539 The @code{gnatbind}
24540 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
24541 out problems. This switch causes bodies to be elaborated as late as possible
24542 instead of as early as possible. In the example above, it would have forced
24543 the choice of the first elaboration order. If you get different results
24544 when using this switch, and particularly if one set of results is right,
24545 and one is wrong as far as you are concerned, it shows that you have some
24546 missing @code{Elaborate} pragmas. For the example above, we have the
24547 following output:
24549 @smallexample
24550 gnatmake -f -q main
24551 main
24553 gnatmake -f -q main -bargs -p
24554 main
24556 @end smallexample
24558 @noindent
24559 It is of course quite unlikely that both these results are correct, so
24560 it is up to you in a case like this to investigate the source of the
24561 difference, by looking at the two elaboration orders that are chosen,
24562 and figuring out which is correct, and then adding the necessary
24563 @code{Elaborate_All} pragmas to ensure the desired order.
24565 @node Inline Assembler
24566 @appendix Inline Assembler
24568 @noindent
24569 If you need to write low-level software that interacts directly
24570 with the hardware, Ada provides two ways to incorporate assembly
24571 language code into your program.  First, you can import and invoke
24572 external routines written in assembly language, an Ada feature fully
24573 supported by GNAT.  However, for small sections of code it may be simpler
24574 or more efficient to include assembly language statements directly
24575 in your Ada source program, using the facilities of the implementation-defined
24576 package @code{System.Machine_Code}, which incorporates the gcc
24577 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
24578 including the following:
24580 @itemize @bullet
24581 @item No need to use non-Ada tools
24582 @item Consistent interface over different targets
24583 @item Automatic usage of the proper calling conventions
24584 @item Access to Ada constants and variables
24585 @item Definition of intrinsic routines
24586 @item Possibility of inlining a subprogram comprising assembler code
24587 @item Code optimizer can take Inline Assembler code into account
24588 @end itemize
24590 This chapter presents a series of examples to show you how to use
24591 the Inline Assembler.  Although it focuses on the Intel x86,
24592 the general approach applies also to other processors.
24593 It is assumed that you are familiar with Ada
24594 and with assembly language programming.
24596 @menu
24597 * Basic Assembler Syntax::
24598 * A Simple Example of Inline Assembler::
24599 * Output Variables in Inline Assembler::
24600 * Input Variables in Inline Assembler::
24601 * Inlining Inline Assembler Code::
24602 * Other Asm Functionality::
24603 * A Complete Example::
24604 @end menu
24606 @c ---------------------------------------------------------------------------
24607 @node Basic Assembler Syntax
24608 @section Basic Assembler Syntax
24610 @noindent
24611 The assembler used by GNAT and gcc is based not on the Intel assembly
24612 language, but rather on a language that descends from the AT&T Unix
24613 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
24614 The following table summarizes the main features of @emph{as} syntax
24615 and points out the differences from the Intel conventions.
24616 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
24617 pre-processor) documentation for further information.
24619 @table @asis
24620 @item Register names
24621 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
24623 Intel: No extra punctuation; for example @code{eax}
24625 @item Immediate operand
24626 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
24628 Intel: No extra punctuation; for example @code{4}
24630 @item Address
24631 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
24633 Intel: No extra punctuation; for example @code{loc}
24635 @item Memory contents
24636 gcc / @emph{as}: No extra punctuation; for example @code{loc}
24638 Intel: Square brackets; for example @code{[loc]}
24640 @item Register contents
24641 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
24643 Intel: Square brackets; for example @code{[eax]}
24645 @item Hexadecimal numbers
24646 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
24648 Intel: Trailing ``h''; for example @code{A0h}
24650 @item Operand size
24651 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
24652 a 16-bit word
24654 Intel: Implicit, deduced by assembler; for example @code{mov}
24656 @item Instruction repetition
24657 gcc / @emph{as}: Split into two lines; for example
24659 @code{rep}
24661 @code{stosl}
24663 Intel: Keep on one line; for example @code{rep stosl}
24665 @item Order of operands
24666 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
24668 Intel: Destination first; for example @code{mov eax, 4}
24669 @end table
24671 @c ---------------------------------------------------------------------------
24672 @node A Simple Example of Inline Assembler
24673 @section A Simple Example of Inline Assembler
24675 @noindent
24676 The following example will generate a single assembly language statement,
24677 @code{nop}, which does nothing.  Despite its lack of run-time effect,
24678 the example will be useful in illustrating the basics of
24679 the Inline Assembler facility.
24681 @smallexample @c ada
24682 @group
24683 with System.Machine_Code; use System.Machine_Code;
24684 procedure Nothing is
24685 begin
24686    Asm ("nop");
24687 end Nothing;
24688 @end group
24689 @end smallexample
24691 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
24692 here it takes one parameter, a @emph{template string} that must be a static
24693 expression and that will form the generated instruction.
24694 @code{Asm} may be regarded as a compile-time procedure that parses
24695 the template string and additional parameters (none here),
24696 from which it generates a sequence of assembly language instructions.
24698 The examples in this chapter will illustrate several of the forms
24699 for invoking @code{Asm}; a complete specification of the syntax
24700 is found in the @cite{GNAT Reference Manual}.
24702 Under the standard GNAT conventions, the @code{Nothing} procedure
24703 should be in a file named @file{nothing.adb}.
24704 You can build the executable in the usual way:
24705 @smallexample
24706 gnatmake nothing
24707 @end smallexample
24708 However, the interesting aspect of this example is not its run-time behavior
24709 but rather the generated assembly code.
24710 To see this output, invoke the compiler as follows:
24711 @smallexample
24712    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
24713 @end smallexample
24714 where the options are:
24716 @table @code
24717 @item -c
24718 compile only (no bind or link)
24719 @item -S
24720 generate assembler listing
24721 @item -fomit-frame-pointer
24722 do not set up separate stack frames
24723 @item -gnatp
24724 do not add runtime checks
24725 @end table
24727 This gives a human-readable assembler version of the code. The resulting
24728 file will have the same name as the Ada source file, but with a @code{.s}
24729 extension. In our example, the file @file{nothing.s} has the following
24730 contents:
24732 @smallexample
24733 @group
24734 .file "nothing.adb"
24735 gcc2_compiled.:
24736 ___gnu_compiled_ada:
24737 .text
24738    .align 4
24739 .globl __ada_nothing
24740 __ada_nothing:
24741 #APP
24742    nop
24743 #NO_APP
24744    jmp L1
24745    .align 2,0x90
24747    ret
24748 @end group
24749 @end smallexample
24751 The assembly code you included is clearly indicated by
24752 the compiler, between the @code{#APP} and @code{#NO_APP}
24753 delimiters. The character before the 'APP' and 'NOAPP'
24754 can differ on different targets. For example, GNU/Linux uses '#APP' while
24755 on NT you will see '/APP'.
24757 If you make a mistake in your assembler code (such as using the
24758 wrong size modifier, or using a wrong operand for the instruction) GNAT
24759 will report this error in a temporary file, which will be deleted when
24760 the compilation is finished.  Generating an assembler file will help
24761 in such cases, since you can assemble this file separately using the
24762 @emph{as} assembler that comes with gcc.
24764 Assembling the file using the command
24766 @smallexample
24767 as @file{nothing.s}
24768 @end smallexample
24769 @noindent
24770 will give you error messages whose lines correspond to the assembler
24771 input file, so you can easily find and correct any mistakes you made.
24772 If there are no errors, @emph{as} will generate an object file
24773 @file{nothing.out}.
24775 @c ---------------------------------------------------------------------------
24776 @node Output Variables in Inline Assembler
24777 @section Output Variables in Inline Assembler
24779 @noindent
24780 The examples in this section, showing how to access the processor flags,
24781 illustrate how to specify the destination operands for assembly language
24782 statements.
24784 @smallexample @c ada
24785 @group
24786 with Interfaces; use Interfaces;
24787 with Ada.Text_IO; use Ada.Text_IO;
24788 with System.Machine_Code; use System.Machine_Code;
24789 procedure Get_Flags is
24790    Flags : Unsigned_32;
24791    use ASCII;
24792 begin
24793    Asm ("pushfl"          & LF & HT & -- push flags on stack
24794         "popl %%eax"      & LF & HT & -- load eax with flags
24795         "movl %%eax, %0",             -- store flags in variable
24796         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24797    Put_Line ("Flags register:" & Flags'Img);
24798 end Get_Flags;
24799 @end group
24800 @end smallexample
24802 In order to have a nicely aligned assembly listing, we have separated
24803 multiple assembler statements in the Asm template string with linefeed
24804 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
24805 The resulting section of the assembly output file is:
24807 @smallexample
24808 @group
24809 #APP
24810    pushfl
24811    popl %eax
24812    movl %eax, -40(%ebp)
24813 #NO_APP
24814 @end group
24815 @end smallexample
24817 It would have been legal to write the Asm invocation as:
24819 @smallexample
24820 Asm ("pushfl popl %%eax movl %%eax, %0")
24821 @end smallexample
24823 but in the generated assembler file, this would come out as:
24825 @smallexample
24826 #APP
24827    pushfl popl %eax movl %eax, -40(%ebp)
24828 #NO_APP
24829 @end smallexample
24831 which is not so convenient for the human reader.
24833 We use Ada comments
24834 at the end of each line to explain what the assembler instructions
24835 actually do.  This is a useful convention.
24837 When writing Inline Assembler instructions, you need to precede each register
24838 and variable name with a percent sign.  Since the assembler already requires
24839 a percent sign at the beginning of a register name, you need two consecutive
24840 percent signs for such names in the Asm template string, thus @code{%%eax}.
24841 In the generated assembly code, one of the percent signs will be stripped off.
24843 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
24844 variables: operands you later define using @code{Input} or @code{Output}
24845 parameters to @code{Asm}.
24846 An output variable is illustrated in
24847 the third statement in the Asm template string:
24848 @smallexample
24849 movl %%eax, %0
24850 @end smallexample
24851 The intent is to store the contents of the eax register in a variable that can
24852 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
24853 necessarily work, since the compiler might optimize by using a register
24854 to hold Flags, and the expansion of the @code{movl} instruction would not be
24855 aware of this optimization.  The solution is not to store the result directly
24856 but rather to advise the compiler to choose the correct operand form;
24857 that is the purpose of the @code{%0} output variable.
24859 Information about the output variable is supplied in the @code{Outputs}
24860 parameter to @code{Asm}:
24861 @smallexample
24862 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24863 @end smallexample
24865 The output is defined by the @code{Asm_Output} attribute of the target type;
24866 the general format is
24867 @smallexample
24868 Type'Asm_Output (constraint_string, variable_name)
24869 @end smallexample
24871 The constraint string directs the compiler how
24872 to store/access the associated variable.  In the example
24873 @smallexample
24874 Unsigned_32'Asm_Output ("=m", Flags);
24875 @end smallexample
24876 the @code{"m"} (memory) constraint tells the compiler that the variable
24877 @code{Flags} should be stored in a memory variable, thus preventing
24878 the optimizer from keeping it in a register.  In contrast,
24879 @smallexample
24880 Unsigned_32'Asm_Output ("=r", Flags);
24881 @end smallexample
24882 uses the @code{"r"} (register) constraint, telling the compiler to
24883 store the variable in a register.
24885 If the constraint is preceded by the equal character (@strong{=}), it tells
24886 the compiler that the variable will be used to store data into it.
24888 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
24889 allowing the optimizer to choose whatever it deems best.
24891 There are a fairly large number of constraints, but the ones that are
24892 most useful (for the Intel x86 processor) are the following:
24894 @table @code
24895 @item =
24896 output constraint
24897 @item g
24898 global (i.e. can be stored anywhere)
24899 @item m
24900 in memory
24901 @item I
24902 a constant
24903 @item a
24904 use eax
24905 @item b
24906 use ebx
24907 @item c
24908 use ecx
24909 @item d
24910 use edx
24911 @item S
24912 use esi
24913 @item D
24914 use edi
24915 @item r
24916 use one of eax, ebx, ecx or edx
24917 @item q
24918 use one of eax, ebx, ecx, edx, esi or edi
24919 @end table
24921 The full set of constraints is described in the gcc and @emph{as}
24922 documentation; note that it is possible to combine certain constraints
24923 in one constraint string.
24925 You specify the association of an output variable with an assembler operand
24926 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
24927 integer.  Thus in
24928 @smallexample @c ada
24929 @group
24930 Asm ("pushfl"          & LF & HT & -- push flags on stack
24931      "popl %%eax"      & LF & HT & -- load eax with flags
24932      "movl %%eax, %0",             -- store flags in variable
24933      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
24934 @end group
24935 @end smallexample
24936 @noindent
24937 @code{%0} will be replaced in the expanded code by the appropriate operand,
24938 whatever
24939 the compiler decided for the @code{Flags} variable.
24941 In general, you may have any number of output variables:
24942 @itemize @bullet
24943 @item
24944 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
24945 @item
24946 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
24947 of @code{Asm_Output} attributes
24948 @end itemize
24950 For example:
24951 @smallexample @c ada
24952 @group
24953 Asm ("movl %%eax, %0" & LF & HT &
24954      "movl %%ebx, %1" & LF & HT &
24955      "movl %%ecx, %2",
24956      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
24957                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
24958                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
24959 @end group
24960 @end smallexample
24961 @noindent
24962 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
24963 in the Ada program.
24965 As a variation on the @code{Get_Flags} example, we can use the constraints
24966 string to direct the compiler to store the eax register into the @code{Flags}
24967 variable, instead of including the store instruction explicitly in the
24968 @code{Asm} template string:
24970 @smallexample @c ada
24971 @group
24972 with Interfaces; use Interfaces;
24973 with Ada.Text_IO; use Ada.Text_IO;
24974 with System.Machine_Code; use System.Machine_Code;
24975 procedure Get_Flags_2 is
24976    Flags : Unsigned_32;
24977    use ASCII;
24978 begin
24979    Asm ("pushfl"      & LF & HT & -- push flags on stack
24980         "popl %%eax",             -- save flags in eax
24981         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
24982    Put_Line ("Flags register:" & Flags'Img);
24983 end Get_Flags_2;
24984 @end group
24985 @end smallexample
24987 @noindent
24988 The @code{"a"} constraint tells the compiler that the @code{Flags}
24989 variable will come from the eax register. Here is the resulting code:
24991 @smallexample
24992 @group
24993 #APP
24994    pushfl
24995    popl %eax
24996 #NO_APP
24997    movl %eax,-40(%ebp)
24998 @end group
24999 @end smallexample
25001 @noindent
25002 The compiler generated the store of eax into Flags after
25003 expanding the assembler code.
25005 Actually, there was no need to pop the flags into the eax register;
25006 more simply, we could just pop the flags directly into the program variable:
25008 @smallexample @c ada
25009 @group
25010 with Interfaces; use Interfaces;
25011 with Ada.Text_IO; use Ada.Text_IO;
25012 with System.Machine_Code; use System.Machine_Code;
25013 procedure Get_Flags_3 is
25014    Flags : Unsigned_32;
25015    use ASCII;
25016 begin
25017    Asm ("pushfl"  & LF & HT & -- push flags on stack
25018         "pop %0",             -- save flags in Flags
25019         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
25020    Put_Line ("Flags register:" & Flags'Img);
25021 end Get_Flags_3;
25022 @end group
25023 @end smallexample
25025 @c ---------------------------------------------------------------------------
25026 @node Input Variables in Inline Assembler
25027 @section Input Variables in Inline Assembler
25029 @noindent
25030 The example in this section illustrates how to specify the source operands
25031 for assembly language statements.
25032 The program simply increments its input value by 1:
25034 @smallexample @c ada
25035 @group
25036 with Interfaces; use Interfaces;
25037 with Ada.Text_IO; use Ada.Text_IO;
25038 with System.Machine_Code; use System.Machine_Code;
25039 procedure Increment is
25041    function Incr (Value : Unsigned_32) return Unsigned_32 is
25042       Result : Unsigned_32;
25043    begin
25044       Asm ("incl %0",
25045            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25046            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25047       return Result;
25048    end Incr;
25050    Value : Unsigned_32;
25052 begin
25053    Value := 5;
25054    Put_Line ("Value before is" & Value'Img);
25055    Value := Incr (Value);
25056    Put_Line ("Value after is" & Value'Img);
25057 end Increment;
25058 @end group
25059 @end smallexample
25061 The @code{Outputs} parameter to @code{Asm} specifies
25062 that the result will be in the eax register and that it is to be stored
25063 in the @code{Result} variable.
25065 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
25066 but with an @code{Asm_Input} attribute.
25067 The @code{"="} constraint, indicating an output value, is not present.
25069 You can have multiple input variables, in the same way that you can have more
25070 than one output variable.
25072 The parameter count (%0, %1) etc, now starts at the first input
25073 statement, and continues with the output statements.
25074 When both parameters use the same variable, the
25075 compiler will treat them as the same %n operand, which is the case here.
25077 Just as the @code{Outputs} parameter causes the register to be stored into the
25078 target variable after execution of the assembler statements, so does the
25079 @code{Inputs} parameter cause its variable to be loaded into the register
25080 before execution of the assembler statements.
25082 Thus the effect of the @code{Asm} invocation is:
25083 @enumerate
25084 @item load the 32-bit value of @code{Value} into eax
25085 @item execute the @code{incl %eax} instruction
25086 @item store the contents of eax into the @code{Result} variable
25087 @end enumerate
25089 The resulting assembler file (with @option{-O2} optimization) contains:
25090 @smallexample
25091 @group
25092 _increment__incr.1:
25093    subl $4,%esp
25094    movl 8(%esp),%eax
25095 #APP
25096    incl %eax
25097 #NO_APP
25098    movl %eax,%edx
25099    movl %ecx,(%esp)
25100    addl $4,%esp
25101    ret
25102 @end group
25103 @end smallexample
25105 @c ---------------------------------------------------------------------------
25106 @node Inlining Inline Assembler Code
25107 @section Inlining Inline Assembler Code
25109 @noindent
25110 For a short subprogram such as the @code{Incr} function in the previous
25111 section, the overhead of the call and return (creating / deleting the stack
25112 frame) can be significant, compared to the amount of code in the subprogram
25113 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
25114 which directs the compiler to expand invocations of the subprogram at the
25115 point(s) of call, instead of setting up a stack frame for out-of-line calls.
25116 Here is the resulting program:
25118 @smallexample @c ada
25119 @group
25120 with Interfaces; use Interfaces;
25121 with Ada.Text_IO; use Ada.Text_IO;
25122 with System.Machine_Code; use System.Machine_Code;
25123 procedure Increment_2 is
25125    function Incr (Value : Unsigned_32) return Unsigned_32 is
25126       Result : Unsigned_32;
25127    begin
25128       Asm ("incl %0",
25129            Inputs  => Unsigned_32'Asm_Input ("a", Value),
25130            Outputs => Unsigned_32'Asm_Output ("=a", Result));
25131       return Result;
25132    end Incr;
25133    pragma Inline (Increment);
25135    Value : Unsigned_32;
25137 begin
25138    Value := 5;
25139    Put_Line ("Value before is" & Value'Img);
25140    Value := Increment (Value);
25141    Put_Line ("Value after is" & Value'Img);
25142 end Increment_2;
25143 @end group
25144 @end smallexample
25146 Compile the program with both optimization (@option{-O2}) and inlining
25147 enabled (@option{-gnatpn} instead of @option{-gnatp}).
25149 The @code{Incr} function is still compiled as usual, but at the
25150 point in @code{Increment} where our function used to be called:
25152 @smallexample
25153 @group
25154 pushl %edi
25155 call _increment__incr.1
25156 @end group
25157 @end smallexample
25159 @noindent
25160 the code for the function body directly appears:
25162 @smallexample
25163 @group
25164 movl %esi,%eax
25165 #APP
25166    incl %eax
25167 #NO_APP
25168    movl %eax,%edx
25169 @end group
25170 @end smallexample
25172 @noindent
25173 thus saving the overhead of stack frame setup and an out-of-line call.
25175 @c ---------------------------------------------------------------------------
25176 @node Other Asm Functionality
25177 @section Other @code{Asm} Functionality
25179 @noindent
25180 This section describes two important parameters to the @code{Asm}
25181 procedure: @code{Clobber}, which identifies register usage;
25182 and @code{Volatile}, which inhibits unwanted optimizations.
25184 @menu
25185 * The Clobber Parameter::
25186 * The Volatile Parameter::
25187 @end menu
25189 @c ---------------------------------------------------------------------------
25190 @node The Clobber Parameter
25191 @subsection The @code{Clobber} Parameter
25193 @noindent
25194 One of the dangers of intermixing assembly language and a compiled language
25195 such as Ada is that the compiler needs to be aware of which registers are
25196 being used by the assembly code.  In some cases, such as the earlier examples,
25197 the constraint string is sufficient to indicate register usage (e.g.,
25198 @code{"a"} for
25199 the eax register).  But more generally, the compiler needs an explicit
25200 identification of the registers that are used by the Inline Assembly
25201 statements.
25203 Using a register that the compiler doesn't know about
25204 could be a side effect of an instruction (like @code{mull}
25205 storing its result in both eax and edx).
25206 It can also arise from explicit register usage in your
25207 assembly code; for example:
25208 @smallexample
25209 @group
25210 Asm ("movl %0, %%ebx" & LF & HT &
25211      "movl %%ebx, %1",
25212      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25213      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
25214 @end group
25215 @end smallexample
25216 @noindent
25217 where the compiler (since it does not analyze the @code{Asm} template string)
25218 does not know you are using the ebx register.
25220 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
25221 to identify the registers that will be used by your assembly code:
25223 @smallexample
25224 @group
25225 Asm ("movl %0, %%ebx" & LF & HT &
25226      "movl %%ebx, %1",
25227      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
25228      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
25229      Clobber => "ebx");
25230 @end group
25231 @end smallexample
25233 The Clobber parameter is a static string expression specifying the
25234 register(s) you are using.  Note that register names are @emph{not} prefixed
25235 by a percent sign. Also, if more than one register is used then their names
25236 are separated by commas; e.g., @code{"eax, ebx"}
25238 The @code{Clobber} parameter has several additional uses:
25239 @enumerate
25240 @item Use ``register'' name @code{cc} to indicate that flags might have changed
25241 @item Use ``register'' name @code{memory} if you changed a memory location
25242 @end enumerate
25244 @c ---------------------------------------------------------------------------
25245 @node The Volatile Parameter
25246 @subsection The @code{Volatile} Parameter
25247 @cindex Volatile parameter
25249 @noindent
25250 Compiler optimizations in the presence of Inline Assembler may sometimes have
25251 unwanted effects.  For example, when an @code{Asm} invocation with an input
25252 variable is inside a loop, the compiler might move the loading of the input
25253 variable outside the loop, regarding it as a one-time initialization.
25255 If this effect is not desired, you can disable such optimizations by setting
25256 the @code{Volatile} parameter to @code{True}; for example:
25258 @smallexample @c ada
25259 @group
25260 Asm ("movl %0, %%ebx" & LF & HT &
25261      "movl %%ebx, %1",
25262      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
25263      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
25264      Clobber  => "ebx",
25265      Volatile => True);
25266 @end group
25267 @end smallexample
25269 By default, @code{Volatile} is set to @code{False} unless there is no
25270 @code{Outputs} parameter.
25272 Although setting @code{Volatile} to @code{True} prevents unwanted
25273 optimizations, it will also disable other optimizations that might be
25274 important for efficiency. In general, you should set @code{Volatile}
25275 to @code{True} only if the compiler's optimizations have created
25276 problems.
25278 @c ---------------------------------------------------------------------------
25279 @node A Complete Example
25280 @section A Complete Example
25282 @noindent
25283 This section contains a complete program illustrating a realistic usage
25284 of GNAT's Inline Assembler capabilities.  It comprises a main procedure
25285 @code{Check_CPU} and a package @code{Intel_CPU}.
25286 The package declares a collection of functions that detect the properties
25287 of the 32-bit x86 processor that is running the program.
25288 The main procedure invokes these functions and displays the information.
25290 The Intel_CPU package could be enhanced by adding functions to
25291 detect the type of x386 co-processor, the processor caching options and
25292 special operations such as the SIMD extensions.
25294 Although the Intel_CPU package has been written for 32-bit Intel
25295 compatible CPUs, it is OS neutral. It has been tested on DOS,
25296 Windows/NT and GNU/Linux.
25298 @menu
25299 * Check_CPU Procedure::
25300 * Intel_CPU Package Specification::
25301 * Intel_CPU Package Body::
25302 @end menu
25304 @c ---------------------------------------------------------------------------
25305 @node Check_CPU Procedure
25306 @subsection @code{Check_CPU} Procedure
25307 @cindex Check_CPU procedure
25309 @smallexample @c adanocomment
25310 ---------------------------------------------------------------------
25311 --                                                                 --
25312 --  Uses the Intel_CPU package to identify the CPU the program is  --
25313 --  running on, and some of the features it supports.              --
25314 --                                                                 --
25315 ---------------------------------------------------------------------
25317 with Intel_CPU;                     --  Intel CPU detection functions
25318 with Ada.Text_IO;                   --  Standard text I/O
25319 with Ada.Command_Line;              --  To set the exit status
25321 procedure Check_CPU is
25323    Type_Found : Boolean := False;
25324    --  Flag to indicate that processor was identified
25326    Features   : Intel_CPU.Processor_Features;
25327    --  The processor features
25329    Signature  : Intel_CPU.Processor_Signature;
25330    --  The processor type signature
25332 begin
25334    -----------------------------------
25335    --  Display the program banner.  --
25336    -----------------------------------
25338    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
25339                          ": check Intel CPU version and features, v1.0");
25340    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
25341    Ada.Text_IO.New_Line;
25343    -----------------------------------------------------------------------
25344    --  We can safely start with the assumption that we are on at least  --
25345    --  a x386 processor. If the CPUID instruction is present, then we   --
25346    --  have a later processor type.                                     --
25347    -----------------------------------------------------------------------
25349    if Intel_CPU.Has_CPUID = False then
25351       --  No CPUID instruction, so we assume this is indeed a x386
25352       --  processor. We can still check if it has a FP co-processor.
25353       if Intel_CPU.Has_FPU then
25354          Ada.Text_IO.Put_Line
25355            ("x386-type processor with a FP co-processor");
25356       else
25357          Ada.Text_IO.Put_Line
25358            ("x386-type processor without a FP co-processor");
25359       end if;  --  check for FPU
25361       --  Program done
25362       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
25363       return;
25365    end if;  --  check for CPUID
25367    -----------------------------------------------------------------------
25368    --  If CPUID is supported, check if this is a true Intel processor,  --
25369    --  if it is not, display a warning.                                 --
25370    -----------------------------------------------------------------------
25372    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
25373       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
25374       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
25375    end if;  --  check if Intel
25377    ----------------------------------------------------------------------
25378    --  With the CPUID instruction present, we can assume at least a    --
25379    --  x486 processor. If the CPUID support level is < 1 then we have  --
25380    --  to leave it at that.                                            --
25381    ----------------------------------------------------------------------
25383    if Intel_CPU.CPUID_Level < 1 then
25385       --  Ok, this is a x486 processor. we still can get the Vendor ID
25386       Ada.Text_IO.Put_Line ("x486-type processor");
25387       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
25389       --  We can also check if there is a FPU present
25390       if Intel_CPU.Has_FPU then
25391          Ada.Text_IO.Put_Line ("Floating-Point support");
25392       else
25393          Ada.Text_IO.Put_Line ("No Floating-Point support");
25394       end if;  --  check for FPU
25396       --  Program done
25397       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
25398       return;
25400    end if;  --  check CPUID level
25402    ---------------------------------------------------------------------
25403    --  With a CPUID level of 1 we can use the processor signature to  --
25404    --  determine it's exact type.                                     --
25405    ---------------------------------------------------------------------
25407    Signature := Intel_CPU.Signature;
25409    ----------------------------------------------------------------------
25410    --  Ok, now we go into a lot of messy comparisons to get the        --
25411    --  processor type. For clarity, no attememt to try to optimize the --
25412    --  comparisons has been made. Note that since Intel_CPU does not   --
25413    --  support getting cache info, we cannot distinguish between P5    --
25414    --  and Celeron types yet.                                          --
25415    ----------------------------------------------------------------------
25417    --  x486SL
25418    if Signature.Processor_Type = 2#00#   and
25419      Signature.Family          = 2#0100# and
25420      Signature.Model           = 2#0100# then
25421       Type_Found := True;
25422       Ada.Text_IO.Put_Line ("x486SL processor");
25423    end if;
25425    --  x486DX2 Write-Back
25426    if Signature.Processor_Type = 2#00#   and
25427      Signature.Family          = 2#0100# and
25428      Signature.Model           = 2#0111# then
25429       Type_Found := True;
25430       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
25431    end if;
25433    --  x486DX4
25434    if Signature.Processor_Type = 2#00#   and
25435      Signature.Family          = 2#0100# and
25436      Signature.Model           = 2#1000# then
25437       Type_Found := True;
25438       Ada.Text_IO.Put_Line ("x486DX4 processor");
25439    end if;
25441    --  x486DX4 Overdrive
25442    if Signature.Processor_Type = 2#01#   and
25443      Signature.Family          = 2#0100# and
25444      Signature.Model           = 2#1000# then
25445       Type_Found := True;
25446       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
25447    end if;
25449    --  Pentium (60, 66)
25450    if Signature.Processor_Type = 2#00#   and
25451      Signature.Family          = 2#0101# and
25452      Signature.Model           = 2#0001# then
25453       Type_Found := True;
25454       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
25455    end if;
25457    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
25458    if Signature.Processor_Type = 2#00#   and
25459      Signature.Family          = 2#0101# and
25460      Signature.Model           = 2#0010# then
25461       Type_Found := True;
25462       Ada.Text_IO.Put_Line
25463         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
25464    end if;
25466    --  Pentium OverDrive (60, 66)
25467    if Signature.Processor_Type = 2#01#   and
25468      Signature.Family          = 2#0101# and
25469      Signature.Model           = 2#0001# then
25470       Type_Found := True;
25471       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
25472    end if;
25474    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
25475    if Signature.Processor_Type = 2#01#   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 OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
25481    end if;
25483    --  Pentium OverDrive processor for x486 processor-based systems
25484    if Signature.Processor_Type = 2#01#   and
25485      Signature.Family          = 2#0101# and
25486      Signature.Model           = 2#0011# then
25487       Type_Found := True;
25488       Ada.Text_IO.Put_Line
25489         ("Pentium OverDrive processor for x486 processor-based systems");
25490    end if;
25492    --  Pentium processor with MMX technology (166, 200)
25493    if Signature.Processor_Type = 2#00#   and
25494      Signature.Family          = 2#0101# and
25495      Signature.Model           = 2#0100# then
25496       Type_Found := True;
25497       Ada.Text_IO.Put_Line
25498         ("Pentium processor with MMX technology (166, 200)");
25499    end if;
25501    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
25502    if Signature.Processor_Type = 2#01#   and
25503      Signature.Family          = 2#0101# and
25504      Signature.Model           = 2#0100# then
25505       Type_Found := True;
25506       Ada.Text_IO.Put_Line
25507         ("Pentium OverDrive processor with MMX " &
25508          "technology for Pentium processor (75, 90, 100, 120, 133)");
25509    end if;
25511    --  Pentium Pro processor
25512    if Signature.Processor_Type = 2#00#   and
25513      Signature.Family          = 2#0110# and
25514      Signature.Model           = 2#0001# then
25515       Type_Found := True;
25516       Ada.Text_IO.Put_Line ("Pentium Pro processor");
25517    end if;
25519    --  Pentium II processor, model 3
25520    if Signature.Processor_Type = 2#00#   and
25521      Signature.Family          = 2#0110# and
25522      Signature.Model           = 2#0011# then
25523       Type_Found := True;
25524       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
25525    end if;
25527    --  Pentium II processor, model 5 or Celeron processor
25528    if Signature.Processor_Type = 2#00#   and
25529      Signature.Family          = 2#0110# and
25530      Signature.Model           = 2#0101# then
25531       Type_Found := True;
25532       Ada.Text_IO.Put_Line
25533         ("Pentium II processor, model 5 or Celeron processor");
25534    end if;
25536    --  Pentium Pro OverDrive processor
25537    if Signature.Processor_Type = 2#01#   and
25538      Signature.Family          = 2#0110# and
25539      Signature.Model           = 2#0011# then
25540       Type_Found := True;
25541       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
25542    end if;
25544    --  If no type recognized, we have an unknown. Display what
25545    --  we _do_ know
25546    if Type_Found = False then
25547       Ada.Text_IO.Put_Line ("Unknown processor");
25548    end if;
25550    -----------------------------------------
25551    --  Display processor stepping level.  --
25552    -----------------------------------------
25554    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
25556    ---------------------------------
25557    --  Display vendor ID string.  --
25558    ---------------------------------
25560    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
25562    ------------------------------------
25563    --  Get the processors features.  --
25564    ------------------------------------
25566    Features := Intel_CPU.Features;
25568    -----------------------------
25569    --  Check for a FPU unit.  --
25570    -----------------------------
25572    if Features.FPU = True then
25573       Ada.Text_IO.Put_Line ("Floating-Point unit available");
25574    else
25575       Ada.Text_IO.Put_Line ("no Floating-Point unit");
25576    end if;  --  check for FPU
25578    --------------------------------
25579    --  List processor features.  --
25580    --------------------------------
25582    Ada.Text_IO.Put_Line ("Supported features: ");
25584    --  Virtual Mode Extension
25585    if Features.VME = True then
25586       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
25587    end if;
25589    --  Debugging Extension
25590    if Features.DE = True then
25591       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
25592    end if;
25594    --  Page Size Extension
25595    if Features.PSE = True then
25596       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
25597    end if;
25599    --  Time Stamp Counter
25600    if Features.TSC = True then
25601       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
25602    end if;
25604    --  Model Specific Registers
25605    if Features.MSR = True then
25606       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
25607    end if;
25609    --  Physical Address Extension
25610    if Features.PAE = True then
25611       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
25612    end if;
25614    --  Machine Check Extension
25615    if Features.MCE = True then
25616       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
25617    end if;
25619    --  CMPXCHG8 instruction supported
25620    if Features.CX8 = True then
25621       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
25622    end if;
25624    --  on-chip APIC hardware support
25625    if Features.APIC = True then
25626       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
25627    end if;
25629    --  Fast System Call
25630    if Features.SEP = True then
25631       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
25632    end if;
25634    --  Memory Type Range Registers
25635    if Features.MTRR = True then
25636       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
25637    end if;
25639    --  Page Global Enable
25640    if Features.PGE = True then
25641       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
25642    end if;
25644    --  Machine Check Architecture
25645    if Features.MCA = True then
25646       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
25647    end if;
25649    --  Conditional Move Instruction Supported
25650    if Features.CMOV = True then
25651       Ada.Text_IO.Put_Line
25652         ("    CMOV   - Conditional Move Instruction Supported");
25653    end if;
25655    --  Page Attribute Table
25656    if Features.PAT = True then
25657       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
25658    end if;
25660    --  36-bit Page Size Extension
25661    if Features.PSE_36 = True then
25662       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
25663    end if;
25665    --  MMX technology supported
25666    if Features.MMX = True then
25667       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
25668    end if;
25670    --  Fast FP Save and Restore
25671    if Features.FXSR = True then
25672       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
25673    end if;
25675    ---------------------
25676    --  Program done.  --
25677    ---------------------
25679    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
25681 exception
25683    when others =>
25684       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
25685       raise;
25687 end Check_CPU;
25688 @end smallexample
25690 @c ---------------------------------------------------------------------------
25691 @node Intel_CPU Package Specification
25692 @subsection @code{Intel_CPU} Package Specification
25693 @cindex Intel_CPU package specification
25695 @smallexample @c adanocomment
25696 -------------------------------------------------------------------------
25697 --                                                                     --
25698 --  file: intel_cpu.ads                                                --
25699 --                                                                     --
25700 --           *********************************************             --
25701 --           * WARNING: for 32-bit Intel processors only *             --
25702 --           *********************************************             --
25703 --                                                                     --
25704 --  This package contains a number of subprograms that are useful in   --
25705 --  determining the Intel x86 CPU (and the features it supports) on    --
25706 --  which the program is running.                                      --
25707 --                                                                     --
25708 --  The package is based upon the information given in the Intel       --
25709 --  Application Note AP-485: "Intel Processor Identification and the   --
25710 --  CPUID Instruction" as of April 1998. This application note can be  --
25711 --  found on www.intel.com.                                            --
25712 --                                                                     --
25713 --  It currently deals with 32-bit processors only, will not detect    --
25714 --  features added after april 1998, and does not guarantee proper     --
25715 --  results on Intel-compatible processors.                            --
25716 --                                                                     --
25717 --  Cache info and x386 fpu type detection are not supported.          --
25718 --                                                                     --
25719 --  This package does not use any privileged instructions, so should   --
25720 --  work on any OS running on a 32-bit Intel processor.                --
25721 --                                                                     --
25722 -------------------------------------------------------------------------
25724 with Interfaces;             use Interfaces;
25725 --  for using unsigned types
25727 with System.Machine_Code;    use System.Machine_Code;
25728 --  for using inline assembler code
25730 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
25731 --  for inserting control characters
25733 package Intel_CPU is
25735    ----------------------
25736    --  Processor bits  --
25737    ----------------------
25739    subtype Num_Bits is Natural range 0 .. 31;
25740    --  the number of processor bits (32)
25742    --------------------------
25743    --  Processor register  --
25744    --------------------------
25746    --  define a processor register type for easy access to
25747    --  the individual bits
25749    type Processor_Register is array (Num_Bits) of Boolean;
25750    pragma Pack (Processor_Register);
25751    for Processor_Register'Size use 32;
25753    -------------------------
25754    --  Unsigned register  --
25755    -------------------------
25757    --  define a processor register type for easy access to
25758    --  the individual bytes
25760    type Unsigned_Register is
25761       record
25762          L1 : Unsigned_8;
25763          H1 : Unsigned_8;
25764          L2 : Unsigned_8;
25765          H2 : Unsigned_8;
25766       end record;
25768    for Unsigned_Register use
25769       record
25770          L1 at 0 range  0 ..  7;
25771          H1 at 0 range  8 .. 15;
25772          L2 at 0 range 16 .. 23;
25773          H2 at 0 range 24 .. 31;
25774       end record;
25776    for Unsigned_Register'Size use 32;
25778    ---------------------------------
25779    --  Intel processor vendor ID  --
25780    ---------------------------------
25782    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
25783    --  indicates an Intel manufactured processor
25785    ------------------------------------
25786    --  Processor signature register  --
25787    ------------------------------------
25789    --  a register type to hold the processor signature
25791    type Processor_Signature is
25792       record
25793          Stepping       : Natural range 0 .. 15;
25794          Model          : Natural range 0 .. 15;
25795          Family         : Natural range 0 .. 15;
25796          Processor_Type : Natural range 0 .. 3;
25797          Reserved       : Natural range 0 .. 262143;
25798       end record;
25800    for Processor_Signature use
25801       record
25802          Stepping       at 0 range  0 ..  3;
25803          Model          at 0 range  4 ..  7;
25804          Family         at 0 range  8 .. 11;
25805          Processor_Type at 0 range 12 .. 13;
25806          Reserved       at 0 range 14 .. 31;
25807       end record;
25809    for Processor_Signature'Size use 32;
25811    -----------------------------------
25812    --  Processor features register  --
25813    -----------------------------------
25815    --  a processor register to hold the processor feature flags
25817    type Processor_Features is
25818       record
25819          FPU    : Boolean;                --  floating point unit on chip
25820          VME    : Boolean;                --  virtual mode extension
25821          DE     : Boolean;                --  debugging extension
25822          PSE    : Boolean;                --  page size extension
25823          TSC    : Boolean;                --  time stamp counter
25824          MSR    : Boolean;                --  model specific registers
25825          PAE    : Boolean;                --  physical address extension
25826          MCE    : Boolean;                --  machine check extension
25827          CX8    : Boolean;                --  cmpxchg8 instruction
25828          APIC   : Boolean;                --  on-chip apic hardware
25829          Res_1  : Boolean;                --  reserved for extensions
25830          SEP    : Boolean;                --  fast system call
25831          MTRR   : Boolean;                --  memory type range registers
25832          PGE    : Boolean;                --  page global enable
25833          MCA    : Boolean;                --  machine check architecture
25834          CMOV   : Boolean;                --  conditional move supported
25835          PAT    : Boolean;                --  page attribute table
25836          PSE_36 : Boolean;                --  36-bit page size extension
25837          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
25838          MMX    : Boolean;                --  MMX technology supported
25839          FXSR   : Boolean;                --  fast FP save and restore
25840          Res_3  : Natural range 0 .. 127; --  reserved for extensions
25841       end record;
25843    for Processor_Features use
25844       record
25845          FPU    at 0 range  0 ..  0;
25846          VME    at 0 range  1 ..  1;
25847          DE     at 0 range  2 ..  2;
25848          PSE    at 0 range  3 ..  3;
25849          TSC    at 0 range  4 ..  4;
25850          MSR    at 0 range  5 ..  5;
25851          PAE    at 0 range  6 ..  6;
25852          MCE    at 0 range  7 ..  7;
25853          CX8    at 0 range  8 ..  8;
25854          APIC   at 0 range  9 ..  9;
25855          Res_1  at 0 range 10 .. 10;
25856          SEP    at 0 range 11 .. 11;
25857          MTRR   at 0 range 12 .. 12;
25858          PGE    at 0 range 13 .. 13;
25859          MCA    at 0 range 14 .. 14;
25860          CMOV   at 0 range 15 .. 15;
25861          PAT    at 0 range 16 .. 16;
25862          PSE_36 at 0 range 17 .. 17;
25863          Res_2  at 0 range 18 .. 22;
25864          MMX    at 0 range 23 .. 23;
25865          FXSR   at 0 range 24 .. 24;
25866          Res_3  at 0 range 25 .. 31;
25867       end record;
25869    for Processor_Features'Size use 32;
25871    -------------------
25872    --  Subprograms  --
25873    -------------------
25875    function Has_FPU return Boolean;
25876    --  return True if a FPU is found
25877    --  use only if CPUID is not supported
25879    function Has_CPUID return Boolean;
25880    --  return True if the processor supports the CPUID instruction
25882    function CPUID_Level return Natural;
25883    --  return the CPUID support level (0, 1 or 2)
25884    --  can only be called if the CPUID instruction is supported
25886    function Vendor_ID return String;
25887    --  return the processor vendor identification string
25888    --  can only be called if the CPUID instruction is supported
25890    function Signature return Processor_Signature;
25891    --  return the processor signature
25892    --  can only be called if the CPUID instruction is supported
25894    function Features return Processor_Features;
25895    --  return the processors features
25896    --  can only be called if the CPUID instruction is supported
25898 private
25900    ------------------------
25901    --  EFLAGS bit names  --
25902    ------------------------
25904    ID_Flag : constant Num_Bits := 21;
25905    --  ID flag bit
25907 end Intel_CPU;
25908 @end smallexample
25910 @c ---------------------------------------------------------------------------
25911 @node Intel_CPU Package Body
25912 @subsection @code{Intel_CPU} Package Body
25913 @cindex Intel_CPU package body
25915 @smallexample @c adanocomment
25916 package body Intel_CPU is
25918    ---------------------------
25919    --  Detect FPU presence  --
25920    ---------------------------
25922    --  There is a FPU present if we can set values to the FPU Status
25923    --  and Control Words.
25925    function Has_FPU return Boolean is
25927       Register : Unsigned_16;
25928       --  processor register to store a word
25930    begin
25932       --  check if we can change the status word
25933       Asm (
25935            --  the assembler code
25936            "finit"              & LF & HT &    --  reset status word
25937            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
25938            "fnstsw %0"          & LF & HT &    --  save status word
25939            "movw %%ax, %0",                    --  store status word
25941            --  output stored in Register
25942            --  register must be a memory location
25943            Outputs => Unsigned_16'Asm_output ("=m", Register),
25945            --  tell compiler that we used eax
25946            Clobber => "eax");
25948       --  if the status word is zero, there is no FPU
25949       if Register = 0 then
25950          return False;   --  no status word
25951       end if;  --  check status word value
25953       --  check if we can get the control word
25954       Asm (
25956            --  the assembler code
25957            "fnstcw %0",   --  save the control word
25959            --  output into Register
25960            --  register must be a memory location
25961            Outputs => Unsigned_16'Asm_output ("=m", Register));
25963       --  check the relevant bits
25964       if (Register and 16#103F#) /= 16#003F# then
25965          return False;   --  no control word
25966       end if;  --  check control word value
25968       --  FPU found
25969       return True;
25971    end Has_FPU;
25973    --------------------------------
25974    --  Detect CPUID instruction  --
25975    --------------------------------
25977    --  The processor supports the CPUID instruction if it is possible
25978    --  to change the value of ID flag bit in the EFLAGS register.
25980    function Has_CPUID return Boolean is
25982       Original_Flags, Modified_Flags : Processor_Register;
25983       --  EFLAG contents before and after changing the ID flag
25985    begin
25987       --  try flipping the ID flag in the EFLAGS register
25988       Asm (
25990            --  the assembler code
25991            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25992            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
25993            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
25994            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
25995            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
25996            "popfl"                & LF & HT &     --  load EFLAGS register
25997            "pushfl"               & LF & HT &     --  push EFLAGS on stack
25998            "pop %1",                              --  save EFLAGS content
26000            --  output values, may be anything
26001            --  Original_Flags is %0
26002            --  Modified_Flags is %1
26003            Outputs =>
26004               (Processor_Register'Asm_output ("=g", Original_Flags),
26005                Processor_Register'Asm_output ("=g", Modified_Flags)),
26007            --  tell compiler eax is destroyed
26008            Clobber => "eax");
26010       --  check if CPUID is supported
26011       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
26012          return True;   --  ID flag was modified
26013       else
26014          return False;  --  ID flag unchanged
26015       end if;  --  check for CPUID
26017    end Has_CPUID;
26019    -------------------------------
26020    --  Get CPUID support level  --
26021    -------------------------------
26023    function CPUID_Level return Natural is
26025       Level : Unsigned_32;
26026       --  returned support level
26028    begin
26030       --  execute CPUID, storing the results in the Level register
26031       Asm (
26033            --  the assembler code
26034            "cpuid",    --  execute CPUID
26036            --  zero is stored in eax
26037            --  returning the support level in eax
26038            Inputs => Unsigned_32'Asm_input ("a", 0),
26040            --  eax is stored in Level
26041            Outputs => Unsigned_32'Asm_output ("=a", Level),
26043            --  tell compiler ebx, ecx and edx registers are destroyed
26044            Clobber => "ebx, ecx, edx");
26046       --  return the support level
26047       return Natural (Level);
26049    end CPUID_Level;
26051    --------------------------------
26052    --  Get CPU Vendor ID String  --
26053    --------------------------------
26055    --  The vendor ID string is returned in the ebx, ecx and edx register
26056    --  after executing the CPUID instruction with eax set to zero.
26057    --  In case of a true Intel processor the string returned is
26058    --  "GenuineIntel"
26060    function Vendor_ID return String is
26062       Ebx, Ecx, Edx : Unsigned_Register;
26063       --  registers containing the vendor ID string
26065       Vendor_ID : String (1 .. 12);
26066       -- the vendor ID string
26068    begin
26070       --  execute CPUID, storing the results in the processor registers
26071       Asm (
26073            --  the assembler code
26074            "cpuid",    --  execute CPUID
26076            --  zero stored in eax
26077            --  vendor ID string returned in ebx, ecx and edx
26078            Inputs => Unsigned_32'Asm_input ("a", 0),
26080            --  ebx is stored in Ebx
26081            --  ecx is stored in Ecx
26082            --  edx is stored in Edx
26083            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
26084                        Unsigned_Register'Asm_output ("=c", Ecx),
26085                        Unsigned_Register'Asm_output ("=d", Edx)));
26087       --  now build the vendor ID string
26088       Vendor_ID( 1) := Character'Val (Ebx.L1);
26089       Vendor_ID( 2) := Character'Val (Ebx.H1);
26090       Vendor_ID( 3) := Character'Val (Ebx.L2);
26091       Vendor_ID( 4) := Character'Val (Ebx.H2);
26092       Vendor_ID( 5) := Character'Val (Edx.L1);
26093       Vendor_ID( 6) := Character'Val (Edx.H1);
26094       Vendor_ID( 7) := Character'Val (Edx.L2);
26095       Vendor_ID( 8) := Character'Val (Edx.H2);
26096       Vendor_ID( 9) := Character'Val (Ecx.L1);
26097       Vendor_ID(10) := Character'Val (Ecx.H1);
26098       Vendor_ID(11) := Character'Val (Ecx.L2);
26099       Vendor_ID(12) := Character'Val (Ecx.H2);
26101       --  return string
26102       return Vendor_ID;
26104    end Vendor_ID;
26106    -------------------------------
26107    --  Get processor signature  --
26108    -------------------------------
26110    function Signature return Processor_Signature is
26112       Result : Processor_Signature;
26113       --  processor signature returned
26115    begin
26117       --  execute CPUID, storing the results in the Result variable
26118       Asm (
26120            --  the assembler code
26121            "cpuid",    --  execute CPUID
26123            --  one is stored in eax
26124            --  processor signature returned in eax
26125            Inputs => Unsigned_32'Asm_input ("a", 1),
26127            --  eax is stored in Result
26128            Outputs => Processor_Signature'Asm_output ("=a", Result),
26130            --  tell compiler that ebx, ecx and edx are also destroyed
26131            Clobber => "ebx, ecx, edx");
26133       --  return processor signature
26134       return Result;
26136    end Signature;
26138    ------------------------------
26139    --  Get processor features  --
26140    ------------------------------
26142    function Features return Processor_Features is
26144       Result : Processor_Features;
26145       --  processor features returned
26147    begin
26149       --  execute CPUID, storing the results in the Result variable
26150       Asm (
26152            --  the assembler code
26153            "cpuid",    --  execute CPUID
26155            --  one stored in eax
26156            --  processor features returned in edx
26157            Inputs => Unsigned_32'Asm_input ("a", 1),
26159            --  edx is stored in Result
26160            Outputs => Processor_Features'Asm_output ("=d", Result),
26162            --  tell compiler that ebx and ecx are also destroyed
26163            Clobber => "ebx, ecx");
26165       --  return processor signature
26166       return Result;
26168    end Features;
26170 end Intel_CPU;
26171 @end smallexample
26172 @c END OF INLINE ASSEMBLER CHAPTER
26173 @c ===============================
26175 @c ***********************************
26176 @c * Compatibility and Porting Guide *
26177 @c ***********************************
26178 @node Compatibility and Porting Guide
26179 @appendix Compatibility and Porting Guide
26181 @noindent
26182 This chapter describes the compatibility issues that may arise between
26183 GNAT and other Ada 83 and Ada 95 compilation systems, and shows how GNAT
26184 can expedite porting
26185 applications developed in other Ada environments.
26187 @menu
26188 * Compatibility with Ada 83::
26189 * Implementation-dependent characteristics::
26190 * Compatibility with Other Ada 95 Systems::
26191 * Representation Clauses::
26192 * Compatibility with DEC Ada 83::
26193 @ifset vms
26194 * Transitioning from Alpha to Integrity OpenVMS::
26195 @end ifset
26196 @end menu
26198 @node Compatibility with Ada 83
26199 @section Compatibility with Ada 83
26200 @cindex Compatibility (between Ada 83 and Ada 95)
26202 @noindent
26203 Ada 95 is designed to be highly upwards compatible with Ada 83.  In
26204 particular, the design intention is that the difficulties associated
26205 with moving from Ada 83 to Ada 95 should be no greater than those
26206 that occur when moving from one Ada 83 system to another.
26208 However, there are a number of points at which there are minor
26209 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
26210 full details of these issues,
26211 and should be consulted for a complete treatment.
26212 In practice the
26213 following subsections treat the most likely issues to be encountered.
26215 @menu
26216 * Legal Ada 83 programs that are illegal in Ada 95::
26217 * More deterministic semantics::
26218 * Changed semantics::
26219 * Other language compatibility issues::
26220 @end menu
26222 @node Legal Ada 83 programs that are illegal in Ada 95
26223 @subsection Legal Ada 83 programs that are illegal in Ada 95
26225 @table @asis
26226 @item Character literals
26227 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
26228 @code{Wide_Character} as a new predefined character type, some uses of
26229 character literals that were legal in Ada 83 are illegal in Ada 95.
26230 For example:
26231 @smallexample @c ada
26232    for Char in 'A' .. 'Z' loop ... end loop;
26233 @end smallexample
26234 @noindent
26235 The problem is that @code{'A'} and @code{'Z'} could be from either
26236 @code{Character} or @code{Wide_Character}.  The simplest correction
26237 is to make the type explicit; e.g.:
26238 @smallexample @c ada
26239    for Char in Character range 'A' .. 'Z' loop ... end loop;
26240 @end smallexample
26242 @item New reserved words
26243 The identifiers @code{abstract}, @code{aliased}, @code{protected},
26244 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
26245 Existing Ada 83 code using any of these identifiers must be edited to
26246 use some alternative name.
26248 @item Freezing rules
26249 The rules in Ada 95 are slightly different with regard to the point at
26250 which entities are frozen, and representation pragmas and clauses are
26251 not permitted past the freeze point.  This shows up most typically in
26252 the form of an error message complaining that a representation item
26253 appears too late, and the appropriate corrective action is to move
26254 the item nearer to the declaration of the entity to which it refers.
26256 A particular case is that representation pragmas
26257 @ifset vms
26258 (including the
26259 extended DEC Ada 83 compatibility pragmas such as @code{Export_Procedure})
26260 @end ifset
26261 cannot be applied to a subprogram body.  If necessary, a separate subprogram
26262 declaration must be introduced to which the pragma can be applied.
26264 @item Optional bodies for library packages
26265 In Ada 83, a package that did not require a package body was nevertheless
26266 allowed to have one.  This lead to certain surprises in compiling large
26267 systems (situations in which the body could be unexpectedly ignored by the
26268 binder).  In Ada 95, if a package does not require a body then it is not
26269 permitted to have a body.  To fix this problem, simply remove a redundant
26270 body if it is empty, or, if it is non-empty, introduce a dummy declaration
26271 into the spec that makes the body required.  One approach is to add a private
26272 part to the package declaration (if necessary), and define a parameterless
26273 procedure called @code{Requires_Body}, which must then be given a dummy
26274 procedure body in the package body, which then becomes required.
26275 Another approach (assuming that this does not introduce elaboration
26276 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
26277 since one effect of this pragma is to require the presence of a package body.
26279 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
26280 In Ada 95, the exception @code{Numeric_Error} is a renaming of
26281 @code{Constraint_Error}.
26282 This means that it is illegal to have separate exception handlers for
26283 the two exceptions.  The fix is simply to remove the handler for the
26284 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
26285 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
26287 @item Indefinite subtypes in generics
26288 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
26289 as the actual for a generic formal private type, but then the instantiation
26290 would be illegal if there were any instances of declarations of variables
26291 of this type in the generic body.  In Ada 95, to avoid this clear violation
26292 of the methodological principle known as the ``contract model'',
26293 the generic declaration explicitly indicates whether
26294 or not such instantiations are permitted.  If a generic formal parameter
26295 has explicit unknown discriminants, indicated by using @code{(<>)} after the
26296 type name, then it can be instantiated with indefinite types, but no
26297 stand-alone variables can be declared of this type.  Any attempt to declare
26298 such a variable will result in an illegality at the time the generic is
26299 declared.  If the @code{(<>)} notation is not used, then it is illegal
26300 to instantiate the generic with an indefinite type.
26301 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
26302 It will show up as a compile time error, and
26303 the fix is usually simply to add the @code{(<>)} to the generic declaration.
26304 @end table
26306 @node More deterministic semantics
26307 @subsection More deterministic semantics
26309 @table @asis
26310 @item Conversions
26311 Conversions from real types to integer types round away from 0.  In Ada 83
26312 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
26313 implementation freedom was intended to support unbiased rounding in
26314 statistical applications, but in practice it interfered with portability.
26315 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
26316 is required.  Numeric code may be affected by this change in semantics.
26317 Note, though, that this issue is no worse than already existed in Ada 83
26318 when porting code from one vendor to another.
26320 @item Tasking
26321 The Real-Time Annex introduces a set of policies that define the behavior of
26322 features that were implementation dependent in Ada 83, such as the order in
26323 which open select branches are executed.
26324 @end table
26326 @node Changed semantics
26327 @subsection Changed semantics
26329 @noindent
26330 The worst kind of incompatibility is one where a program that is legal in
26331 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
26332 possible in Ada 83.  Fortunately this is extremely rare, but the one
26333 situation that you should be alert to is the change in the predefined type
26334 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
26336 @table @asis
26337 @item range of @code{Character}
26338 The range of @code{Standard.Character} is now the full 256 characters
26339 of Latin-1, whereas in most Ada 83 implementations it was restricted
26340 to 128 characters. Although some of the effects of
26341 this change will be manifest in compile-time rejection of legal
26342 Ada 83 programs it is possible for a working Ada 83 program to have
26343 a different effect in Ada 95, one that was not permitted in Ada 83.
26344 As an example, the expression
26345 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
26346 delivers @code{255} as its value.
26347 In general, you should look at the logic of any
26348 character-processing Ada 83 program and see whether it needs to be adapted
26349 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
26350 character handling package that may be relevant if code needs to be adapted
26351 to account for the additional Latin-1 elements.
26352 The desirable fix is to
26353 modify the program to accommodate the full character set, but in some cases
26354 it may be convenient to define a subtype or derived type of Character that
26355 covers only the restricted range.
26356 @cindex Latin-1
26357 @end table
26359 @node Other language compatibility issues
26360 @subsection Other language compatibility issues
26361 @table @asis
26362 @item @option{-gnat83 switch}
26363 All implementations of GNAT provide a switch that causes GNAT to operate
26364 in Ada 83 mode.  In this mode, some but not all compatibility problems
26365 of the type described above are handled automatically.  For example, the
26366 new Ada 95 reserved words are treated simply as identifiers as in Ada 83.
26367 However,
26368 in practice, it is usually advisable to make the necessary modifications
26369 to the program to remove the need for using this switch.
26370 See @ref{Compiling Ada 83 Programs}.
26372 @item Support for removed Ada 83 pragmas and attributes
26373 A number of pragmas and attributes from Ada 83 have been removed from Ada 95,
26374 generally because they have been replaced by other mechanisms.  Ada 95
26375 compilers are allowed, but not required, to implement these missing
26376 elements.  In contrast with some other Ada 95 compilers, GNAT implements all
26377 such pragmas and attributes, eliminating this compatibility concern.  These
26378 include @code{pragma Interface} and the floating point type attributes
26379 (@code{Emax}, @code{Mantissa}, etc.), among other items.
26380 @end table
26382 @node Implementation-dependent characteristics
26383 @section Implementation-dependent characteristics
26384 @noindent
26385 Although the Ada language defines the semantics of each construct as
26386 precisely as practical, in some situations (for example for reasons of
26387 efficiency, or where the effect is heavily dependent on the host or target
26388 platform) the implementation is allowed some freedom.  In porting Ada 83
26389 code to GNAT, you need to be aware of whether / how the existing code
26390 exercised such implementation dependencies.  Such characteristics fall into
26391 several categories, and GNAT offers specific support in assisting the
26392 transition from certain Ada 83 compilers.
26394 @menu
26395 * Implementation-defined pragmas::
26396 * Implementation-defined attributes::
26397 * Libraries::
26398 * Elaboration order::
26399 * Target-specific aspects::
26400 @end menu
26402 @node Implementation-defined pragmas
26403 @subsection Implementation-defined pragmas
26405 @noindent
26406 Ada compilers are allowed to supplement the language-defined pragmas, and
26407 these are a potential source of non-portability.  All GNAT-defined pragmas
26408 are described in the GNAT Reference Manual, and these include several that
26409 are specifically intended to correspond to other vendors' Ada 83 pragmas.
26410 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
26412 compatibility with DEC Ada 83, GNAT supplies the pragmas
26413 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
26414 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
26415 and @code{Volatile}.
26416 Other relevant pragmas include @code{External} and @code{Link_With}.
26417 Some vendor-specific
26418 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
26419 recognized, thus
26420 avoiding compiler rejection of units that contain such pragmas; they are not
26421 relevant in a GNAT context and hence are not otherwise implemented.
26423 @node Implementation-defined attributes
26424 @subsection Implementation-defined attributes
26426 Analogous to pragmas, the set of attributes may be extended by an
26427 implementation.  All GNAT-defined attributes are described in the
26428 @cite{GNAT Reference Manual}, and these include several that are specifically
26429 intended
26430 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
26431 the attribute @code{VADS_Size} may be useful.  For compatibility with DEC
26432 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
26433 @code{Type_Class}.
26435 @node Libraries
26436 @subsection Libraries
26437 @noindent
26438 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
26439 code uses vendor-specific libraries then there are several ways to manage
26440 this in Ada 95:
26441 @enumerate
26442 @item
26443 If the source code for the libraries (specifications and bodies) are
26444 available, then the libraries can be migrated in the same way as the
26445 application.
26446 @item
26447 If the source code for the specifications but not the bodies are
26448 available, then you can reimplement the bodies.
26449 @item
26450 Some new Ada 95 features obviate the need for library support.  For
26451 example most Ada 83 vendors supplied a package for unsigned integers.  The
26452 Ada 95 modular type feature is the preferred way to handle this need, so
26453 instead of migrating or reimplementing the unsigned integer package it may
26454 be preferable to retrofit the application using modular types.
26455 @end enumerate
26457 @node Elaboration order
26458 @subsection Elaboration order
26459 @noindent
26460 The implementation can choose any elaboration order consistent with the unit
26461 dependency relationship.  This freedom means that some orders can result in
26462 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
26463 to invoke a subprogram its body has been elaborated, or to instantiate a
26464 generic before the generic body has been elaborated.  By default GNAT
26465 attempts to choose a safe order (one that will not encounter access before
26466 elaboration problems) by implicitly inserting Elaborate_All pragmas where
26467 needed.  However, this can lead to the creation of elaboration circularities
26468 and a resulting rejection of the program by gnatbind.  This issue is
26469 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
26470 In brief, there are several
26471 ways to deal with this situation:
26473 @itemize @bullet
26474 @item
26475 Modify the program to eliminate the circularities, e.g. by moving
26476 elaboration-time code into explicitly-invoked procedures
26477 @item
26478 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
26479 @code{Elaborate} pragmas, and then inhibit the generation of implicit
26480 @code{Elaborate_All}
26481 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
26482 (by selectively suppressing elaboration checks via pragma
26483 @code{Suppress(Elaboration_Check)} when it is safe to do so).
26484 @end itemize
26486 @node Target-specific aspects
26487 @subsection Target-specific aspects
26488 @noindent
26489 Low-level applications need to deal with machine addresses, data
26490 representations, interfacing with assembler code, and similar issues.  If
26491 such an Ada 83 application is being ported to different target hardware (for
26492 example where the byte endianness has changed) then you will need to
26493 carefully examine the program logic; the porting effort will heavily depend
26494 on the robustness of the original design.  Moreover, Ada 95 is sometimes
26495 incompatible with typical Ada 83 compiler practices regarding implicit
26496 packing, the meaning of the Size attribute, and the size of access values.
26497 GNAT's approach to these issues is described in @ref{Representation Clauses}.
26499 @node Compatibility with Other Ada 95 Systems
26500 @section Compatibility with Other Ada 95 Systems
26502 @noindent
26503 Providing that programs avoid the use of implementation dependent and
26504 implementation defined features of Ada 95, as documented in the Ada 95
26505 reference manual, there should be a high degree of portability between
26506 GNAT and other Ada 95 systems.  The following are specific items which
26507 have proved troublesome in moving GNAT programs to other Ada 95
26508 compilers, but do not affect porting code to GNAT@.
26510 @table @asis
26511 @item Ada 83 Pragmas and Attributes
26512 Ada 95 compilers are allowed, but not required, to implement the missing
26513 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
26514 GNAT implements all such pragmas and attributes, eliminating this as
26515 a compatibility concern, but some other Ada 95 compilers reject these
26516 pragmas and attributes.
26518 @item Special-needs Annexes
26519 GNAT implements the full set of special needs annexes.  At the
26520 current time, it is the only Ada 95 compiler to do so.  This means that
26521 programs making use of these features may not be portable to other Ada
26522 95 compilation systems.
26524 @item Representation Clauses
26525 Some other Ada 95 compilers implement only the minimal set of
26526 representation clauses required by the Ada 95 reference manual.  GNAT goes
26527 far beyond this minimal set, as described in the next section.
26528 @end table
26530 @node Representation Clauses
26531 @section Representation Clauses
26533 @noindent
26534 The Ada 83 reference manual was quite vague in describing both the minimal
26535 required implementation of representation clauses, and also their precise
26536 effects.  The Ada 95 reference manual is much more explicit, but the minimal
26537 set of capabilities required in Ada 95 is quite limited.
26539 GNAT implements the full required set of capabilities described in the
26540 Ada 95 reference manual, but also goes much beyond this, and in particular
26541 an effort has been made to be compatible with existing Ada 83 usage to the
26542 greatest extent possible.
26544 A few cases exist in which Ada 83 compiler behavior is incompatible with
26545 requirements in the Ada 95 reference manual.  These are instances of
26546 intentional or accidental dependence on specific implementation dependent
26547 characteristics of these Ada 83 compilers.  The following is a list of
26548 the cases most likely to arise in existing legacy Ada 83 code.
26550 @table @asis
26551 @item Implicit Packing
26552 Some Ada 83 compilers allowed a Size specification to cause implicit
26553 packing of an array or record.  This could cause expensive implicit
26554 conversions for change of representation in the presence of derived
26555 types, and the Ada design intends to avoid this possibility.
26556 Subsequent AI's were issued to make it clear that such implicit
26557 change of representation in response to a Size clause is inadvisable,
26558 and this recommendation is represented explicitly in the Ada 95 RM
26559 as implementation advice that is followed by GNAT@.
26560 The problem will show up as an error
26561 message rejecting the size clause.  The fix is simply to provide
26562 the explicit pragma @code{Pack}, or for more fine tuned control, provide
26563 a Component_Size clause.
26565 @item Meaning of Size Attribute
26566 The Size attribute in Ada 95 for discrete types is defined as being the
26567 minimal number of bits required to hold values of the type.  For example,
26568 on a 32-bit machine, the size of Natural will typically be 31 and not
26569 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
26570 some 32 in this situation.  This problem will usually show up as a compile
26571 time error, but not always.  It is a good idea to check all uses of the
26572 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
26573 Object_Size can provide a useful way of duplicating the behavior of
26574 some Ada 83 compiler systems.
26576 @item Size of Access Types
26577 A common assumption in Ada 83 code is that an access type is in fact a pointer,
26578 and that therefore it will be the same size as a System.Address value.  This
26579 assumption is true for GNAT in most cases with one exception.  For the case of
26580 a pointer to an unconstrained array type (where the bounds may vary from one
26581 value of the access type to another), the default is to use a ``fat pointer'',
26582 which is represented as two separate pointers, one to the bounds, and one to
26583 the array.  This representation has a number of advantages, including improved
26584 efficiency.  However, it may cause some difficulties in porting existing Ada 83
26585 code which makes the assumption that, for example, pointers fit in 32 bits on
26586 a machine with 32-bit addressing.
26588 To get around this problem, GNAT also permits the use of ``thin pointers'' for
26589 access types in this case (where the designated type is an unconstrained array
26590 type).  These thin pointers are indeed the same size as a System.Address value.
26591 To specify a thin pointer, use a size clause for the type, for example:
26593 @smallexample @c ada
26594 type X is access all String;
26595 for X'Size use Standard'Address_Size;
26596 @end smallexample
26598 @noindent
26599 which will cause the type X to be represented using a single pointer.
26600 When using this representation, the bounds are right behind the array.
26601 This representation is slightly less efficient, and does not allow quite
26602 such flexibility in the use of foreign pointers or in using the
26603 Unrestricted_Access attribute to create pointers to non-aliased objects.
26604 But for any standard portable use of the access type it will work in
26605 a functionally correct manner and allow porting of existing code.
26606 Note that another way of forcing a thin pointer representation
26607 is to use a component size clause for the element size in an array,
26608 or a record representation clause for an access field in a record.
26609 @end table
26611 @node Compatibility with DEC Ada 83
26612 @section Compatibility with DEC Ada 83
26614 @noindent
26615 The VMS version of GNAT fully implements all the pragmas and attributes
26616 provided by DEC Ada 83, as well as providing the standard DEC Ada 83
26617 libraries, including Starlet.  In addition, data layouts and parameter
26618 passing conventions are highly compatible.  This means that porting
26619 existing DEC Ada 83 code to GNAT in VMS systems should be easier than
26620 most other porting efforts.  The following are some of the most
26621 significant differences between GNAT and DEC Ada 83.
26623 @table @asis
26624 @item Default floating-point representation
26625 In GNAT, the default floating-point format is IEEE, whereas in DEC Ada 83,
26626 it is VMS format.  GNAT does implement the necessary pragmas
26627 (Long_Float, Float_Representation) for changing this default.
26629 @item System
26630 The package System in GNAT exactly corresponds to the definition in the
26631 Ada 95 reference manual, which means that it excludes many of the
26632 DEC Ada 83 extensions.  However, a separate package Aux_DEC is provided
26633 that contains the additional definitions, and a special pragma,
26634 Extend_System allows this package to be treated transparently as an
26635 extension of package System.
26637 @item To_Address
26638 The definitions provided by Aux_DEC are exactly compatible with those
26639 in the DEC Ada 83 version of System, with one exception.
26640 DEC Ada provides the following declarations:
26642 @smallexample @c ada
26643 TO_ADDRESS (INTEGER)
26644 TO_ADDRESS (UNSIGNED_LONGWORD)
26645 TO_ADDRESS (universal_integer)
26646 @end smallexample
26648 @noindent
26649 The version of TO_ADDRESS taking a universal integer argument is in fact
26650 an extension to Ada 83 not strictly compatible with the reference manual.
26651 In GNAT, we are constrained to be exactly compatible with the standard,
26652 and this means we cannot provide this capability.  In DEC Ada 83, the
26653 point of this definition is to deal with a call like:
26655 @smallexample @c ada
26656 TO_ADDRESS (16#12777#);
26657 @end smallexample
26659 @noindent
26660 Normally, according to the Ada 83 standard, one would expect this to be
26661 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
26662 of TO_ADDRESS@.  However, in DEC Ada 83, there is no ambiguity, since the
26663 definition using universal_integer takes precedence.
26665 In GNAT, since the version with universal_integer cannot be supplied, it is
26666 not possible to be 100% compatible.  Since there are many programs using
26667 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
26668 to change the name of the function in the UNSIGNED_LONGWORD case, so the
26669 declarations provided in the GNAT version of AUX_Dec are:
26671 @smallexample @c ada
26672 function To_Address (X : Integer) return Address;
26673 pragma Pure_Function (To_Address);
26675 function To_Address_Long (X : Unsigned_Longword)
26676  return Address;
26677 pragma Pure_Function (To_Address_Long);
26678 @end smallexample
26680 @noindent
26681 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
26682 change the name to TO_ADDRESS_LONG@.
26684 @item Task_Id values
26685 The Task_Id values assigned will be different in the two systems, and GNAT
26686 does not provide a specified value for the Task_Id of the environment task,
26687 which in GNAT is treated like any other declared task.
26688 @end table
26690 For full details on these and other less significant compatibility issues,
26691 see appendix E of the Digital publication entitled @cite{DEC Ada, Technical
26692 Overview and Comparison on DIGITAL Platforms}.
26694 For GNAT running on other than VMS systems, all the DEC Ada 83 pragmas and
26695 attributes are recognized, although only a subset of them can sensibly
26696 be implemented.  The description of pragmas in this reference manual
26697 indicates whether or not they are applicable to non-VMS systems.
26700 @ifset vms
26701 @node Transitioning from Alpha to Integrity OpenVMS
26702 @section Transitioning from Alpha to Integrity OpenVMS
26704 @menu
26705 * Introduction to transitioning::
26706 * Migration of 32 bit code::
26707 * Taking advantage of 64 bit addressing::
26708 * Technical details::
26709 @end menu
26711 @node Introduction to transitioning
26712 @subsection Introduction to transitioning
26714 @noindent
26715 This guide is meant to assist users of GNAT Pro
26716 for Alpha OpenVMS who are planning to transition to the IA64 architecture.
26717 GNAT Pro for Open VMS Integrity has been designed to meet
26718 three main goals:
26720 @enumerate
26721 @item
26722 Providing a full conforming implementation of the Ada 95 language
26724 @item
26725 Allowing maximum backward compatibility, thus easing migration of existing
26726 Ada source code
26728 @item
26729 Supplying a path for exploiting the full IA64 address range
26730 @end enumerate
26732 @noindent
26733 Ada's strong typing semantics has made it
26734 impractical to have different 32-bit and 64-bit modes. As soon as
26735 one object could possibly be outside the 32-bit address space, this
26736 would make it necessary for the @code{System.Address} type to be 64 bits.
26737 In particular, this would cause inconsistencies if 32-bit code is
26738 called from 64-bit code that raises an exception.
26740 This issue has been resolved by always using 64-bit addressing
26741 at the system level, but allowing for automatic conversions between
26742 32-bit and 64-bit addresses where required. Thus users who
26743 do not currently require 64-bit addressing capabilities, can
26744 recompile their code with only minimal changes (and indeed
26745 if the code is written in portable Ada, with no assumptions about
26746 the size of the @code{Address} type, then no changes at all are necessary).
26747 At the same time,
26748 this approach provides a simple, gradual upgrade path to future
26749 use of larger memories than available for 32-bit systems.
26750 Also, newly written applications or libraries will by default
26751 be fully compatible with future systems exploiting 64-bit
26752 addressing capabilities present in IA64.
26754 @ref{Migration of 32 bit code}, will focus on porting applications
26755 that do not require more than 2 GB of
26756 addressable memory. This code will be referred to as
26757 @emph{32-bit code}.
26758 For applications intending to exploit the full ia64 address space,
26759 @ref{Taking advantage of 64 bit addressing},
26760 will consider further changes that may be required.
26761 Such code is called @emph{64-bit code} in the
26762 remainder of this guide.
26765 @node Migration of 32 bit code
26766 @subsection Migration of 32-bit code
26768 @menu
26769 * Address types::
26770 * Access types::
26771 * Unchecked conversions::
26772 * Predefined constants::
26773 * Single source compatibility::
26774 * Experience with source compatibility::
26775 @end menu
26777 @node Address types
26778 @subsubsection Address types
26780 @noindent
26781 To solve the problem of mixing 64-bit and 32-bit addressing,
26782 while maintaining maximum backward compatibility, the following
26783 approach has been taken:
26785 @itemize @bullet
26786 @item
26787 @code{System.Address} always has a size of 64 bits
26789 @item
26790 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
26791 @end itemize
26794 @noindent
26795 Since @code{System.Short_Address} is a subtype of @code{System.Address},
26796 a @code{Short_Address}
26797 may be used where an @code{Address} is required, and vice versa, without
26798 needing explicit type conversions.
26799 By virtue of the Open VMS Integrity parameter passing conventions,
26800 even imported
26801 and exported subprograms that have 32-bit address parameters are
26802 compatible with those that have 64-bit address parameters.
26803 (See @ref{Making code 64 bit clean} for details.)
26805 The areas that may need attention are those where record types have
26806 been defined that contain components of the type @code{System.Address}, and
26807 where objects of this type are passed to code expecting a record layout with
26808 32-bit addresses.
26810 Different compilers on different platforms cannot be
26811 expected to represent the same type in the same way,
26812 since alignment constraints
26813 and other system-dependent properties affect the compiler's decision.
26814 For that reason, Ada code
26815 generally uses representation clauses to specify the expected
26816 layout where required.
26818 If such a representation clause uses 32 bits for a component having
26819 the type @code{System.Address}, GNAT Pro for OpenVMS Integrity will detect
26820 that error and produce a specific diagnostic message.
26821 The developer should then determine whether the representation
26822 should be 64 bits or not and make either of two changes:
26823 change the size to 64 bits and leave the type as @code{System.Address}, or
26824 leave the size as 32 bits and change the type to @code{System.Short_Address}.
26825 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
26826 required in any code setting or accessing the field; the compiler will
26827 automatically perform any needed conversions between address
26828 formats.
26830 @node Access types
26831 @subsubsection Access types
26833 @noindent
26834 By default, objects designated by access values are always
26835 allocated in the 32-bit
26836 address space. Thus legacy code will never contain
26837 any objects that are not addressable with 32-bit addresses, and
26838 the compiler will never raise exceptions as result of mixing
26839 32-bit and 64-bit addresses.
26841 However, the access values themselves are represented in 64 bits, for optimum
26842 performance and future compatibility with 64-bit code. As was
26843 the case with @code{System.Address}, the compiler will give an error message
26844 if an object or record component has a representation clause that
26845 requires the access value to fit in 32 bits. In such a situation,
26846 an explicit size clause for the access type, specifying 32 bits,
26847 will have the desired effect.
26849 General access types (declared with @code{access all}) can never be
26850 32 bits, as values of such types must be able to refer to any object
26851 of the  designated type,
26852 including objects residing outside the 32-bit address range.
26853 Existing Ada 83 code will not contain such type definitions,
26854 however, since general access types were introduced in Ada 95.
26856 @node Unchecked conversions
26857 @subsubsection Unchecked conversions
26859 @noindent
26860 In the case of an @code{Unchecked_Conversion} where the source type is a
26861 64-bit access type or the type @code{System.Address}, and the target
26862 type is a 32-bit type, the compiler will generate a warning.
26863 Even though the generated code will still perform the required
26864 conversions, it is highly recommended in these cases to use
26865 respectively a 32-bit access type or @code{System.Short_Address}
26866 as the source type.
26868 @node Predefined constants
26869 @subsubsection Predefined constants
26871 @noindent
26872 The following predefined constants have changed:
26874 @multitable {@code{System.Address_Size}} {2**32} {2**64}
26875 @item   @b{Constant}               @tab @b{Old} @tab @b{New}
26876 @item   @code{System.Word_Size}    @tab 32      @tab 64
26877 @item   @code{System.Memory_Size}  @tab 2**32   @tab 2**64
26878 @item   @code{System.Address_Size} @tab 32      @tab 64
26879 @end multitable
26881 @noindent
26882 If you need to refer to the specific
26883 memory size of a 32-bit implementation, instead of the
26884 actual memory size, use @code{System.Short_Memory_Size}
26885 rather than @code{System.Memory_Size}.
26886 Similarly, references to @code{System.Address_Size} may need
26887 to be replaced by @code{System.Short_Address'Size}.
26888 The program @command{gnatfind} may be useful for locating
26889 references to the above constants, so that you can verify that they
26890 are still correct.
26892 @node Single source compatibility
26893 @subsubsection Single source compatibility
26895 @noindent
26896 In order to allow the same source code to be compiled on
26897 both Alpha and IA64 platforms, GNAT Pro for Alpha/OpenVMS
26898 defines @code{System.Short_Address} and System.Short_Memory_Size
26899 as aliases of respectively @code{System.Address} and
26900 @code{System.Memory_Size}.
26901 (These aliases also leave the door open for a possible
26902 future ``upgrade'' of OpenVMS Alpha to a 64-bit address space.)
26904 @node Experience with source compatibility
26905 @subsubsection Experience with source compatibility
26907 @noindent
26908 The Security Server and STARLET provide an interesting ``test case''
26909 for source compatibility issues, since it is in such system code
26910 where assumptions about @code{Address} size might be expected to occur.
26911 Indeed, there were a small number of occasions in the Security Server
26912 file @file{jibdef.ads}
26913 where a representation clause for a record type specified
26914 32 bits for a component of type @code{Address}.
26915 All of these errors were detected by the compiler.
26916 The repair was obvious and immediate; to simply replace @code{Address} by
26917 @code{Short_Address}.
26919 In the case of STARLET, there were several record types that should
26920 have had representation clauses but did not.  In these record types
26921 there was an implicit assumption that an @code{Address} value occupied
26922 32 bits.
26923 These compiled without error, but their usage resulted in run-time error
26924 returns from STARLET system calls.
26925 To assist in the compile-time detection of such situations, we
26926 plan to include a switch to generate a warning message when a
26927 record component is of type @code{Address}.
26930 @c ****************************************
26931 @node Taking advantage of 64 bit addressing
26932 @subsection Taking advantage of 64-bit addressing
26934 @menu
26935 * Making code 64 bit clean::
26936 * Allocating memory from the 64 bit storage pool::
26937 * Restrictions on use of 64 bit objects::
26938 * Using 64 bit storage pools by default::
26939 * General access types::
26940 * STARLET and other predefined libraries::
26941 @end menu
26943 @node Making code 64 bit clean
26944 @subsubsection Making code 64-bit clean
26946 @noindent
26947 In order to prevent problems that may occur when (parts of) a
26948 system start using memory outside the 32-bit address range,
26949 we recommend some additional guidelines:
26951 @itemize @bullet
26952 @item
26953 For imported subprograms that take parameters of the
26954 type @code{System.Address}, ensure that these subprograms can
26955 indeed handle 64-bit addresses. If not, or when in doubt,
26956 change the subprogram declaration to specify
26957 @code{System.Short_Address} instead.
26959 @item
26960 Resolve all warnings related to size mismatches in
26961 unchecked conversions. Failing to do so causes
26962 erroneous execution if the source object is outside
26963 the 32-bit address space.
26965 @item
26966 (optional) Explicitly use the 32-bit storage pool
26967 for access types used in a 32-bit context, or use
26968 generic access types where possible
26969 (@pxref{Restrictions on use of 64 bit objects}).
26970 @end itemize
26972 @noindent
26973 If these rules are followed, the compiler will automatically insert
26974 any necessary checks to ensure that no addresses or access values
26975 passed to 32-bit code ever refer to objects outside the 32-bit
26976 address range.
26977 Any attempt to do this will raise @code{Constraint_Error}.
26979 @node Allocating memory from the 64 bit storage pool
26980 @subsubsection Allocating memory from the 64-bit storage pool
26982 @noindent
26983 For any access type @code{T} that potentially requires memory allocations
26984 beyond the 32-bit address space,
26985 use the following representation clause:
26987 @smallexample @c ada
26988    for T'Storage_Pool use System.Pool_64;
26989 @end smallexample
26992 @node Restrictions on use of 64 bit objects
26993 @subsubsection Restrictions on use of 64-bit objects
26995 @noindent
26996 Taking the address of an object allocated from a 64-bit storage pool,
26997 and then passing this address to a subprogram expecting
26998 @code{System.Short_Address},
26999 or assigning it to a variable of type @code{Short_Address}, will cause
27000 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
27001 (@pxref{Making code 64 bit clean}), or checks are suppressed,
27002 no exception is raised and execution
27003 will become erroneous.
27005 @node Using 64 bit storage pools by default
27006 @subsubsection Using 64-bit storage pools by default
27008 @noindent
27009 In some cases it may be desirable to have the compiler allocate
27010 from 64-bit storage pools by default. This may be the case for
27011 libraries that are 64-bit clean, but may be used in both 32-bit
27012 and 64-bit contexts. For these cases the following configuration
27013 pragma may be specified:
27015 @smallexample @c ada
27016   pragma Pool_64_Default;
27017 @end smallexample
27019 @noindent
27020 Any code compiled in the context of this pragma will by default
27021 use the @code{System.Pool_64} storage pool. This default may be overridden
27022 for a specific access type @code{T} by the representation clause:
27024 @smallexample @c ada
27025    for T'Storage_Pool use System.Pool_32;
27026 @end smallexample
27028 @noindent
27029 Any object whose address may be passed to a subprogram with a
27030 @code{Short_Address} argument, or assigned to a variable of type
27031 @code{Short_Address}, needs to be allocated from this pool.
27033 @node General access types
27034 @subsubsection General access types
27036 @noindent
27037 Objects designated by access values from a
27038 general access type (declared with @code{access all}) are never allocated
27039 from a 64-bit storage pool. Code that uses general access types will
27040 accept objects allocated in either 32-bit or 64-bit address spaces,
27041 but never allocate objects outside the 32-bit address space.
27042 Using general access types ensures maximum compatibility with both
27043 32-bit and 64-bit code.
27046 @node STARLET and other predefined libraries
27047 @subsubsection STARLET and other predefined libraries
27049 @noindent
27050 All code that comes as part of GNAT is 64-bit clean, but the
27051 restrictions given in @ref{Restrictions on use of 64 bit objects},
27052 still apply. Look at the package
27053 specifications to see in which contexts objects allocated
27054 in 64-bit address space are acceptable.
27056 @node Technical details
27057 @subsection Technical details
27059 @noindent
27060 GNAT Pro for Open VMS Integrity takes advantage of the freedom given in the Ada
27061 standard with respect to the type of @code{System.Address}. Previous versions
27062 of GNAT Pro have defined this type as private and implemented it as
27063 a modular type.
27065 In order to allow defining @code{System.Short_Address} as a proper subtype,
27066 and to match the implicit sign extension in parameter passing,
27067 in GNAT Pro for Open VMS Integrity, @code{System.Address} is defined as a
27068 visible (i.e., non-private) integer type.
27069 Standard operations on the type, such as the binary operators ``+'', ``-'',
27070 etc., that take @code{Address} operands and return an @code{Address} result,
27071 have been hidden by declaring these
27072 @code{abstract}, an Ada 95 feature that helps avoid the potential ambiguities
27073 that would otherwise result from overloading.
27074 (Note that, although @code{Address} is a visible integer type,
27075 good programming practice dictates against exploiting the type's
27076 integer properties such as literals, since this will compromise
27077 code portability.)
27079 Defining @code{Address} as a visible integer type helps achieve
27080 maximum compatibility for existing Ada code,
27081 without sacrificing the capabilities of the IA64 architecture.
27082 @end ifset
27085 @c ************************************************
27086 @ifset unw
27087 @node Microsoft Windows Topics
27088 @appendix Microsoft Windows Topics
27089 @cindex Windows NT
27090 @cindex Windows 95
27091 @cindex Windows 98
27093 @noindent
27094 This chapter describes topics that are specific to the Microsoft Windows
27095 platforms (NT, 2000, and XP Professional).
27097 @menu
27098 * Using GNAT on Windows::
27099 * Using a network installation of GNAT::
27100 * CONSOLE and WINDOWS subsystems::
27101 * Temporary Files::
27102 * Mixed-Language Programming on Windows::
27103 * Windows Calling Conventions::
27104 * Introduction to Dynamic Link Libraries (DLLs)::
27105 * Using DLLs with GNAT::
27106 * Building DLLs with GNAT::
27107 * Building DLLs with GNAT Project files::
27108 * Building DLLs with gnatdll::
27109 * GNAT and Windows Resources::
27110 * Debugging a DLL::
27111 * GNAT and COM/DCOM Objects::
27112 @end menu
27114 @node Using GNAT on Windows
27115 @section Using GNAT on Windows
27117 @noindent
27118 One of the strengths of the GNAT technology is that its tool set
27119 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
27120 @code{gdb} debugger, etc.) is used in the same way regardless of the
27121 platform.
27123 On Windows this tool set is complemented by a number of Microsoft-specific
27124 tools that have been provided to facilitate interoperability with Windows
27125 when this is required. With these tools:
27127 @itemize @bullet
27129 @item
27130 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
27131 subsystems.
27133 @item
27134 You can use any Dynamically Linked Library (DLL) in your Ada code (both
27135 relocatable and non-relocatable DLLs are supported).
27137 @item
27138 You can build Ada DLLs for use in other applications. These applications
27139 can be written in a language other than Ada (e.g., C, C++, etc). Again both
27140 relocatable and non-relocatable Ada DLLs are supported.
27142 @item
27143 You can include Windows resources in your Ada application.
27145 @item
27146 You can use or create COM/DCOM objects.
27147 @end itemize
27149 @noindent
27150 Immediately below are listed all known general GNAT-for-Windows restrictions.
27151 Other restrictions about specific features like Windows Resources and DLLs
27152 are listed in separate sections below.
27154 @itemize @bullet
27156 @item
27157 It is not possible to use @code{GetLastError} and @code{SetLastError}
27158 when tasking, protected records, or exceptions are used. In these
27159 cases, in order to implement Ada semantics, the GNAT run-time system
27160 calls certain Win32 routines that set the last error variable to 0 upon
27161 success. It should be possible to use @code{GetLastError} and
27162 @code{SetLastError} when tasking, protected record, and exception
27163 features are not used, but it is not guaranteed to work.
27165 @item
27166 It is not possible to link against Microsoft libraries except for
27167 import libraries. The library must be built to be compatible with
27168 @file{MSVCRT.LIB} (/MD Microsoft compiler option), @file{LIBC.LIB} and
27169 @file{LIBCMT.LIB} (/ML or /MT Microsoft compiler options) are known to
27170 not be compatible with the GNAT runtime. Even if the library is
27171 compatible with @file{MSVCRT.LIB} it is not guaranteed to work.
27173 @item
27174 When the compilation environment is located on FAT32 drives, users may
27175 experience recompilations of the source files that have not changed if
27176 Daylight Saving Time (DST) state has changed since the last time files
27177 were compiled. NTFS drives do not have this problem.
27179 @item
27180 No components of the GNAT toolset use any entries in the Windows
27181 registry. The only entries that can be created are file associations and
27182 PATH settings, provided the user has chosen to create them at installation
27183 time, as well as some minimal book-keeping information needed to correctly
27184 uninstall or integrate different GNAT products.
27185 @end itemize
27187 @node Using a network installation of GNAT
27188 @section Using a network installation of GNAT
27190 @noindent
27191 Make sure the system on which GNAT is installed is accessible from the
27192 current machine, i.e. the install location is shared over the network.
27193 Shared resources are accessed on Windows by means of UNC paths, which
27194 have the format @code{\\server\sharename\path}
27196 In order to use such a network installation, simply add the UNC path of the
27197 @file{bin} directory of your GNAT installation in front of your PATH. For
27198 example, if GNAT is installed in @file{\GNAT} directory of a share location
27199 called @file{c-drive} on a machine @file{LOKI}, the following command will
27200 make it available:
27202 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
27204 Be aware that every compilation using the network installation results in the
27205 transfer of large amounts of data across the network and will likely cause
27206 serious performance penalty.
27208 @node CONSOLE and WINDOWS subsystems
27209 @section CONSOLE and WINDOWS subsystems
27210 @cindex CONSOLE Subsystem
27211 @cindex WINDOWS Subsystem
27212 @cindex -mwindows
27214 @noindent
27215 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
27216 (which is the default subsystem) will always create a console when
27217 launching the application. This is not something desirable when the
27218 application has a Windows GUI. To get rid of this console the
27219 application must be using the @code{WINDOWS} subsystem. To do so
27220 the @option{-mwindows} linker option must be specified.
27222 @smallexample
27223 $ gnatmake winprog -largs -mwindows
27224 @end smallexample
27226 @node Temporary Files
27227 @section Temporary Files
27228 @cindex Temporary files
27230 @noindent
27231 It is possible to control where temporary files gets created by setting
27232 the TMP environment variable. The file will be created:
27234 @itemize
27235 @item Under the directory pointed to by the TMP environment variable if
27236 this directory exists.
27238 @item Under c:\temp, if the TMP environment variable is not set (or not
27239 pointing to a directory) and if this directory exists.
27241 @item Under the current working directory otherwise.
27242 @end itemize
27244 @noindent
27245 This allows you to determine exactly where the temporary
27246 file will be created. This is particularly useful in networked
27247 environments where you may not have write access to some
27248 directories.
27250 @node Mixed-Language Programming on Windows
27251 @section Mixed-Language Programming on Windows
27253 @noindent
27254 Developing pure Ada applications on Windows is no different than on
27255 other GNAT-supported platforms. However, when developing or porting an
27256 application that contains a mix of Ada and C/C++, the choice of your
27257 Windows C/C++ development environment conditions your overall
27258 interoperability strategy.
27260 If you use @command{gcc} to compile the non-Ada part of your application,
27261 there are no Windows-specific restrictions that affect the overall
27262 interoperability with your Ada code. If you plan to use
27263 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
27264 the following limitations:
27266 @itemize @bullet
27267 @item
27268 You cannot link your Ada code with an object or library generated with
27269 Microsoft tools if these use the @code{.tls} section (Thread Local
27270 Storage section) since the GNAT linker does not yet support this section.
27272 @item
27273 You cannot link your Ada code with an object or library generated with
27274 Microsoft tools if these use I/O routines other than those provided in
27275 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
27276 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
27277 libraries can cause a conflict with @code{msvcrt.dll} services. For
27278 instance Visual C++ I/O stream routines conflict with those in
27279 @code{msvcrt.dll}.
27280 @end itemize
27282 @noindent
27283 If you do want to use the Microsoft tools for your non-Ada code and hit one
27284 of the above limitations, you have two choices:
27286 @enumerate
27287 @item
27288 Encapsulate your non Ada code in a DLL to be linked with your Ada
27289 application. In this case, use the Microsoft or whatever environment to
27290 build the DLL and use GNAT to build your executable
27291 (@pxref{Using DLLs with GNAT}).
27293 @item
27294 Or you can encapsulate your Ada code in a DLL to be linked with the
27295 other part of your application. In this case, use GNAT to build the DLL
27296 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
27297 environment to build your executable.
27298 @end enumerate
27300 @node Windows Calling Conventions
27301 @section Windows Calling Conventions
27302 @findex Stdcall
27303 @findex APIENTRY
27305 @menu
27306 * C Calling Convention::
27307 * Stdcall Calling Convention::
27308 * DLL Calling Convention::
27309 @end menu
27311 @noindent
27312 When a subprogram @code{F} (caller) calls a subprogram @code{G}
27313 (callee), there are several ways to push @code{G}'s parameters on the
27314 stack and there are several possible scenarios to clean up the stack
27315 upon @code{G}'s return. A calling convention is an agreed upon software
27316 protocol whereby the responsibilities between the caller (@code{F}) and
27317 the callee (@code{G}) are clearly defined. Several calling conventions
27318 are available for Windows:
27320 @itemize @bullet
27321 @item
27322 @code{C} (Microsoft defined)
27324 @item
27325 @code{Stdcall} (Microsoft defined)
27327 @item
27328 @code{DLL} (GNAT specific)
27329 @end itemize
27331 @node C Calling Convention
27332 @subsection @code{C} Calling Convention
27334 @noindent
27335 This is the default calling convention used when interfacing to C/C++
27336 routines compiled with either @command{gcc} or Microsoft Visual C++.
27338 In the @code{C} calling convention subprogram parameters are pushed on the
27339 stack by the caller from right to left. The caller itself is in charge of
27340 cleaning up the stack after the call. In addition, the name of a routine
27341 with @code{C} calling convention is mangled by adding a leading underscore.
27343 The name to use on the Ada side when importing (or exporting) a routine
27344 with @code{C} calling convention is the name of the routine. For
27345 instance the C function:
27347 @smallexample
27348 int get_val (long);
27349 @end smallexample
27351 @noindent
27352 should be imported from Ada as follows:
27354 @smallexample @c ada
27355 @group
27356 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27357 pragma Import (C, Get_Val, External_Name => "get_val");
27358 @end group
27359 @end smallexample
27361 @noindent
27362 Note that in this particular case the @code{External_Name} parameter could
27363 have been omitted since, when missing, this parameter is taken to be the
27364 name of the Ada entity in lower case. When the @code{Link_Name} parameter
27365 is missing, as in the above example, this parameter is set to be the
27366 @code{External_Name} with a leading underscore.
27368 When importing a variable defined in C, you should always use the @code{C}
27369 calling convention unless the object containing the variable is part of a
27370 DLL (in which case you should use the @code{DLL} calling convention,
27371 @pxref{DLL Calling Convention}).
27373 @node Stdcall Calling Convention
27374 @subsection @code{Stdcall} Calling Convention
27376 @noindent
27377 This convention, which was the calling convention used for Pascal
27378 programs, is used by Microsoft for all the routines in the Win32 API for
27379 efficiency reasons. It must be used to import any routine for which this
27380 convention was specified.
27382 In the @code{Stdcall} calling convention subprogram parameters are pushed
27383 on the stack by the caller from right to left. The callee (and not the
27384 caller) is in charge of cleaning the stack on routine exit. In addition,
27385 the name of a routine with @code{Stdcall} calling convention is mangled by
27386 adding a leading underscore (as for the @code{C} calling convention) and a
27387 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
27388 bytes) of the parameters passed to the routine.
27390 The name to use on the Ada side when importing a C routine with a
27391 @code{Stdcall} calling convention is the name of the C routine. The leading
27392 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
27393 the compiler. For instance the Win32 function:
27395 @smallexample
27396 @b{APIENTRY} int get_val (long);
27397 @end smallexample
27399 @noindent
27400 should be imported from Ada as follows:
27402 @smallexample @c ada
27403 @group
27404 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27405 pragma Import (Stdcall, Get_Val);
27406 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
27407 @end group
27408 @end smallexample
27410 @noindent
27411 As for the @code{C} calling convention, when the @code{External_Name}
27412 parameter is missing, it is taken to be the name of the Ada entity in lower
27413 case. If instead of writing the above import pragma you write:
27415 @smallexample @c ada
27416 @group
27417 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27418 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
27419 @end group
27420 @end smallexample
27422 @noindent
27423 then the imported routine is @code{_retrieve_val@@4}. However, if instead
27424 of specifying the @code{External_Name} parameter you specify the
27425 @code{Link_Name} as in the following example:
27427 @smallexample @c ada
27428 @group
27429 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
27430 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
27431 @end group
27432 @end smallexample
27434 @noindent
27435 then the imported routine is @code{retrieve_val@@4}, that is, there is no
27436 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
27437 added at the end of the @code{Link_Name} by the compiler.
27439 @noindent
27440 Note, that in some special cases a DLL's entry point name lacks a trailing
27441 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
27442 The @code{gnatdll} tool, which creates the import library for the DLL, is able
27443 to handle those cases (@pxref{Using gnatdll} for the description of
27444 the switches).
27446 @node DLL Calling Convention
27447 @subsection @code{DLL} Calling Convention
27449 @noindent
27450 This convention, which is GNAT-specific, must be used when you want to
27451 import in Ada a variables defined in a DLL. For functions and procedures
27452 this convention is equivalent to the @code{Stdcall} convention. As an
27453 example, if a DLL contains a variable defined as:
27455 @smallexample
27456 int my_var;
27457 @end smallexample
27459 @noindent
27460 then, to access this variable from Ada you should write:
27462 @smallexample @c ada
27463 @group
27464 My_Var : Interfaces.C.int;
27465 pragma Import (DLL, My_Var);
27466 @end group
27467 @end smallexample
27469 The remarks concerning the @code{External_Name} and @code{Link_Name}
27470 parameters given in the previous sections equally apply to the @code{DLL}
27471 calling convention.
27473 @node Introduction to Dynamic Link Libraries (DLLs)
27474 @section Introduction to Dynamic Link Libraries (DLLs)
27475 @findex DLL
27477 @noindent
27478 A Dynamically Linked Library (DLL) is a library that can be shared by
27479 several applications running under Windows. A DLL can contain any number of
27480 routines and variables.
27482 One advantage of DLLs is that you can change and enhance them without
27483 forcing all the applications that depend on them to be relinked or
27484 recompiled. However, you should be aware than all calls to DLL routines are
27485 slower since, as you will understand below, such calls are indirect.
27487 To illustrate the remainder of this section, suppose that an application
27488 wants to use the services of a DLL @file{API.dll}. To use the services
27489 provided by @file{API.dll} you must statically link against the DLL or
27490 an import library which contains a jump table with an entry for each
27491 routine and variable exported by the DLL. In the Microsoft world this
27492 import library is called @file{API.lib}. When using GNAT this import
27493 library is called either @file{libAPI.a} or @file{libapi.a} (names are
27494 case insensitive).
27496 After you have linked your application with the DLL or the import library
27497 and you run your application, here is what happens:
27499 @enumerate
27500 @item
27501 Your application is loaded into memory.
27503 @item
27504 The DLL @file{API.dll} is mapped into the address space of your
27505 application. This means that:
27507 @itemize @bullet
27508 @item
27509 The DLL will use the stack of the calling thread.
27511 @item
27512 The DLL will use the virtual address space of the calling process.
27514 @item
27515 The DLL will allocate memory from the virtual address space of the calling
27516 process.
27518 @item
27519 Handles (pointers) can be safely exchanged between routines in the DLL
27520 routines and routines in the application using the DLL.
27521 @end itemize
27523 @item
27524 The entries in the jump table (from the import library @file{libAPI.a}
27525 or @file{API.lib} or automatically created when linking against a DLL)
27526 which is part of your application are initialized with the addresses
27527 of the routines and variables in @file{API.dll}.
27529 @item
27530 If present in @file{API.dll}, routines @code{DllMain} or
27531 @code{DllMainCRTStartup} are invoked. These routines typically contain
27532 the initialization code needed for the well-being of the routines and
27533 variables exported by the DLL.
27534 @end enumerate
27536 @noindent
27537 There is an additional point which is worth mentioning. In the Windows
27538 world there are two kind of DLLs: relocatable and non-relocatable
27539 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
27540 in the target application address space. If the addresses of two
27541 non-relocatable DLLs overlap and these happen to be used by the same
27542 application, a conflict will occur and the application will run
27543 incorrectly. Hence, when possible, it is always preferable to use and
27544 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
27545 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
27546 User's Guide) removes the debugging symbols from the DLL but the DLL can
27547 still be relocated.
27549 As a side note, an interesting difference between Microsoft DLLs and
27550 Unix shared libraries, is the fact that on most Unix systems all public
27551 routines are exported by default in a Unix shared library, while under
27552 Windows it is possible (but not required) to list exported routines in
27553 a definition file (@pxref{The Definition File}).
27555 @node Using DLLs with GNAT
27556 @section Using DLLs with GNAT
27558 @menu
27559 * Creating an Ada Spec for the DLL Services::
27560 * Creating an Import Library::
27561 @end menu
27563 @noindent
27564 To use the services of a DLL, say @file{API.dll}, in your Ada application
27565 you must have:
27567 @enumerate
27568 @item
27569 The Ada spec for the routines and/or variables you want to access in
27570 @file{API.dll}. If not available this Ada spec must be built from the C/C++
27571 header files provided with the DLL.
27573 @item
27574 The import library (@file{libAPI.a} or @file{API.lib}). As previously
27575 mentioned an import library is a statically linked library containing the
27576 import table which will be filled at load time to point to the actual
27577 @file{API.dll} routines. Sometimes you don't have an import library for the
27578 DLL you want to use. The following sections will explain how to build
27579 one. Note that this is optional.
27581 @item
27582 The actual DLL, @file{API.dll}.
27583 @end enumerate
27585 @noindent
27586 Once you have all the above, to compile an Ada application that uses the
27587 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
27588 you simply issue the command
27590 @smallexample
27591 $ gnatmake my_ada_app -largs -lAPI
27592 @end smallexample
27594 @noindent
27595 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
27596 tells the GNAT linker to look first for a library named @file{API.lib}
27597 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
27598 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
27599 contains the following pragma
27601 @smallexample @c ada
27602 pragma Linker_Options ("-lAPI");
27603 @end smallexample
27605 @noindent
27606 you do not have to add @option{-largs -lAPI} at the end of the
27607 @command{gnatmake} command.
27609 If any one of the items above is missing you will have to create it
27610 yourself. The following sections explain how to do so using as an
27611 example a fictitious DLL called @file{API.dll}.
27613 @node Creating an Ada Spec for the DLL Services
27614 @subsection Creating an Ada Spec for the DLL Services
27616 @noindent
27617 A DLL typically comes with a C/C++ header file which provides the
27618 definitions of the routines and variables exported by the DLL. The Ada
27619 equivalent of this header file is a package spec that contains definitions
27620 for the imported entities. If the DLL you intend to use does not come with
27621 an Ada spec you have to generate one such spec yourself. For example if
27622 the header file of @file{API.dll} is a file @file{api.h} containing the
27623 following two definitions:
27625 @smallexample
27626 @group
27627 @cartouche
27628 int some_var;
27629 int get (char *);
27630 @end cartouche
27631 @end group
27632 @end smallexample
27634 @noindent
27635 then the equivalent Ada spec could be:
27637 @smallexample @c ada
27638 @group
27639 @cartouche
27640 with Interfaces.C.Strings;
27641 package API is
27642    use Interfaces;
27644    Some_Var : C.int;
27645    function Get (Str : C.Strings.Chars_Ptr) return C.int;
27647 private
27648    pragma Import (C, Get);
27649    pragma Import (DLL, Some_Var);
27650 end API;
27651 @end cartouche
27652 @end group
27653 @end smallexample
27655 @noindent
27656 Note that a variable is @strong{always imported with a DLL convention}. A
27657 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
27658 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
27659 (@pxref{Windows Calling Conventions}).
27661 @node Creating an Import Library
27662 @subsection Creating an Import Library
27663 @cindex Import library
27665 @menu
27666 * The Definition File::
27667 * GNAT-Style Import Library::
27668 * Microsoft-Style Import Library::
27669 @end menu
27671 @noindent
27672 If a Microsoft-style import library @file{API.lib} or a GNAT-style
27673 import library @file{libAPI.a} is available with @file{API.dll} you
27674 can skip this section. You can also skip this section if
27675 @file{API.dll} is built with GNU tools as in this case it is possible
27676 to link directly against the DLL. Otherwise read on.
27678 @node The Definition File
27679 @subsubsection The Definition File
27680 @cindex Definition file
27681 @findex .def
27683 @noindent
27684 As previously mentioned, and unlike Unix systems, the list of symbols
27685 that are exported from a DLL must be provided explicitly in Windows.
27686 The main goal of a definition file is precisely that: list the symbols
27687 exported by a DLL. A definition file (usually a file with a @code{.def}
27688 suffix) has the following structure:
27690 @smallexample
27691 @group
27692 @cartouche
27693 [LIBRARY @i{name}]
27694 [DESCRIPTION @i{string}]
27695 EXPORTS
27696    @i{symbol1}
27697    @i{symbol2}
27698    ...
27699 @end cartouche
27700 @end group
27701 @end smallexample
27703 @table @code
27704 @item LIBRARY @i{name}
27705 This section, which is optional, gives the name of the DLL.
27707 @item DESCRIPTION @i{string}
27708 This section, which is optional, gives a description string that will be
27709 embedded in the import library.
27711 @item EXPORTS
27712 This section gives the list of exported symbols (procedures, functions or
27713 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
27714 section of @file{API.def} looks like:
27716 @smallexample
27717 @group
27718 @cartouche
27719 EXPORTS
27720    some_var
27721    get
27722 @end cartouche
27723 @end group
27724 @end smallexample
27725 @end table
27727 @noindent
27728 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
27729 (@pxref{Windows Calling Conventions}) for a Stdcall
27730 calling convention function in the exported symbols list.
27732 @noindent
27733 There can actually be other sections in a definition file, but these
27734 sections are not relevant to the discussion at hand.
27736 @node GNAT-Style Import Library
27737 @subsubsection GNAT-Style Import Library
27739 @noindent
27740 To create a static import library from @file{API.dll} with the GNAT tools
27741 you should proceed as follows:
27743 @enumerate
27744 @item
27745 Create the definition file @file{API.def} (@pxref{The Definition File}).
27746 For that use the @code{dll2def} tool as follows:
27748 @smallexample
27749 $ dll2def API.dll > API.def
27750 @end smallexample
27752 @noindent
27753 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
27754 to standard output the list of entry points in the DLL. Note that if
27755 some routines in the DLL have the @code{Stdcall} convention
27756 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
27757 suffix then you'll have to edit @file{api.def} to add it, and specify
27758 @code{-k} to @code{gnatdll} when creating the import library.
27760 @noindent
27761 Here are some hints to find the right @code{@@}@i{nn} suffix.
27763 @enumerate
27764 @item
27765 If you have the Microsoft import library (.lib), it is possible to get
27766 the right symbols by using Microsoft @code{dumpbin} tool (see the
27767 corresponding Microsoft documentation for further details).
27769 @smallexample
27770 $ dumpbin /exports api.lib
27771 @end smallexample
27773 @item
27774 If you have a message about a missing symbol at link time the compiler
27775 tells you what symbol is expected. You just have to go back to the
27776 definition file and add the right suffix.
27777 @end enumerate
27779 @item
27780 Build the import library @code{libAPI.a}, using @code{gnatdll}
27781 (@pxref{Using gnatdll}) as follows:
27783 @smallexample
27784 $ gnatdll -e API.def -d API.dll
27785 @end smallexample
27787 @noindent
27788 @code{gnatdll} takes as input a definition file @file{API.def} and the
27789 name of the DLL containing the services listed in the definition file
27790 @file{API.dll}. The name of the static import library generated is
27791 computed from the name of the definition file as follows: if the
27792 definition file name is @i{xyz}@code{.def}, the import library name will
27793 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
27794 @option{-e} could have been removed because the name of the definition
27795 file (before the ``@code{.def}'' suffix) is the same as the name of the
27796 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
27797 @end enumerate
27799 @node Microsoft-Style Import Library
27800 @subsubsection Microsoft-Style Import Library
27802 @noindent
27803 With GNAT you can either use a GNAT-style or Microsoft-style import
27804 library. A Microsoft import library is needed only if you plan to make an
27805 Ada DLL available to applications developed with Microsoft
27806 tools (@pxref{Mixed-Language Programming on Windows}).
27808 To create a Microsoft-style import library for @file{API.dll} you
27809 should proceed as follows:
27811 @enumerate
27812 @item
27813 Create the definition file @file{API.def} from the DLL. For this use either
27814 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
27815 tool (see the corresponding Microsoft documentation for further details).
27817 @item
27818 Build the actual import library using Microsoft's @code{lib} utility:
27820 @smallexample
27821 $ lib -machine:IX86 -def:API.def -out:API.lib
27822 @end smallexample
27824 @noindent
27825 If you use the above command the definition file @file{API.def} must
27826 contain a line giving the name of the DLL:
27828 @smallexample
27829 LIBRARY      "API"
27830 @end smallexample
27832 @noindent
27833 See the Microsoft documentation for further details about the usage of
27834 @code{lib}.
27835 @end enumerate
27837 @node Building DLLs with GNAT
27838 @section Building DLLs with GNAT
27839 @cindex DLLs, building
27841 @noindent
27842 This section explain how to build DLLs using the GNAT built-in DLL
27843 support. With the following procedure it is straight forward to build
27844 and use DLLs with GNAT.
27846 @enumerate
27848 @item building object files
27850 The first step is to build all objects files that are to be included
27851 into the DLL. This is done by using the standard @command{gnatmake} tool.
27853 @item building the DLL
27855 To build the DLL you must use @command{gcc}'s @code{-shared}
27856 option. It is quite simple to use this method:
27858 @smallexample
27859 $ gcc -shared -o api.dll obj1.o obj2.o ...
27860 @end smallexample
27862 It is important to note that in this case all symbols found in the
27863 object files are automatically exported. It is possible to restrict
27864 the set of symbols to export by passing to @command{gcc} a definition
27865 file, @pxref{The Definition File}. For example:
27867 @smallexample
27868 $ gcc -shared -o api.dll api.def obj1.o obj2.o ...
27869 @end smallexample
27871 If you use a definition file you must export the elaboration procedures
27872 for every package that required one. Elaboration procedures are named
27873 using the package name followed by "_E".
27875 @item preparing DLL to be used
27877 For the DLL to be used by client programs the bodies must be hidden
27878 from it and the .ali set with read-only attribute. This is very important
27879 otherwise GNAT will recompile all packages and will not actually use
27880 the code in the DLL. For example:
27882 @smallexample
27883 $ mkdir apilib
27884 $ copy *.ads *.ali api.dll apilib
27885 $ attrib +R apilib\*.ali
27886 @end smallexample
27888 @end enumerate
27890 At this point it is possible to use the DLL by directly linking
27891 against it. Note that you must use the GNAT shared runtime when using
27892 GNAT shared libraries. This is achieved by using @code{-shared} binder's
27893 option.
27895 @smallexample
27896 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
27897 @end smallexample
27899 @node Building DLLs with GNAT Project files
27900 @section Building DLLs with GNAT Project files
27901 @cindex DLLs, building
27903 @noindent
27904 There is nothing specific to Windows in this area. @pxref{Library Projects}.
27906 @node Building DLLs with gnatdll
27907 @section Building DLLs with gnatdll
27908 @cindex DLLs, building
27910 @menu
27911 * Limitations When Using Ada DLLs from Ada::
27912 * Exporting Ada Entities::
27913 * Ada DLLs and Elaboration::
27914 * Ada DLLs and Finalization::
27915 * Creating a Spec for Ada DLLs::
27916 * Creating the Definition File::
27917 * Using gnatdll::
27918 @end menu
27920 @noindent
27921 Note that it is prefered to use the built-in GNAT DLL support
27922 (@pxref{Building DLLs with GNAT}) or GNAT Project files
27923 (@pxref{Building DLLs with GNAT Project files}) to build DLLs.
27925 This section explains how to build DLLs containing Ada code using
27926 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
27927 remainder of this section.
27929 The steps required to build an Ada DLL that is to be used by Ada as well as
27930 non-Ada applications are as follows:
27932 @enumerate
27933 @item
27934 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
27935 @code{Stdcall} calling convention to avoid any Ada name mangling for the
27936 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
27937 skip this step if you plan to use the Ada DLL only from Ada applications.
27939 @item
27940 Your Ada code must export an initialization routine which calls the routine
27941 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
27942 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
27943 routine exported by the Ada DLL must be invoked by the clients of the DLL
27944 to initialize the DLL.
27946 @item
27947 When useful, the DLL should also export a finalization routine which calls
27948 routine @code{adafinal} generated by @command{gnatbind} to perform the
27949 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
27950 The finalization routine exported by the Ada DLL must be invoked by the
27951 clients of the DLL when the DLL services are no further needed.
27953 @item
27954 You must provide a spec for the services exported by the Ada DLL in each
27955 of the programming languages to which you plan to make the DLL available.
27957 @item
27958 You must provide a definition file listing the exported entities
27959 (@pxref{The Definition File}).
27961 @item
27962 Finally you must use @code{gnatdll} to produce the DLL and the import
27963 library (@pxref{Using gnatdll}).
27964 @end enumerate
27966 @noindent
27967 Note that a relocatable DLL stripped using the @code{strip} binutils
27968 tool will not be relocatable anymore. To build a DLL without debug
27969 information pass @code{-largs -s} to @code{gnatdll}.
27971 @node Limitations When Using Ada DLLs from Ada
27972 @subsection Limitations When Using Ada DLLs from Ada
27974 @noindent
27975 When using Ada DLLs from Ada applications there is a limitation users
27976 should be aware of. Because on Windows the GNAT run time is not in a DLL of
27977 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
27978 each Ada DLL includes the services of the GNAT run time that are necessary
27979 to the Ada code inside the DLL. As a result, when an Ada program uses an
27980 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
27981 one in the main program.
27983 It is therefore not possible to exchange GNAT run-time objects between the
27984 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
27985 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
27986 types, etc.
27988 It is completely safe to exchange plain elementary, array or record types,
27989 Windows object handles, etc.
27991 @node Exporting Ada Entities
27992 @subsection Exporting Ada Entities
27993 @cindex Export table
27995 @noindent
27996 Building a DLL is a way to encapsulate a set of services usable from any
27997 application. As a result, the Ada entities exported by a DLL should be
27998 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
27999 any Ada name mangling. Please note that the @code{Stdcall} convention
28000 should only be used for subprograms, not for variables. As an example here
28001 is an Ada package @code{API}, spec and body, exporting two procedures, a
28002 function, and a variable:
28004 @smallexample @c ada
28005 @group
28006 @cartouche
28007 with Interfaces.C; use Interfaces;
28008 package API is
28009    Count : C.int := 0;
28010    function Factorial (Val : C.int) return C.int;
28012    procedure Initialize_API;
28013    procedure Finalize_API;
28014    --  Initialization & Finalization routines. More in the next section.
28015 private
28016    pragma Export (C, Initialize_API);
28017    pragma Export (C, Finalize_API);
28018    pragma Export (C, Count);
28019    pragma Export (C, Factorial);
28020 end API;
28021 @end cartouche
28022 @end group
28023 @end smallexample
28025 @smallexample @c ada
28026 @group
28027 @cartouche
28028 package body API is
28029    function Factorial (Val : C.int) return C.int is
28030       Fact : C.int := 1;
28031    begin
28032       Count := Count + 1;
28033       for K in 1 .. Val loop
28034          Fact := Fact * K;
28035       end loop;
28036       return Fact;
28037    end Factorial;
28039    procedure Initialize_API is
28040       procedure Adainit;
28041       pragma Import (C, Adainit);
28042    begin
28043       Adainit;
28044    end Initialize_API;
28046    procedure Finalize_API is
28047       procedure Adafinal;
28048       pragma Import (C, Adafinal);
28049    begin
28050       Adafinal;
28051    end Finalize_API;
28052 end API;
28053 @end cartouche
28054 @end group
28055 @end smallexample
28057 @noindent
28058 If the Ada DLL you are building will only be used by Ada applications
28059 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
28060 convention. As an example, the previous package could be written as
28061 follows:
28063 @smallexample @c ada
28064 @group
28065 @cartouche
28066 package API is
28067    Count : Integer := 0;
28068    function Factorial (Val : Integer) return Integer;
28070    procedure Initialize_API;
28071    procedure Finalize_API;
28072    --  Initialization and Finalization routines.
28073 end API;
28074 @end cartouche
28075 @end group
28076 @end smallexample
28078 @smallexample @c ada
28079 @group
28080 @cartouche
28081 package body API is
28082    function Factorial (Val : Integer) return Integer is
28083       Fact : Integer := 1;
28084    begin
28085       Count := Count + 1;
28086       for K in 1 .. Val loop
28087          Fact := Fact * K;
28088       end loop;
28089       return Fact;
28090    end Factorial;
28092    ...
28093    --  The remainder of this package body is unchanged.
28094 end API;
28095 @end cartouche
28096 @end group
28097 @end smallexample
28099 @noindent
28100 Note that if you do not export the Ada entities with a @code{C} or
28101 @code{Stdcall} convention you will have to provide the mangled Ada names
28102 in the definition file of the Ada DLL
28103 (@pxref{Creating the Definition File}).
28105 @node Ada DLLs and Elaboration
28106 @subsection Ada DLLs and Elaboration
28107 @cindex DLLs and elaboration
28109 @noindent
28110 The DLL that you are building contains your Ada code as well as all the
28111 routines in the Ada library that are needed by it. The first thing a
28112 user of your DLL must do is elaborate the Ada code
28113 (@pxref{Elaboration Order Handling in GNAT}).
28115 To achieve this you must export an initialization routine
28116 (@code{Initialize_API} in the previous example), which must be invoked
28117 before using any of the DLL services. This elaboration routine must call
28118 the Ada elaboration routine @code{adainit} generated by the GNAT binder
28119 (@pxref{Binding with Non-Ada Main Programs}). See the body of
28120 @code{Initialize_Api} for an example. Note that the GNAT binder is
28121 automatically invoked during the DLL build process by the @code{gnatdll}
28122 tool (@pxref{Using gnatdll}).
28124 When a DLL is loaded, Windows systematically invokes a routine called
28125 @code{DllMain}. It would therefore be possible to call @code{adainit}
28126 directly from @code{DllMain} without having to provide an explicit
28127 initialization routine. Unfortunately, it is not possible to call
28128 @code{adainit} from the @code{DllMain} if your program has library level
28129 tasks because access to the @code{DllMain} entry point is serialized by
28130 the system (that is, only a single thread can execute ``through'' it at a
28131 time), which means that the GNAT run time will deadlock waiting for the
28132 newly created task to complete its initialization.
28134 @node Ada DLLs and Finalization
28135 @subsection Ada DLLs and Finalization
28136 @cindex DLLs and finalization
28138 @noindent
28139 When the services of an Ada DLL are no longer needed, the client code should
28140 invoke the DLL finalization routine, if available. The DLL finalization
28141 routine is in charge of releasing all resources acquired by the DLL. In the
28142 case of the Ada code contained in the DLL, this is achieved by calling
28143 routine @code{adafinal} generated by the GNAT binder
28144 (@pxref{Binding with Non-Ada Main Programs}).
28145 See the body of @code{Finalize_Api} for an
28146 example. As already pointed out the GNAT binder is automatically invoked
28147 during the DLL build process by the @code{gnatdll} tool
28148 (@pxref{Using gnatdll}).
28150 @node Creating a Spec for Ada DLLs
28151 @subsection Creating a Spec for Ada DLLs
28153 @noindent
28154 To use the services exported by the Ada DLL from another programming
28155 language (e.g. C), you have to translate the specs of the exported Ada
28156 entities in that language. For instance in the case of @code{API.dll},
28157 the corresponding C header file could look like:
28159 @smallexample
28160 @group
28161 @cartouche
28162 extern int *_imp__count;
28163 #define count (*_imp__count)
28164 int factorial (int);
28165 @end cartouche
28166 @end group
28167 @end smallexample
28169 @noindent
28170 It is important to understand that when building an Ada DLL to be used by
28171 other Ada applications, you need two different specs for the packages
28172 contained in the DLL: one for building the DLL and the other for using
28173 the DLL. This is because the @code{DLL} calling convention is needed to
28174 use a variable defined in a DLL, but when building the DLL, the variable
28175 must have either the @code{Ada} or @code{C} calling convention. As an
28176 example consider a DLL comprising the following package @code{API}:
28178 @smallexample @c ada
28179 @group
28180 @cartouche
28181 package API is
28182    Count : Integer := 0;
28183    ...
28184    --  Remainder of the package omitted.
28185 end API;
28186 @end cartouche
28187 @end group
28188 @end smallexample
28190 @noindent
28191 After producing a DLL containing package @code{API}, the spec that
28192 must be used to import @code{API.Count} from Ada code outside of the
28193 DLL is:
28195 @smallexample @c ada
28196 @group
28197 @cartouche
28198 package API is
28199    Count : Integer;
28200    pragma Import (DLL, Count);
28201 end API;
28202 @end cartouche
28203 @end group
28204 @end smallexample
28206 @node Creating the Definition File
28207 @subsection Creating the Definition File
28209 @noindent
28210 The definition file is the last file needed to build the DLL. It lists
28211 the exported symbols. As an example, the definition file for a DLL
28212 containing only package @code{API} (where all the entities are exported
28213 with a @code{C} calling convention) is:
28215 @smallexample
28216 @group
28217 @cartouche
28218 EXPORTS
28219     count
28220     factorial
28221     finalize_api
28222     initialize_api
28223 @end cartouche
28224 @end group
28225 @end smallexample
28227 @noindent
28228 If the @code{C} calling convention is missing from package @code{API},
28229 then the definition file contains the mangled Ada names of the above
28230 entities, which in this case are:
28232 @smallexample
28233 @group
28234 @cartouche
28235 EXPORTS
28236     api__count
28237     api__factorial
28238     api__finalize_api
28239     api__initialize_api
28240 @end cartouche
28241 @end group
28242 @end smallexample
28244 @node Using gnatdll
28245 @subsection Using @code{gnatdll}
28246 @findex gnatdll
28248 @menu
28249 * gnatdll Example::
28250 * gnatdll behind the Scenes::
28251 * Using dlltool::
28252 @end menu
28254 @noindent
28255 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
28256 and non-Ada sources that make up your DLL have been compiled.
28257 @code{gnatdll} is actually in charge of two distinct tasks: build the
28258 static import library for the DLL and the actual DLL. The form of the
28259 @code{gnatdll} command is
28261 @smallexample
28262 @cartouche
28263 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
28264 @end cartouche
28265 @end smallexample
28267 @noindent
28268 where @i{list-of-files} is a list of ALI and object files. The object
28269 file list must be the exact list of objects corresponding to the non-Ada
28270 sources whose services are to be included in the DLL. The ALI file list
28271 must be the exact list of ALI files for the corresponding Ada sources
28272 whose services are to be included in the DLL. If @i{list-of-files} is
28273 missing, only the static import library is generated.
28275 @noindent
28276 You may specify any of the following switches to @code{gnatdll}:
28278 @table @code
28279 @item -a[@var{address}]
28280 @cindex @option{-a} (@code{gnatdll})
28281 Build a non-relocatable DLL at @var{address}. If @var{address} is not
28282 specified the default address @var{0x11000000} will be used. By default,
28283 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
28284 advise the reader to build relocatable DLL.
28286 @item -b @var{address}
28287 @cindex @option{-b} (@code{gnatdll})
28288 Set the relocatable DLL base address. By default the address is
28289 @var{0x11000000}.
28291 @item -bargs @var{opts}
28292 @cindex @option{-bargs} (@code{gnatdll})
28293 Binder options. Pass @var{opts} to the binder.
28295 @item -d @var{dllfile}
28296 @cindex @option{-d} (@code{gnatdll})
28297 @var{dllfile} is the name of the DLL. This switch must be present for
28298 @code{gnatdll} to do anything. The name of the generated import library is
28299 obtained algorithmically from @var{dllfile} as shown in the following
28300 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
28301 @code{libxyz.a}. The name of the definition file to use (if not specified
28302 by option @option{-e}) is obtained algorithmically from @var{dllfile}
28303 as shown in the following example:
28304 if @var{dllfile} is @code{xyz.dll}, the definition
28305 file used is @code{xyz.def}.
28307 @item -e @var{deffile}
28308 @cindex @option{-e} (@code{gnatdll})
28309 @var{deffile} is the name of the definition file.
28311 @item -g
28312 @cindex @option{-g} (@code{gnatdll})
28313 Generate debugging information. This information is stored in the object
28314 file and copied from there to the final DLL file by the linker,
28315 where it can be read by the debugger. You must use the
28316 @option{-g} switch if you plan on using the debugger or the symbolic
28317 stack traceback.
28319 @item -h
28320 @cindex @option{-h} (@code{gnatdll})
28321 Help mode. Displays @code{gnatdll} switch usage information.
28323 @item -Idir
28324 @cindex @option{-I} (@code{gnatdll})
28325 Direct @code{gnatdll} to search the @var{dir} directory for source and
28326 object files needed to build the DLL.
28327 (@pxref{Search Paths and the Run-Time Library (RTL)}).
28329 @item -k
28330 @cindex @option{-k} (@code{gnatdll})
28331 Removes the @code{@@}@i{nn} suffix from the import library's exported
28332 names, but keeps them for the link names. You must specify this
28333 option if you want to use a @code{Stdcall} function in a DLL for which
28334 the @code{@@}@i{nn} suffix has been removed. This is the case for most
28335 of the Windows NT DLL for example. This option has no effect when
28336 @option{-n} option is specified.
28338 @item -l @var{file}
28339 @cindex @option{-l} (@code{gnatdll})
28340 The list of ALI and object files used to build the DLL are listed in
28341 @var{file}, instead of being given in the command line. Each line in
28342 @var{file} contains the name of an ALI or object file.
28344 @item -n
28345 @cindex @option{-n} (@code{gnatdll})
28346 No Import. Do not create the import library.
28348 @item -q
28349 @cindex @option{-q} (@code{gnatdll})
28350 Quiet mode. Do not display unnecessary messages.
28352 @item -v
28353 @cindex @option{-v} (@code{gnatdll})
28354 Verbose mode. Display extra information.
28356 @item -largs @var{opts}
28357 @cindex @option{-largs} (@code{gnatdll})
28358 Linker options. Pass @var{opts} to the linker.
28359 @end table
28361 @node gnatdll Example
28362 @subsubsection @code{gnatdll} Example
28364 @noindent
28365 As an example the command to build a relocatable DLL from @file{api.adb}
28366 once @file{api.adb} has been compiled and @file{api.def} created is
28368 @smallexample
28369 $ gnatdll -d api.dll api.ali
28370 @end smallexample
28372 @noindent
28373 The above command creates two files: @file{libapi.a} (the import
28374 library) and @file{api.dll} (the actual DLL). If you want to create
28375 only the DLL, just type:
28377 @smallexample
28378 $ gnatdll -d api.dll -n api.ali
28379 @end smallexample
28381 @noindent
28382 Alternatively if you want to create just the import library, type:
28384 @smallexample
28385 $ gnatdll -d api.dll
28386 @end smallexample
28388 @node gnatdll behind the Scenes
28389 @subsubsection @code{gnatdll} behind the Scenes
28391 @noindent
28392 This section details the steps involved in creating a DLL. @code{gnatdll}
28393 does these steps for you. Unless you are interested in understanding what
28394 goes on behind the scenes, you should skip this section.
28396 We use the previous example of a DLL containing the Ada package @code{API},
28397 to illustrate the steps necessary to build a DLL. The starting point is a
28398 set of objects that will make up the DLL and the corresponding ALI
28399 files. In the case of this example this means that @file{api.o} and
28400 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
28401 the following:
28403 @enumerate
28404 @item
28405 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
28406 the information necessary to generate relocation information for the
28407 DLL.
28409 @smallexample
28410 @group
28411 $ gnatbind -n api
28412 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
28413 @end group
28414 @end smallexample
28416 @noindent
28417 In addition to the base file, the @command{gnatlink} command generates an
28418 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
28419 asks @command{gnatlink} to generate the routines @code{DllMain} and
28420 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
28421 is loaded into memory.
28423 @item
28424 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
28425 export table (@file{api.exp}). The export table contains the relocation
28426 information in a form which can be used during the final link to ensure
28427 that the Windows loader is able to place the DLL anywhere in memory.
28429 @smallexample
28430 @group
28431 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28432           --output-exp api.exp
28433 @end group
28434 @end smallexample
28436 @item
28437 @code{gnatdll} builds the base file using the new export table. Note that
28438 @command{gnatbind} must be called once again since the binder generated file
28439 has been deleted during the previous call to @command{gnatlink}.
28441 @smallexample
28442 @group
28443 $ gnatbind -n api
28444 $ gnatlink api -o api.jnk api.exp -mdll
28445       -Wl,--base-file,api.base
28446 @end group
28447 @end smallexample
28449 @item
28450 @code{gnatdll} builds the new export table using the new base file and
28451 generates the DLL import library @file{libAPI.a}.
28453 @smallexample
28454 @group
28455 $ dlltool --dllname api.dll --def api.def --base-file api.base \
28456           --output-exp api.exp --output-lib libAPI.a
28457 @end group
28458 @end smallexample
28460 @item
28461 Finally @code{gnatdll} builds the relocatable DLL using the final export
28462 table.
28464 @smallexample
28465 @group
28466 $ gnatbind -n api
28467 $ gnatlink api api.exp -o api.dll -mdll
28468 @end group
28469 @end smallexample
28470 @end enumerate
28472 @node Using dlltool
28473 @subsubsection Using @code{dlltool}
28475 @noindent
28476 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
28477 DLLs and static import libraries. This section summarizes the most
28478 common @code{dlltool} switches. The form of the @code{dlltool} command
28481 @smallexample
28482 $ dlltool [@var{switches}]
28483 @end smallexample
28485 @noindent
28486 @code{dlltool} switches include:
28488 @table @option
28489 @item --base-file @var{basefile}
28490 @cindex @option{--base-file} (@command{dlltool})
28491 Read the base file @var{basefile} generated by the linker. This switch
28492 is used to create a relocatable DLL.
28494 @item --def @var{deffile}
28495 @cindex @option{--def} (@command{dlltool})
28496 Read the definition file.
28498 @item --dllname @var{name}
28499 @cindex @option{--dllname} (@command{dlltool})
28500 Gives the name of the DLL. This switch is used to embed the name of the
28501 DLL in the static import library generated by @code{dlltool} with switch
28502 @option{--output-lib}.
28504 @item -k
28505 @cindex @option{-k} (@command{dlltool})
28506 Kill @code{@@}@i{nn} from exported names
28507 (@pxref{Windows Calling Conventions}
28508 for a discussion about @code{Stdcall}-style symbols.
28510 @item --help
28511 @cindex @option{--help} (@command{dlltool})
28512 Prints the @code{dlltool} switches with a concise description.
28514 @item --output-exp @var{exportfile}
28515 @cindex @option{--output-exp} (@command{dlltool})
28516 Generate an export file @var{exportfile}. The export file contains the
28517 export table (list of symbols in the DLL) and is used to create the DLL.
28519 @item --output-lib @i{libfile}
28520 @cindex @option{--output-lib} (@command{dlltool})
28521 Generate a static import library @var{libfile}.
28523 @item -v
28524 @cindex @option{-v} (@command{dlltool})
28525 Verbose mode.
28527 @item --as @i{assembler-name}
28528 @cindex @option{--as} (@command{dlltool})
28529 Use @i{assembler-name} as the assembler. The default is @code{as}.
28530 @end table
28532 @node GNAT and Windows Resources
28533 @section GNAT and Windows Resources
28534 @cindex Resources, windows
28536 @menu
28537 * Building Resources::
28538 * Compiling Resources::
28539 * Using Resources::
28540 @end menu
28542 @noindent
28543 Resources are an easy way to add Windows specific objects to your
28544 application. The objects that can be added as resources include:
28546 @itemize @bullet
28547 @item
28548 menus
28550 @item
28551 accelerators
28553 @item
28554 dialog boxes
28556 @item
28557 string tables
28559 @item
28560 bitmaps
28562 @item
28563 cursors
28565 @item
28566 icons
28568 @item
28569 fonts
28570 @end itemize
28572 @noindent
28573 This section explains how to build, compile and use resources.
28575 @node Building Resources
28576 @subsection Building Resources
28577 @cindex Resources, building
28579 @noindent
28580 A resource file is an ASCII file. By convention resource files have an
28581 @file{.rc} extension.
28582 The easiest way to build a resource file is to use Microsoft tools
28583 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
28584 @code{dlgedit.exe} to build dialogs.
28585 It is always possible to build an @file{.rc} file yourself by writing a
28586 resource script.
28588 It is not our objective to explain how to write a resource file. A
28589 complete description of the resource script language can be found in the
28590 Microsoft documentation.
28592 @node Compiling Resources
28593 @subsection Compiling Resources
28594 @findex rc
28595 @findex windres
28596 @cindex Resources, compiling
28598 @noindent
28599 This section describes how to build a GNAT-compatible (COFF) object file
28600 containing the resources. This is done using the Resource Compiler
28601 @code{windres} as follows:
28603 @smallexample
28604 $ windres -i myres.rc -o myres.o
28605 @end smallexample
28607 @noindent
28608 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
28609 file. You can specify an alternate preprocessor (usually named
28610 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
28611 parameter. A list of all possible options may be obtained by entering
28612 the command @code{windres} @option{--help}.
28614 It is also possible to use the Microsoft resource compiler @code{rc.exe}
28615 to produce a @file{.res} file (binary resource file). See the
28616 corresponding Microsoft documentation for further details. In this case
28617 you need to use @code{windres} to translate the @file{.res} file to a
28618 GNAT-compatible object file as follows:
28620 @smallexample
28621 $ windres -i myres.res -o myres.o
28622 @end smallexample
28624 @node Using Resources
28625 @subsection Using Resources
28626 @cindex Resources, using
28628 @noindent
28629 To include the resource file in your program just add the
28630 GNAT-compatible object file for the resource(s) to the linker
28631 arguments. With @command{gnatmake} this is done by using the @option{-largs}
28632 option:
28634 @smallexample
28635 $ gnatmake myprog -largs myres.o
28636 @end smallexample
28638 @node Debugging a DLL
28639 @section Debugging a DLL
28640 @cindex DLL debugging
28642 @menu
28643 * Program and DLL Both Built with GCC/GNAT::
28644 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
28645 @end menu
28647 @noindent
28648 Debugging a DLL is similar to debugging a standard program. But
28649 we have to deal with two different executable parts: the DLL and the
28650 program that uses it. We have the following four possibilities:
28652 @enumerate 1
28653 @item
28654 The program and the DLL are built with @code{GCC/GNAT}.
28655 @item
28656 The program is built with foreign tools and the DLL is built with
28657 @code{GCC/GNAT}.
28658 @item
28659 The program is built with @code{GCC/GNAT} and the DLL is built with
28660 foreign tools.
28661 @item
28662 @end enumerate
28664 @noindent
28665 In this section we address only cases one and two above.
28666 There is no point in trying to debug
28667 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
28668 information in it. To do so you must use a debugger compatible with the
28669 tools suite used to build the DLL.
28671 @node Program and DLL Both Built with GCC/GNAT
28672 @subsection Program and DLL Both Built with GCC/GNAT
28674 @noindent
28675 This is the simplest case. Both the DLL and the program have @code{GDB}
28676 compatible debugging information. It is then possible to break anywhere in
28677 the process. Let's suppose here that the main procedure is named
28678 @code{ada_main} and that in the DLL there is an entry point named
28679 @code{ada_dll}.
28681 @noindent
28682 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
28683 program must have been built with the debugging information (see GNAT -g
28684 switch). Here are the step-by-step instructions for debugging it:
28686 @enumerate 1
28687 @item Launch @code{GDB} on the main program.
28689 @smallexample
28690 $ gdb -nw ada_main
28691 @end smallexample
28693 @item Break on the main procedure and run the program.
28695 @smallexample
28696 (gdb) break ada_main
28697 (gdb) run
28698 @end smallexample
28700 @noindent
28701 This step is required to be able to set a breakpoint inside the DLL. As long
28702 as the program is not run, the DLL is not loaded. This has the
28703 consequence that the DLL debugging information is also not loaded, so it is not
28704 possible to set a breakpoint in the DLL.
28706 @item Set a breakpoint inside the DLL
28708 @smallexample
28709 (gdb) break ada_dll
28710 (gdb) run
28711 @end smallexample
28713 @end enumerate
28715 @noindent
28716 At this stage a breakpoint is set inside the DLL. From there on
28717 you can use the standard approach to debug the whole program
28718 (@pxref{Running and Debugging Ada Programs}).
28720 To break on the @code{DllMain} routine it is not possible to follow
28721 the procedure above. At the time the program stop on @code{ada_main}
28722 the @code{DllMain} routine as already been called. Either you can use
28723 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
28725 @enumerate 1
28726 @item Launch @code{GDB} on the main program.
28728 @smallexample
28729 $ gdb -nw ada_main
28730 @end smallexample
28732 @item Load DLL symbols
28734 @smallexample
28735 (gdb) add-sym api.dll
28736 @end smallexample
28738 @item Set a breakpoint inside the DLL
28740 @smallexample
28741 (gdb) break ada_dll.adb:45
28742 @end smallexample
28744 Note that at this point it is not possible to break using the routine symbol
28745 directly as the program is not yet running. The solution is to break
28746 on the proper line (break in @file{ada_dll.adb} line 45).
28748 @item Start the program
28750 @smallexample
28751 (gdb) run
28752 @end smallexample
28754 @end enumerate
28756 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
28757 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
28759 @menu
28760 * Debugging the DLL Directly::
28761 * Attaching to a Running Process::
28762 @end menu
28764 @noindent
28765 In this case things are slightly more complex because it is not possible to
28766 start the main program and then break at the beginning to load the DLL and the
28767 associated DLL debugging information. It is not possible to break at the
28768 beginning of the program because there is no @code{GDB} debugging information,
28769 and therefore there is no direct way of getting initial control. This
28770 section addresses this issue by describing some methods that can be used
28771 to break somewhere in the DLL to debug it.
28773 @noindent
28774 First suppose that the main procedure is named @code{main} (this is for
28775 example some C code built with Microsoft Visual C) and that there is a
28776 DLL named @code{test.dll} containing an Ada entry point named
28777 @code{ada_dll}.
28779 @noindent
28780 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
28781 been built with debugging information (see GNAT -g option).
28783 @node Debugging the DLL Directly
28784 @subsubsection Debugging the DLL Directly
28786 @enumerate 1
28787 @item
28788 Launch the debugger on the DLL.
28790 @smallexample
28791 $ gdb -nw test.dll
28792 @end smallexample
28794 @item Set a breakpoint on a DLL subroutine.
28796 @smallexample
28797 (gdb) break ada_dll.adb:45
28798 @end smallexample
28800 Note that at this point it is not possible to break using the routine symbol
28801 directly as the program is not yet running. The solution is to break
28802 on the proper line (break in @file{ada_dll.adb} line 45).
28804 @item
28805 Specify the executable file to @code{GDB}.
28807 @smallexample
28808 (gdb) exec-file main.exe
28809 @end smallexample
28811 @item
28812 Run the program.
28814 @smallexample
28815 (gdb) run
28816 @end smallexample
28818 @noindent
28819 This will run the program until it reaches the breakpoint that has been
28820 set. From that point you can use the standard way to debug a program
28821 as described in (@pxref{Running and Debugging Ada Programs}).
28823 @end enumerate
28825 @noindent
28826 It is also possible to debug the DLL by attaching to a running process.
28828 @node Attaching to a Running Process
28829 @subsubsection Attaching to a Running Process
28830 @cindex DLL debugging, attach to process
28832 @noindent
28833 With @code{GDB} it is always possible to debug a running process by
28834 attaching to it. It is possible to debug a DLL this way. The limitation
28835 of this approach is that the DLL must run long enough to perform the
28836 attach operation. It may be useful for instance to insert a time wasting
28837 loop in the code of the DLL to meet this criterion.
28839 @enumerate 1
28841 @item Launch the main program @file{main.exe}.
28843 @smallexample
28844 $ main
28845 @end smallexample
28847 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
28848 that the process PID for @file{main.exe} is 208.
28850 @item Launch gdb.
28852 @smallexample
28853 $ gdb -nw
28854 @end smallexample
28856 @item Attach to the running process to be debugged.
28858 @smallexample
28859 (gdb) attach 208
28860 @end smallexample
28862 @item Load the process debugging information.
28864 @smallexample
28865 (gdb) symbol-file main.exe
28866 @end smallexample
28868 @item Break somewhere in the DLL.
28870 @smallexample
28871 (gdb) break ada_dll
28872 @end smallexample
28874 @item Continue process execution.
28876 @smallexample
28877 (gdb) continue
28878 @end smallexample
28880 @end enumerate
28882 @noindent
28883 This last step will resume the process execution, and stop at
28884 the breakpoint we have set. From there you can use the standard
28885 approach to debug a program as described in
28886 (@pxref{Running and Debugging Ada Programs}).
28888 @node GNAT and COM/DCOM Objects
28889 @section GNAT and COM/DCOM Objects
28890 @findex COM
28891 @findex DCOM
28893 @noindent
28894 This section is temporarily left blank.
28896 @end ifset
28898 @c **********************************
28899 @c * GNU Free Documentation License *
28900 @c **********************************
28901 @include fdl.texi
28902 @c GNU Free Documentation License
28904 @node Index,,GNU Free Documentation License, Top
28905 @unnumbered Index
28907 @printindex cp
28909 @contents
28910 @c Put table of contents at end, otherwise it precedes the "title page" in
28911 @c the .txt version
28912 @c Edit the pdf file to move the contents to the beginning, after the title
28913 @c page
28915 @bye