2003-02-18 Ben Elliston <bje@redhat.com>
[official-gcc.git] / gcc / ada / gnat_ug.texi
blobbb9cf0dc59c29c558712b754a798a75e41c70a7d
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                                 o
9 @c                                                                            o
10 @c          Copyright (C) 1992-2002 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_UG 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.
44 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
45 @c     command must be preceded by two empty lines
47 @c  4. The @item command must be on a line of its own if it is in an
48 @c     @itemize or @enumerate command.
50 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
51 @c     or "ali".
53 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
55 @ifset vms
56 @setfilename gnat_ug_vms.info
57 @settitle GNAT User's Guide for OpenVMS Alpha
58 @end ifset
60 @ifset wnt
61 @setfilename gnat_ug_wnt.info
62 @settitle GNAT User's Guide for Windows NT
63 @end ifset
65 @ifset unx
66 @setfilename gnat_ug_unx.info
67 @settitle GNAT User's Guide for Unix Platforms
68 @end ifset
70 @ifset vxworks
71 @setfilename gnat_ug_vxw.info
72 @settitle GNAT User's Guide for Cross Platforms
73 @end ifset
75 @include gcc-common.texi
77 @setchapternewpage odd
78 @syncodeindex fn cp
79 @c %**end of header
81 @copying
82 Copyright @copyright{} 1995-2002, Free Software Foundation
84 Permission is granted to copy, distribute and/or modify this document
85 under the terms of the GNU Free Documentation License, Version 1.2
86 or any later version published by the Free Software Foundation;
87 with the Invariant Sections being ``GNU Free Documentation License'', with the
88 Front-Cover Texts being
89 @ifset vms
90 ``GNAT User's Guide for OpenVMS Alpha'',
91 @end ifset
92 @ifset wnt
93 ``GNAT User's Guide for Windows NT'',
94 @end ifset
95 @ifset unx
96 ``GNAT User's Guide for Unix Platforms'',
97 @end ifset
98 @ifset vxworks
99 ``GNAT User's Guide for Cross Platforms'',
100 @end ifset
101 and with no Back-Cover Texts.
102 A copy of the license is included in the section entitled ``GNU
103 Free Documentation License''.
104 @end copying
106 @titlepage
108 @ifset vms
109 @title GNAT User's Guide
110 @center @titlefont{for OpenVMS Alpha}
111 @end ifset
113 @ifset wnt
114 @title GNAT User's Guide
115 @center @titlefont{for Windows NT}
116 @end ifset
118 @ifset unx
119 @title GNAT User's Guide
120 @center @titlefont{for Unix Platforms}
121 @end ifset
123 @ifset vxworks
124 @title GNAT User's Guide
125 @center @titlefont{for Cross Platforms}
126 @end ifset
128 @subtitle GNAT, The GNU Ada 95 Compiler
129 @subtitle GNAT Version for GCC @value{version-GCC}
131 @author Ada Core Technologies, Inc.
133 @page
134 @vskip 0pt plus 1filll
136 @insertcopying
138 @end titlepage
140 @ifnottex
141 @node Top, About This Guide, (dir), (dir)
142 @top GNAT User's Guide
144 @ifset vms
145 GNAT User's Guide for OpenVMS Alpha
146 @end ifset
148 @ifset wnt
149 GNAT User's Guide for Windows NT
150 @end ifset
152 @ifset unx
153 GNAT User's Guide for Unix Platforms
154 @end ifset
156 @ifset vxworks
157 GNAT User's Guide for Cross Platforms
158 @end ifset
160 GNAT, The GNU Ada 95 Compiler
162 GNAT Version for GCC @value{version-GCC}
164 Ada Core Technologies, Inc.
166 @insertcopying
168 @menu
169 * About This Guide::
170 @ifset vxworks
171 * Preliminary Note for Cross Platform Users::
172 @end ifset
173 * Getting Started with GNAT::
174 * The GNAT Compilation Model::
175 * Compiling Using gcc::
176 * Binding Using gnatbind::
177 * Linking Using gnatlink::
178 * The GNAT Make Program gnatmake::
179 * Renaming Files Using gnatchop::
180 * Configuration Pragmas::
181 * Handling Arbitrary File Naming Conventions Using gnatname::
182 * GNAT Project Manager::
183 * Elaboration Order Handling in GNAT::
184 * The Cross-Referencing Tools gnatxref and gnatfind::
185 * File Name Krunching Using gnatkr::
186 * Preprocessing Using gnatprep::
187 @ifset vms
188 * The GNAT Run-Time Library Builder gnatlbr::
189 @end ifset
190 * The GNAT Library Browser gnatls::
191 @ifclear vms
192 * GNAT and Libraries::
193 * Using the GNU make Utility::
194 @ifclear vxworks
195 * Finding Memory Problems with gnatmem::
196 @end ifclear
197 @end ifclear
198 * Finding Memory Problems with GNAT Debug Pool::
199 * Creating Sample Bodies Using gnatstub::
200 * Reducing the Size of Ada Executables with gnatelim::
201 * Other Utility Programs::
202 @ifset vms
203 * Compatibility with DEC Ada::
204 @end ifset
205 * Running and Debugging Ada Programs::
206 * Inline Assembler::
207 @ifset wnt
208 * Microsoft Windows Topics::
209 @end ifset
210 @ifset vxworks
211 * VxWorks Topics::
212 * LynxOS Topics::
213 @end ifset
214 * Performance Considerations::
215 * GNU Free Documentation License::
216 * Index::
218  --- The Detailed Node Listing ---
220 About This Guide
222 * What This Guide Contains::
223 * What You Should Know before Reading This Guide::
224 * Related Information::
225 * Conventions::
227 @ifset vxworks
228 Preliminary Note for Cross Platform Users::
229 @end ifset
231 Getting Started with GNAT
233 * Running GNAT::
234 @ifclear vxworks
235 * Running a Simple Ada Program::
236 @end ifclear
237 @ifset vxworks
238 * Building a Simple Ada Program::
239 * Executing a Program on VxWorks::
240 @end ifset
241 * Running a Program with Multiple Units::
242 * Using the gnatmake Utility::
243 @ifset vms
244 * Editing with Emacs::
245 @end ifset
247 The GNAT Compilation Model
249 * Source Representation::
250 * Foreign Language Representation::
251 * File Naming Rules::
252 * Using Other File Names::
253 * Alternative File Naming Schemes::
254 * Generating Object Files::
255 * Source Dependencies::
256 * The Ada Library Information Files::
257 * Binding an Ada Program::
258 * Mixed Language Programming::
259 * Building Mixed Ada & C++ Programs::
260 * Comparison between GNAT and C/C++ Compilation Models::
261 * Comparison between GNAT and Conventional Ada Library Models::
263 Foreign Language Representation
265 * Latin-1::
266 * Other 8-Bit Codes::
267 * Wide Character Encodings::
269 Compiling Ada Programs With gcc
271 * Compiling Programs::
272 * Switches for gcc::
273 * Search Paths and the Run-Time Library (RTL)::
274 * Order of Compilation Issues::
275 * Examples::
277 Switches for gcc
279 * Output and Error Message Control::
280 * Debugging and Assertion Control::
281 * Run-Time Checks::
282 * Stack Overflow Checking::
283 * Run-Time Control::
284 * Validity Checking::
285 * Style Checking::
286 * Using gcc for Syntax Checking::
287 * Using gcc for Semantic Checking::
288 * Compiling Ada 83 Programs::
289 * Character Set Control::
290 * File Naming Control::
291 * Subprogram Inlining Control::
292 * Auxiliary Output Control::
293 * Debugging Control::
294 * Units to Sources Mapping Files::
296 Binding Ada Programs With gnatbind
298 * Running gnatbind::
299 * Generating the Binder Program in C::
300 * Consistency-Checking Modes::
301 * Binder Error Message Control::
302 * Elaboration Control::
303 * Output Control::
304 * Binding with Non-Ada Main Programs::
305 * Binding Programs with No Main Subprogram::
306 * Summary of Binder Switches::
307 * Command-Line Access::
308 * Search Paths for gnatbind::
309 * Examples of gnatbind Usage::
311 Linking Using gnatlink
313 * Running gnatlink::
314 * Switches for gnatlink::
315 * Setting Stack Size from gnatlink::
316 * Setting Heap Size from gnatlink::
318 The GNAT Make Program gnatmake
320 * Running gnatmake::
321 * Switches for gnatmake::
322 * Mode Switches for gnatmake::
323 * Notes on the Command Line::
324 * How gnatmake Works::
325 * Examples of gnatmake Usage::
327 Renaming Files Using gnatchop
329 * Handling Files with Multiple Units::
330 * Operating gnatchop in Compilation Mode::
331 * Command Line for gnatchop::
332 * Switches for gnatchop::
333 * Examples of gnatchop Usage::
335 Configuration Pragmas
337 * Handling of Configuration Pragmas::
338 * The Configuration Pragmas Files::
340 Handling Arbitrary File Naming Conventions Using gnatname
342 * Arbitrary File Naming Conventions::
343 * Running gnatname::
344 * Switches for gnatname::
345 * Examples of gnatname Usage::
347 GNAT Project Manager
349 * Introduction::
350 * Examples of Project Files::
351 * Project File Syntax::
352 * Objects and Sources in Project Files::
353 * Importing Projects::
354 * Project Extension::
355 * External References in Project Files::
356 * Packages in Project Files::
357 * Variables from Imported Projects::
358 * Naming Schemes::
359 * Library Projects::
360 * Switches Related to Project Files::
361 * Tools Supporting Project Files::
362 * An Extended Example::
363 * Project File Complete Syntax::
365 Elaboration Order Handling in GNAT
367 * Elaboration Code in Ada 95::
368 * Checking the Elaboration Order in Ada 95::
369 * Controlling the Elaboration Order in Ada 95::
370 * Controlling Elaboration in GNAT - Internal Calls::
371 * Controlling Elaboration in GNAT - External Calls::
372 * Default Behavior in GNAT - Ensuring Safety::
373 * Elaboration Issues for Library Tasks::
374 * Mixing Elaboration Models::
375 * What to Do If the Default Elaboration Behavior Fails::
376 * Elaboration for Access-to-Subprogram Values::
377 * Summary of Procedures for Elaboration Control::
378 * Other Elaboration Order Considerations::
380 The Cross-Referencing Tools gnatxref and gnatfind
382 * gnatxref Switches::
383 * gnatfind Switches::
384 * Project Files for gnatxref and gnatfind::
385 * Regular Expressions in gnatfind and gnatxref::
386 * Examples of gnatxref Usage::
387 * Examples of gnatfind Usage::
389 File Name Krunching Using gnatkr
391 * About gnatkr::
392 * Using gnatkr::
393 * Krunching Method::
394 * Examples of gnatkr Usage::
396 Preprocessing Using gnatprep
398 * Using gnatprep::
399 * Switches for gnatprep::
400 * Form of Definitions File::
401 * Form of Input Text for gnatprep::
403 @ifset vms
404 The GNAT Run-Time Library Builder gnatlbr
406 * Running gnatlbr::
407 * Switches for gnatlbr::
408 * Examples of gnatlbr Usage::
409 @end ifset
411 The GNAT Library Browser gnatls
413 * Running gnatls::
414 * Switches for gnatls::
415 * Examples of gnatls Usage::
417 @ifclear vms
419 GNAT and Libraries
421 * Creating an Ada Library::
422 * Installing an Ada Library::
423 * Using an Ada Library::
424 * Creating an Ada Library to be Used in a Non-Ada Context::
425 * Rebuilding the GNAT Run-Time Library::
427 Using the GNU make Utility
429 * Using gnatmake in a Makefile::
430 * Automatically Creating a List of Directories::
431 * Generating the Command Line Switches::
432 * Overcoming Command Line Length Limits::
434 @ifclear vxworks
435 Finding Memory Problems with gnatmem
437 * Running gnatmem (GDB Mode)::
438 * Running gnatmem (GMEM Mode)::
439 * Switches for gnatmem::
440 * Examples of gnatmem Usage::
441 * GDB and GMEM Modes::
442 * Implementation Note::
444 @end ifclear
445 @end ifclear
447 Finding Memory Problems with GNAT Debug Pool
449 Creating Sample Bodies Using gnatstub
451 * Running gnatstub::
452 * Switches for gnatstub::
454 Reducing the Size of Ada Executables with gnatelim
456 * About gnatelim::
457 * Eliminate Pragma::
458 * Tree Files::
459 * Preparing Tree and Bind Files for gnatelim::
460 * Running gnatelim::
461 * Correcting the List of Eliminate Pragmas::
462 * Making Your Executables Smaller::
463 * Summary of the gnatelim Usage Cycle::
465 Other Utility Programs
467 * Using Other Utility Programs with GNAT::
468 * The gnatpsta Utility Program::
469 * The External Symbol Naming Scheme of GNAT::
470 * Ada Mode for Glide::
471 * Converting Ada Files to html with gnathtml::
472 @ifset vms
473 * LSE::
474 @end ifset
476 @ifset vms
477 Compatibility with DEC Ada
479 * Ada 95 Compatibility::
480 * Differences in the Definition of Package System::
481 * Language-Related Features::
482 * The Package STANDARD::
483 * The Package SYSTEM::
484 * Tasking and Task-Related Features::
485 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
486 * Pragmas and Pragma-Related Features::
487 * Library of Predefined Units::
488 * Bindings::
489 * Main Program Definition::
490 * Implementation-Defined Attributes::
491 * Compiler and Run-Time Interfacing::
492 * Program Compilation and Library Management::
493 * Input-Output::
494 * Implementation Limits::
495 * Tools::
497 Language-Related Features
499 * Integer Types and Representations::
500 * Floating-Point Types and Representations::
501 * Pragmas Float_Representation and Long_Float::
502 * Fixed-Point Types and Representations::
503 * Record and Array Component Alignment::
504 * Address Clauses::
505 * Other Representation Clauses::
507 Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
509 * Assigning Task IDs::
510 * Task IDs and Delays::
511 * Task-Related Pragmas::
512 * Scheduling and Task Priority::
513 * The Task Stack::
514 * External Interrupts::
516 Pragmas and Pragma-Related Features
518 * Restrictions on the Pragma INLINE::
519 * Restrictions on the Pragma INTERFACE::
520 * Restrictions on the Pragma SYSTEM_NAME::
522 Library of Predefined Units
524 * Changes to DECLIB::
526 Bindings
528 * Shared Libraries and Options Files::
529 * Interfaces to C::
530 @end ifset
532 Running and Debugging Ada Programs
534 * The GNAT Debugger GDB::
535 * Running GDB::
536 * Introduction to GDB Commands::
537 * Using Ada Expressions::
538 * Calling User-Defined Subprograms::
539 * Using the Next Command in a Function::
540 * Ada Exceptions::
541 * Ada Tasks::
542 * Debugging Generic Units::
543 * GNAT Abnormal Termination or Failure to Terminate::
544 * Naming Conventions for GNAT Source Files::
545 * Getting Internal Debugging Information::
546 * Stack Traceback::
548 Inline Assembler
550 * Basic Assembler Syntax::
551 * A Simple Example of Inline Assembler::
552 * Output Variables in Inline Assembler::
553 * Input Variables in Inline Assembler::
554 * Inlining Inline Assembler Code::
555 * Other Asm Functionality::
556 * A Complete Example::
558 @ifset wnt
559 Microsoft Windows Topics
561 * Using GNAT on Windows::
562 * GNAT Setup Tool::
563 * CONSOLE and WINDOWS subsystems::
564 * Temporary Files::
565 * Mixed-Language Programming on Windows::
566 * Windows Calling Conventions::
567 * Introduction to Dynamic Link Libraries (DLLs)::
568 * Using DLLs with GNAT::
569 * Building DLLs with GNAT::
570 * GNAT and Windows Resources::
571 * GNAT and COM/DCOM Objects::
572 @end ifset
574 @ifset vxworks
575 VxWorks Topics
577 * Kernel Configuration for VxWorks::
578 * Kernel Compilation Issues for VxWorks::
579 * Handling Relocation Issues for PowerPc Targets::
580 * Support for Software Floating Point on PowerPC Processors::
581 * Interrupt Handling for VxWorks::
582 * Simulating Command Line Arguments for VxWorks::
583 * Debugging Issues for VxWorks::
584 * Using GNAT from the Tornado 2 Project Facility::
585 * Frequently Asked Questions for VxWorks::
587 LynxOS Topics
589 * Getting Started with GNAT on LynxOS::
590 * Kernel Configuration for LynxOS::
591 * Patch Level Issues for LynxOS::
592 * Debugging Issues for LynxOS::
593 * An Example Debugging Session for LynxOS::
594 @end ifset
596 Performance Considerations
598 * Controlling Run-Time Checks::
599 * Optimization Levels::
600 * Debugging Optimized Code::
601 * Inlining of Subprograms::
602 @ifset vms
603 * Coverage Analysis::
604 @end ifset
606 * Index::
607 @end menu
608 @end ifnottex
610 @node About This Guide
611 @unnumbered About This Guide
613 @noindent
614 @ifset vms
615 This guide describes the use of of GNAT, a full language compiler for the Ada
616 95 programming language, implemented on DIGITAL OpenVMS Alpha Systems.
617 @end ifset
618 @ifclear vms
619 This guide describes the use of GNAT, a compiler and software development
620 toolset for the full Ada 95 programming language.
621 @end ifclear
622 It describes the features of the compiler and tools, and details
623 how to use them to build Ada 95 applications.
625 @menu
626 * What This Guide Contains::
627 * What You Should Know before Reading This Guide::
628 * Related Information::
629 * Conventions::
630 @end menu
632 @node What This Guide Contains
633 @unnumberedsec What This Guide Contains
635 @noindent
636 This guide contains the following chapters:
637 @itemize @bullet
638 @ifset vxworks
639 @item
640 @ref{Preliminary Note for Cross Platform Users}, describes the basic
641 differences between the cross and native versions of GNAT.
642 @end ifset
643 @item
644 @ref{Getting Started with GNAT}, describes how to get started compiling
645 and running Ada programs with the GNAT Ada programming environment.
646 @item
647 @ref{The GNAT Compilation Model}, describes the compilation model used
648 by GNAT.
649 @item
650 @ref{Compiling Using gcc}, describes how to compile
651 Ada programs with @code{gcc}, the Ada compiler.
652 @item
653 @ref{Binding Using gnatbind}, describes how to
654 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
655 utility.
656 @item
657 @ref{Linking Using gnatlink},
658 describes @code{gnatlink}, a
659 program that provides for linking using the GNAT run-time library to
660 construct a program. @code{gnatlink} can also incorporate foreign language
661 object units into the executable.
662 @item
663 @ref{The GNAT Make Program gnatmake}, describes @code{gnatmake}, a
664 utility that automatically determines the set of sources
665 needed by an Ada compilation unit, and executes the necessary compilations
666 binding and link.
667 @item
668 @ref{Renaming Files Using gnatchop}, describes
669 @code{gnatchop}, a utility that allows you to preprocess a file that
670 contains Ada source code, and split it into one or more new files, one
671 for each compilation unit.
672 @item
673 @ref{Configuration Pragmas}, describes the configuration pragmas handled by GNAT.
674 @item
675 @ref{Handling Arbitrary File Naming Conventions Using gnatname}, shows how to override
676 the default GNAT file naming conventions, either for an individual unit or globally.
677 @item
678 @ref{GNAT Project Manager}, describes how to use project files to organize large projects.
679 @item
680 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps you deal with
681 elaboration order issues.
682 @item
683 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
684 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
685 way to navigate through sources.
686 @item
687 @ref{File Name Krunching Using gnatkr}, describes the @code{gnatkr}
688 file name krunching utility, used to handle shortened
689 file names on operating systems with a limit on the length of names.
690 @item
691 @ref{Preprocessing Using gnatprep}, describes @code{gnatprep}, a
692 preprocessor utility that allows a single source file to be used to
693 generate multiple or parameterized source files, by means of macro
694 substitution.
695 @item
696 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
697 utility that displays information about compiled units, including dependences
698 on the corresponding sources files, and consistency of compilations.
699 @ifclear vms
700 @item
701 @ref{GNAT and Libraries}, describes the process of creating and using
702 Libraries with GNAT. It also describes how to recompile the GNAT run-time
703 library.
705 @item
706 @ref{Using the GNU make Utility}, describes some techniques for using
707 the GNAT toolset in Makefiles.
709 @ifclear vxworks
710 @item
711 @ref{Finding Memory Problems with gnatmem}, describes @code{gnatmem}, a
712 utility that monitors dynamic allocation and deallocation activity in a
713 program, and displays information about incorrect deallocations and sources
714 of possible memory leaks.
715 @end ifclear
716 @end ifclear
717 @item
718 @ref{Finding Memory Problems with GNAT Debug Pool}, describes how to
719 use the GNAT-specific Debug Pool in order to detect as early as possible
720 the use of incorrect memory references.
722 @item
723 @ref{Creating Sample Bodies Using gnatstub}, discusses @code{gnatstub},
724 a utility that generates empty but compilable bodies for library units.
726 @item
727 @ref{Reducing the Size of Ada Executables with gnatelim}, describes
728 @code{gnatelim}, a tool which detects unused subprograms and helps
729 the compiler to create a smaller executable for the program.
731 @item
732 @ref{Other Utility Programs}, discusses several other GNAT utilities,
733 including @code{gnatpsta}.
735 @item
736 @ref{Running and Debugging Ada Programs}, describes how to run and debug
737 Ada programs.
739 @item
740 @ref{Inline Assembler}, shows how to use the inline assembly facility in an Ada program.
742 @ifset vxworks
743 @item
744 @ref{VxWorks Topics}, presents information relevant to the VxWorks target for cross-compilation
745 configurations.
747 @item
748 @ref{LynxOS Topics}, presents information relevant to the LynxOS target for cross-compilation
749 configurations.
750 @end ifset
752 @item
753 @ref{Performance Considerations}, reviews the trade offs between using
754 defaults or options in program development.
755 @ifset vms
756 @item
757 @ref{Compatibility with DEC Ada}, details the compatibility of GNAT with
758 DEC Ada 83 for OpenVMS Alpha.
759 @end ifset
760 @end itemize
762 @node What You Should Know before Reading This Guide
763 @unnumberedsec What You Should Know before Reading This Guide
765 @cindex Ada 95 Language Reference Manual
766 @noindent
767 This user's guide assumes that you are familiar with Ada 95 language, as
768 described in the International Standard ANSI/ISO/IEC-8652:1995, Jan
769 1995.
771 @node Related Information
772 @unnumberedsec Related Information
774 @noindent
775 For further information about related tools, refer to the following
776 documents:
778 @itemize @bullet
779 @item
780 @cite{GNAT Reference Manual}, which contains all reference
781 material for the GNAT implementation of Ada 95.
783 @item
784 @cite{Ada 95 Language Reference Manual}, which contains all reference
785 material for the Ada 95 programming language.
787 @item
788 @cite{Debugging with GDB}
789 @ifset vms
790 , located in the GNU:[DOCS] directory,
791 @end ifset
792 contains all details on the use of the GNU source-level debugger.
794 @item
795 @cite{GNU Emacs Manual}
796 @ifset vms
797 , located in the GNU:[DOCS] directory if the EMACS kit is installed,
798 @end ifset
799 contains full information on the extensible editor and programming
800 environment Emacs.
802 @end itemize
804 @node Conventions
805 @unnumberedsec Conventions
806 @cindex Conventions
807 @cindex Typographical conventions
809 @noindent
810 Following are examples of the typographical and graphic conventions used
811 in this guide:
813 @itemize @bullet
814 @item
815 @code{Functions}, @code{utility program names}, @code{standard names},
816 and @code{classes}.
818 @item
819 @samp{Option flags}
821 @item
822 @file{File Names}, @file{button names}, and @file{field names}.
824 @item
825 @var{Variables}.
827 @item
828 @emph{Emphasis}.
830 @item
831 [optional information or parameters]
833 @item
834 Examples are described by text
835 @smallexample
836 and then shown this way.
837 @end smallexample
838 @end itemize
840 @noindent
841 Commands that are entered by the user are preceded in this manual by the
842 characters @w{"@code{$ }"} (dollar sign followed by space). If your system
843 uses this sequence as a prompt, then the commands will appear exactly as
844 you see them in the manual. If your system uses some other prompt, then
845 the command will appear with the @code{$} replaced by whatever prompt
846 character you are using.
848 @ifset vxworks
849 @node Preliminary Note for Cross Platform Users
850 @chapter Preliminary Note for Cross Platform Users
852 @noindent
853 The use of GNAT in a cross environment is very similar to its use in a
854 native environment. Most of the tools described in this manual have
855 similar functions and options in both modes. The major
856 difference is that the name of the cross tools includes the target for
857 which the cross compiler is configured. For instance, the cross @command{gnatmake}
858 tool is called @command{@i{target}-gnatmake} where @code{@i{target}} stands for the name of
859 the cross target. Thus, in an environment configured for the
860 target @code{powerpc-wrs-vxworks}, the @command{gnatmake} command is
861 @code{powerpc-wrs-vxworks-gnatmake}. This convention allows the
862 installation of a native and one or several cross development
863 environments at the same location.
865 The tools that are most relevant in a cross environment are:
866 @code{@i{target}-gcc}, @code{@i{target}-gnatmake},
867 @code{@i{target}-gnatbind}, @code{@i{target}-gnatlink} to build cross
868 applications and @code{@i{target}-gnatls} for cross library
869 browsing. @code{@i{target}-gdb} is also usually available for cross
870 debugging in text mode. The graphical debugger interface
871 @code{gvd} is always a native tool but it can be configured to drive
872 the above mentioned cross debugger, thus allowing graphical cross debugging
873 sessions. Some other tools such as  @code{@i{target}-gnatchop},
874 @code{@i{target}-gnatkr}, @code{@i{target}-gnatprep},
875 @code{@i{target}-gnatpsta}, @code{@i{target}-gnatxref}, @code{@i{target}-gnatfind}
876 and @code{@i{target}-gnatname} are also provided for completeness
877 even though they do not differ greatly from their native counterpart.
879 In the rest of this manual, the tools are sometimes designated with
880 their full cross name, and sometimes with their simplified native
881 name.
883 @end ifset
885 @node Getting Started with GNAT
886 @chapter Getting Started with GNAT
888 @ifclear vxworks
889 @noindent
890 This chapter describes some simple ways of using GNAT to build
891 executable Ada programs.
892 @end ifclear
893 @ifset vxworks
894 @noindent
895 This introduction is a starting point for using GNAT to develop
896 and execute Ada 95 programs in a cross environment.
897 It provides some specifics
898 about the GNAT toolchain targeted to the Wind River Sytems' VxWorks/Tornado platform;
899 for other targets please refer to the corresponding chapter later in this manual.
901 Basic familiarity with use of GNAT in a native environment is
902 presumed. For the VxWorks specific part, a knowledge of how to start
903 Tornado's @code{windsh} tool is also presumed.
904 @end ifset
906 @menu
907 * Running GNAT::
908 @ifclear vxworks
909 * Running a Simple Ada Program::
910 @end ifclear
911 @ifset vxworks
912 * Building a Simple Ada Program::
913 * Executing a Program on VxWorks::
914 @end ifset
916 * Running a Program with Multiple Units::
918 * Using the gnatmake Utility::
919 @ifset vms
920 * Editing with Emacs::
921 @end ifset
922 @ifclear vms
923 * Introduction to Glide and GVD::
924 @end ifclear
925 @end menu
927 @node Running GNAT
928 @section Running GNAT
930 @noindent
931 Three steps are needed to create an executable file from an Ada source
932 file:
934 @enumerate
935 @item
936 The source file(s) must be compiled.
937 @item
938 The file(s) must be bound using the GNAT binder.
939 @item
940 @ifclear vxworks
941 All appropriate object files must be linked to produce an executable.
942 @end ifclear
943 @ifset vxworks
944 All appropriate object files must be linked to produce a loadable module.
945 @end ifset
946 @end enumerate
948 @noindent
949 All three steps are most commonly handled by using the @code{gnatmake}
950 utility program that, given the name of the main program, automatically
951 performs the necessary compilation, binding and linking steps.
953 @ifclear vxworks
954 @node Running a Simple Ada Program
955 @section Running a Simple Ada Program
956 @end ifclear
957 @ifset vxworks
958 @node Building a Simple Ada Program
959 @section Building a Simple Ada Program
960 @end ifset
962 @noindent
963 Any text editor may be used to prepare an Ada program. If @code{Glide} is
964 used, the optional Ada mode may be helpful in laying out the program. The
965 program text is a normal text file. We will suppose in our initial
966 example that you have used your editor to prepare the following
967 standard format text file:
969 @smallexample
970 @group
971 @cartouche
972 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
973 @b{procedure} Hello @b{is}
974 @b{begin}
975    Put_Line ("Hello WORLD!");
976 @b{end} Hello;
977 @end cartouche
978 @end group
979 @end smallexample
981 @noindent
982 This file should be named @file{hello.adb}.
983 With the normal default file naming conventions, GNAT requires
984 that each file
985 contain a single compilation unit whose file name is the
986 unit name,
987 with periods replaced by hyphens; the
988 extension is @file{ads} for a
989 spec and @file{adb} for a body.
990 You can override this default file naming convention by use of the
991 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
992 Alternatively, if you want to rename your files according to this default
993 convention, which is probably more convenient if you will be using GNAT
994 for all your compilations, then the @code{gnatchop} utility
995 can be used to generate correctly-named source files
996 (@pxref{Renaming Files Using gnatchop}).
998 You can compile the program using the following command (@code{$} is used
999 as the command prompt in the examples in this document):
1001 @ifclear vxworks
1002 @smallexample
1003 $ gcc -c hello.adb
1004 @end smallexample
1005 @end ifclear
1007 @ifset vxworks
1008 @smallexample
1009 $ @i{target}-gcc -c hello.adb
1010 @end smallexample
1011 @end ifset
1013 @noindent
1014 @code{gcc} is the command used to run the compiler. This compiler is
1015 capable of compiling programs in several languages, including Ada 95 and
1016 C. It assumes that you have given it an Ada program if the file extension is
1017 either @file{.ads} or @file{.adb}, and it will then call the GNAT compiler to compile
1018 the specified file.
1020 @ifclear vms
1021 The @option{-c} switch is required. It tells @command{gcc} to only do a
1022 compilation. (For C programs, @command{gcc} can also do linking, but this
1023 capability is not used directly for Ada programs, so the @option{-c}
1024 switch must always be present.)
1025 @end ifclear
1027 This compile command generates a file
1028 @file{hello.o}, which is the object
1029 file corresponding to your Ada program. It also generates an "Ada Library Information" file
1030 @file{hello.ali},
1031 which contains additional information used to check
1032 that an Ada program is consistent.
1033 @ifclear vxworks
1034 To build an executable file,
1035 @end ifclear
1036 @ifset vxworks
1037 To build a downloadable module,
1038 @end ifset
1039 use @code{gnatbind} to bind the program
1040 and @code{gnatlink} to link it. The
1041 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1042 @file{ali} file, but the default extension of @file{.ali} can
1043 be omitted. This means that in the most common case, the argument
1044 is simply the name of the main program:
1046 @ifclear vxworks
1047 @smallexample
1048 $ gnatbind hello
1049 $ gnatlink hello
1050 @end smallexample
1051 @end ifclear
1053 @ifset vxworks
1054 @smallexample
1055 $ @i{target}-gnatbind hello
1056 $ @i{target}-gnatlink hello
1057 @end smallexample
1058 @end ifset
1060 @noindent
1061 A simpler method of carrying out these steps is to use
1062 @command{gnatmake},
1063 a master program that invokes all the required
1064 compilation, binding and linking tools in the correct order. In particular,
1065 @command{gnatmake} automatically recompiles any sources that have been modified
1066 since they were last compiled, or sources that depend
1067 on such modified sources, so that "version skew" is avoided.
1068 @cindex Version skew (avoided by @command{gnatmake})
1070 @ifclear vxworks
1071 @smallexample
1072 $ gnatmake hello.adb
1073 @end smallexample
1074 @end ifclear
1076 @ifset vxworks
1077 @smallexample
1078 $ @i{target}-gnatmake hello.adb
1079 @end smallexample
1080 @end ifset
1082 @ifclear vxworks
1083 @noindent
1084 The result is an executable program called @file{hello}, which can be
1085 run by entering:
1087 @c The following should be removed (BMB 2001-01-23)
1088 @c @smallexample
1089 @c $ ^./hello^$ RUN HELLO^
1090 @c @end smallexample
1092 @smallexample
1093 $ hello
1094 @end smallexample
1096 @noindent
1097 assuming that the current directory is on the search path for executable programs.
1099 @noindent
1100 and, if all has gone well, you will see
1102 @smallexample
1103 Hello WORLD!
1104 @end smallexample
1106 @noindent
1107 appear in response to this command.
1109 @end ifclear
1111 @ifset vxworks
1112 @noindent
1113 The result is a relocatable object called @file{hello}.
1115 @emph{Technical note:} the result of the linking stage is a
1116 relocatable partially-linked object containing all the relevant GNAT
1117 run-time units, in contrast with the executable-format object file found in
1118 native environments.
1121 @node Executing a Program on VxWorks
1122 @section Executing a Program on VxWorks
1124 @noindent
1125 Getting a program to execute involves loading it onto the target, running it, and then (if re-execution is needed) unloading it.
1127 @menu
1128 * Loading and Running the Program::
1129 * Unloading the Program::
1130 @end menu
1132 @node Loading and Running the Program
1133 @subsection Loading and Running the Program
1135 @noindent
1136 An Ada program is loaded and run in the same way as a C program.
1137 Details may be found in the @cite{Tornado User's Guide}.
1139 In order to load and run our simple "Hello World" example, we assume that
1140 the target has access to the disk of the host containing this object and
1141 that its working directory has been set to the directory containing this
1142 object. The commands are typed in Tornado's Windshell. The @code{windsh} prompt
1143 is the @code{->} sequence.
1145 @smallexample
1146 -> vf0=open("/vio/0",2,0)
1147 new symbol "vf0" added to symbol table.
1148 vf0 = 0x2cab48: value = 12 = 0xc
1149 -> ioGlobalStdSet(1,vf0)
1150 value = 1 = 0x1
1151 -> ld < hello
1152 value = 665408 = 0xa2740
1153 -> hello
1154 Hello World
1155 value = 0 = 0x0
1157 @end smallexample
1159 @noindent
1160 The first two commands redirect output to the shell window.
1161 They are only needed if the target server was started without the
1162 @code{-C} option.  The third command loads the module, which is the file
1163 @file{hello} created previously by the @code{@i{target}-gnatmake} command.
1164 Note that for Tornado AE, the @command{ml} command replaces @command{ld}."
1166 The "Hello World" program comprises a procedure named @code{hello}, and this
1167 is the name entered for the procedure in the target server's symbol table
1168 when the module is loaded.  To execute the procedure, type the symbol name @code{hello}
1169 into @code{windsh} as shown in the last command above.
1171 Note that by default the entry point of an Ada program is the name of the main
1172 Ada subprogram in a VxWorks environment. It is possible to use an alternative
1173 name; see the description of @code{gnatbind} options for details.
1175 @node Unloading the Program
1176 @subsection Unloading the Program
1178 @noindent
1179 It is important to remember that
1180 you must unload a program once you have run it. You
1181 cannot load it once and run it several times. If you don't follow
1182 this rule, your program's behavior can be unpredictable, and will most
1183 probably crash.
1185 This effect is due to the implementation of Ada 95's @emph{elaboration} semantics.
1186 The unit elaboration phase comprises a @emph{static} elaboration and a
1187 @emph{dynamic} elaboration. On a native platform they both take place
1188 when the program is run. Thus rerunning the program will repeat the complete
1189 elaboration phase, and the program will run correctly.
1191 On VxWorks, the process is a bit different.
1192 The static elaboration phase is handled by
1193 the loader (typically when you type @code{ld < program_name} in
1194 @code{windsh}). The dynamic phase takes place when the program is run. If the
1195 program is run twice and has not been unloaded and then reloaded, the
1196 second time it is run, the static elaboration phase is skipped.
1197 Variables initialized during the static elaboration phase
1198 may have been modified during the first execution of the program. Thus the
1199 second execution isn't performed on a completely initialized environment.
1201 Note that in C programs, elaboration isn't systematic. Multiple runs without reload
1202 might work, but, even with C programs, if there is an elaboration
1203 phase, you will have to unload your program before re-running it.
1204 @end ifset
1207 @node Running a Program with Multiple Units
1208 @section Running a Program with Multiple Units
1210 @noindent
1211 Consider a slightly more complicated example that has three files: a
1212 main program, and the spec and body of a package:
1214 @smallexample
1215 @cartouche
1216 @group
1217 @b{package} Greetings @b{is}
1218    @b{procedure} Hello;
1219    @b{procedure} Goodbye;
1220 @b{end} Greetings;
1222 @b{with} Ada.Text_IO; @b{use} Ada.Text_IO;
1223 @b{package} @b{body} Greetings @b{is}
1224    @b{procedure} Hello @b{is}
1225    @b{begin}
1226       Put_Line ("Hello WORLD!");
1227    @b{end} Hello;
1229    @b{procedure} Goodbye @b{is}
1230    @b{begin}
1231       Put_Line ("Goodbye WORLD!");
1232    @b{end} Goodbye;
1233 @b{end} Greetings;
1234 @end group
1236 @group
1237 @b{with} Greetings;
1238 @b{procedure} Gmain @b{is}
1239 @b{begin}
1240    Greetings.Hello;
1241    Greetings.Goodbye;
1242 @b{end} Gmain;
1243 @end group
1244 @end cartouche
1245 @end smallexample
1247 @noindent
1248 Following the one-unit-per-file rule, place this program in the
1249 following three separate files:
1251 @table @file
1252 @item greetings.ads
1253 spec of package @code{Greetings}
1255 @item greetings.adb
1256 body of package @code{Greetings}
1258 @item gmain.adb
1259 body of main program
1260 @end table
1262 @noindent
1263 To build an executable version of
1264 this program, we could use four separate steps to compile, bind, and link
1265 the program, as follows:
1267 @ifclear vxworks
1268 @smallexample
1269 $ gcc -c gmain.adb
1270 $ gcc -c greetings.adb
1271 $ gnatbind gmain
1272 $ gnatlink gmain
1273 @end smallexample
1274 @end ifclear
1276 @ifset vxworks
1277 @smallexample
1278 $ @i{target}-gcc -c gmain.adb
1279 $ @i{target}-gcc -c greetings.adb
1280 $ @i{target}-gnatbind gmain
1281 $ @i{target}-gnatlink gmain
1282 @end smallexample
1283 @end ifset
1285 @noindent
1286 Note that there is no required order of compilation when using GNAT.
1287 In particular it is perfectly fine to compile the main program first.
1288 Also, it is not necessary to compile package specs in the case where
1289 there is an accompanying body; you only need to compile the body. If you want
1290 to submit these files to the compiler for semantic checking and not code generation,
1291 then use the
1292 @option{-gnatc} switch:
1294 @ifclear vxworks
1295 @smallexample
1296    $ gcc -c greetings.ads -gnatc
1297 @end smallexample
1298 @end ifclear
1300 @ifset vxworks
1301 @smallexample
1302 $ @i{target}-gcc -c greetings.ads -gnatc
1303 @end smallexample
1304 @end ifset
1306 @noindent
1307 Although the compilation can be done in separate steps as in the
1308 above example, in practice it is almost always more convenient
1309 to use the @code{gnatmake} tool. All you need to know in this case
1310 is the name of the main program's source file. The effect of the above four
1311 commands can be achieved with a single one:
1313 @ifclear vxworks
1314 @smallexample
1315 $ gnatmake gmain.adb
1316 @end smallexample
1317 @end ifclear
1319 @ifset vxworks
1320 @smallexample
1321 $ @i{target}-gnatmake gmain.adb
1322 @end smallexample
1323 @end ifset
1325 @noindent
1326 In the next section we discuss the advantages of using @code{gnatmake} in
1327 more detail.
1329 @node Using the gnatmake Utility
1330 @section Using the @command{gnatmake} Utility
1332 @noindent
1333 If you work on a program by compiling single components at a time using
1334 @code{gcc}, you typically keep track of the units you modify. In order to
1335 build a consistent system, you compile not only these units, but also any
1336 units that depend on the units you have modified.
1337 For example, in the preceding case,
1338 if you edit @file{gmain.adb}, you only need to recompile that file. But if
1339 you edit @file{greetings.ads}, you must recompile both
1340 @file{greetings.adb} and @file{gmain.adb}, because both files contain
1341 units that depend on @file{greetings.ads}.
1343 @code{gnatbind} will warn you if you forget one of these compilation
1344 steps, so that it is impossible to generate an inconsistent program as a
1345 result of forgetting to do a compilation. Nevertheless it is tedious and
1346 error-prone to keep track of dependencies among units.
1347 One approach to handle the dependency-bookkeeping is to use a
1348 makefile. However, makefiles present maintenance problems of their own:
1349 if the dependencies change as you change the program, you must make
1350 sure that the makefile is kept up-to-date manually, which is also an
1351 error-prone process.
1353 The @code{gnatmake} utility takes care of these details automatically.
1354 Invoke it using either one of the following forms:
1356 @ifclear vxworks
1357 @smallexample
1358 $ gnatmake gmain.adb
1359 $ gnatmake ^gmain^GMAIN^
1360 @end smallexample
1361 @end ifclear
1363 @ifset vxworks
1364 @smallexample
1365 $ @i{target}-gnatmake gmain.adb
1366 $ @i{target}-gnatmake gmain
1367 @end smallexample
1368 @end ifset
1370 @noindent
1371 The argument is the name of the file containing the main program;
1372 you may omit the extension. @code{gnatmake}
1373 examines the environment, automatically recompiles any files that need
1374 recompiling, and binds and links the resulting set of object files,
1375 generating the executable file, @file{^gmain^GMAIN.EXE^}.
1376 In a large program, it
1377 can be extremely helpful to use @code{gnatmake}, because working out by hand
1378 what needs to be recompiled can be difficult.
1380 Note that @code{gnatmake}
1381 takes into account all the Ada 95 rules that
1382 establish dependencies among units. These include dependencies that result
1383 from inlining subprogram bodies, and from
1384 generic instantiation. Unlike some other
1385 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1386 found by the compiler on a previous compilation, which may possibly
1387 be wrong when sources change. @code{gnatmake} determines the exact set of
1388 dependencies from scratch each time it is run.
1390 @ifset vms
1391 @node Editing with Emacs
1392 @section Editing with Emacs
1393 @cindex Emacs
1395 @noindent
1396 Emacs is an extensible self-documenting text editor that is available in a
1397 separate VMSINSTAL kit.
1399 Invoke Emacs by typing "Emacs" at the command prompt. To get started,
1400 click on the Emacs Help menu and run the Emacs Tutorial.
1401 In a character cell terminal, Emacs help is invoked with "Ctrl-h" (also written
1402 as "C-h"), and the tutorial by "C-h t".
1404 Documentation on Emacs and other tools is available in Emacs under the
1405 pull-down menu button: Help - Info. After selecting Info, use the middle
1406 mouse button to select a topic (e.g. Emacs).
1408 In a character cell terminal, do "C-h i" to invoke info, and then "m"
1409 (stands for menu) followed by the menu item desired, as in "m Emacs", to get
1410 to the Emacs manual.
1411 Help on Emacs is also available by typing "HELP EMACS" at the DCL command
1412 prompt.
1414 The tutorial is highly recommended in order to learn the intricacies of Emacs,
1415 which is sufficiently extensible to provide for a complete programming
1416 environment and shell for the sophisticated user.
1417 @end ifset
1419 @ifclear vms
1420 @node Introduction to Glide and GVD
1421 @section Introduction to Glide and GVD
1422 @cindex Glide
1423 @cindex GVD
1424 @noindent
1425 Although it is possible to develop programs using only the command line interface (@command{gnatmake}, etc.) a graphical Interactive Development Environment can make it easier for you to compose, navigate, and debug programs.  This section describes the main features of Glide, the GNAT graphical IDE, and also shows how to use the basic commands in GVD, the GNU Visual Debugger.  Additional information may be found in the on-line help for these tools.
1427 @menu
1428 * Building a New Program with Glide::
1429 * Simple Debugging with GVD::
1430 * Other Glide Features::
1431 @end menu
1433 @node Building a New Program with Glide
1434 @subsection Building a New Program with Glide
1435 @noindent
1436 The simplest way to invoke Glide is to enter @command{glide} at the command prompt.  It will generally be useful to issue this as a background command, thus allowing you to continue using your command window for other purposes while Glide is running:
1438 @smallexample
1439 $ glide&
1440 @end smallexample
1442 @noindent
1443 Glide will start up with an initial screen displaying the top-level menu items as well as some other information.  The menu selections are as follows
1444 @itemize @bullet
1445 @item @code{Buffers}
1446 @item @code{Files}
1447 @item @code{Tools}
1448 @item @code{Edit}
1449 @item @code{Search}
1450 @item @code{Mule}
1451 @item @code{Glide}
1452 @item @code{Help}
1453 @end itemize
1455 @noindent
1456 For this introductory example, you will need to create a new Ada source file.  First, select the @code{Files} menu.  This will pop open a menu with around a dozen or so items.  To create a file, select the @code{Open file...} choice.  Depending on the platform, you may see a pop-up window where you can browse to an appropriate directory and then enter the file name, or else simply see a line at the bottom of the Glide window where you can likewise enter the file name.  Note that in Glide, when you attempt to open a non-existent file, the effect is to create a file with that name.  For this example enter @file{hello.adb} as the name of the file.
1458 A new buffer will now appear, occupying the entire Glide window, with the file name at the top.  The menu selections are slightly different from the ones you saw on the opening screen; there is an @code{Entities} item, and in place of @code{Glide} there is now an @code{Ada} item.  Glide uses the file extension to identify the source language, so @file{adb} indicates an Ada source file.
1460 You will enter some of the source program lines explicitly, and use the syntax-oriented template mechanism to enter other lines.  First, type the following text:
1461 @smallexample
1462 with Ada.Text_IO; use Ada.Text_IO;
1463 procedure Hello is
1464 begin
1465 @end smallexample
1467 @noindent
1468 Observe that Glide uses different colors to distinguish reserved words from identifiers.  Also, after the @code{procedure Hello is} line, the cursor is automatically indented in anticipation of declarations.  When you enter @code{begin}, Glide recognizes that there are no declarations and thus places @code{begin} flush left.  But after the @code{begin} line the cursor is again indented, where the statement(s) will be placed.
1470 The main part of the program will be a @code{for} loop.  Instead of entering the text explicitly, however, use a statement template.  Select the @code{Ada} item on the top menu bar, move the mouse to the @code{Statements} item, and you will see a large selection of alternatives.  Choose @code{for loop}.  You will be prompted (at the bottom of the buffer) for a loop name; simply press the @key{Enter} key since a loop name is not needed.  You should see the beginning of a @code{for} loop appear in the source program window.  You will now be prompted for the name of the loop variable; enter a line with the identifier @code{ind} (lower case).  Note that, by default, Glide capitalizes the name (you can override such behavior if you wish, although this is outside the scope of this introduction).  Next, Glide prompts you for the loop range; enter a line containing @code{1..5} and you will see this also appear in the source program, together with the remaining elements of the @code{for} loop syntax.
1472 Next enter the statement (with an intentional error, a missing semicolon) that will form the body of the loop:
1473 @smallexample
1474 Put_Line("Hello, World" & Integer'Image(I))
1475 @end smallexample
1477 @noindent
1478 Finally, type @code{end Hello;} as the last line in the program.  Now save the file: choose the @code{File} menu item, and then the @code{Save buffer} selection.  You will see a message at the bottom of the buffer confirming that the file has been saved.
1480 You are now ready to attempt to build the program.  Select the @code{Ada} item from the top menu bar.  Although we could choose simply to compile the file, we will instead attempt to do a build (which invokes @command{gnatmake}) since, if the compile is successful, we want to build an executable.  Thus select @code{Ada build}.  This will fail because of the compilation error, and you will notice that the Glide window has been split: the top window contains the source file, and the bottom window contains the output from the GNAT tools.  Glide allows you to navigate from a compilation error to the source file position corresponding to the error: click the middle mouse button (or simultaneously press the left and right buttons, on a two-button mouse) on the diagnostic line in the tool window.  The focus will shift to the source window, and the cursor will be positioned on the character at which the error was detected.
1482 Correct the error: type in a semicolon to terminate the statement.  Although you can again save the file explicitly, you can also simply invoke @code{Ada} @result{} @code{Build} and you will be prompted to save the file.  This time the build will succeed; the tool output window shows you the options that are supplied by default.  The GNAT tools' output (e.g., object and ALI files, executable) will go in the directory from which Glide was launched.
1484 To execute the program, choose @code{Ada} and then @code{Run}.  You should see the program's output displayed in the bottom window:
1486 @smallexample
1487 Hello, world 1
1488 Hello, world 2
1489 Hello, world 3
1490 Hello, world 4
1491 Hello, world 5
1492 @end smallexample
1494 @node Simple Debugging with GVD
1495 @subsection Simple Debugging with GVD
1497 @noindent
1498 This section describes how to set breakpoints, examine/modify variables, and step through execution.
1500 In order to enable debugging, you need to pass the @option{-g} switch to both the compiler and to @command{gnatlink}.  If you are using the command line, passing @option{-g} to @command{gnatmake} will have this effect.  You can then launch GVD, e.g. on the @code{hello} program, by issuing the command:
1502 @smallexample
1503 $ gvd hello
1504 @end smallexample
1506 @noindent
1507 If you are using Glide, then @option{-g} is passed to the relevant tools by default when you do a build.  Start the debugger by selecting the @code{Ada} menu item, and then @code{Debug}.
1509 GVD comes up in a multi-part window.  One pane shows the names of files comprising your executable; another pane shows the source code of the current unit (initially your main subprogram), another pane shows the debugger output and user interactions, and the fourth pane (the data canvas at the top of the window) displays data objects that you have selected.
1511 To the left of the source file pane, you will notice green dots adjacent to some lines.  These are lines for which object code exists and where breakpoints can thus be set.  You set/reset a breakpoint by clicking the green dot.  When a breakpoint is set, the dot is replaced by an @code{X} in a red circle.  Clicking the circle toggles the breakpoint off, and the red circle is replaced by the green dot.
1513 For this example, set a breakpoint at the statement where @code{Put_Line} is invoked.
1515 Start program execution by selecting the @code{Run} button on the top menu bar.  (The @code{Start} button will also start your program, but it will cause program execution to break at the entry to your main subprogram.)  Evidence of reaching the breakpoint will appear: the source file line will be highlighted, and the debugger interactions pane will display a relevant message.
1517 You can examine the values of variables in several ways.  Move the mouse over an occurrence of @code{Ind} in the @code{for} loop, and you will see the value (now @code{1}) displayed.  Alternatively, right-click on @code{Ind} and select @code{Display Ind}; a box showing the variable's name and value will appear in the data canvas.
1519 Although a loop index is a constant with respect to Ada semantics, you can change its value in the debugger.  Right-click in the box for @code{Ind}, and select the @code{Set Value of Ind} item.  Enter @code{2} as the new value, and press @command{OK}.  The box for @code{Ind} shows the update.
1521 Press the @code{Step} button on the top menu bar; this will step through one line of program text (the invocation of @code{Put_Line}), and you can observe the effect of having modified @code{Ind} since the value displayed is @code{2}.
1523 Remove the breakpoint, and resume execution by selecting the @code{Cont} button.  You will see the remaining output lines displayed in the debugger interaction window, along with a message confirming normal program termination.
1526 @node Other Glide Features
1527 @subsection Other Glide Features
1529 @noindent
1530 You may have observed that some of the menu selections contain abbreviations; e.g., @code{(C-x C-f)} for @code{Open file...} in the @code{Files} menu.  These are @emph{shortcut keys} that you can use instead of selecting menu items.  The @key{C} stands for @key{Ctrl}; thus @code{(C-x C-f)} means @key{Ctrl-x} followed by @key{Ctrl-f}, and this sequence can be used instead of selecting @code{Files} and then @code{Open file...}.
1532 To abort a Glide command, type @key{Ctrl-g}.
1534 If you want Glide to start with an existing source file, you can either launch Glide as above and then open the file via @code{Files} @result{} @code{Open file...}, or else simply pass the name of the source file on the command line:
1536 @smallexample
1537 $ glide hello.adb&
1538 @end smallexample
1540 @noindent
1541 While you are using Glide, a number of @emph{buffers} exist.  You create some explicitly; e.g., when you open/create a file.  Others arise as an effect of the commands that you issue; e.g., the buffer containing the output of the tools invoked during a build.  If a buffer is hidden, you can bring it into a visible window by first opening the @code{Buffers} menu and then selecting the desired entry.
1543 If a buffer occupies only part of the Glide screen and you want to expand it to fill the entire screen, then click in the buffer and then select @code{Files} @result{} @code{One Window}.
1545 If a window is occupied by one buffer and you want to split the window to bring up a second buffer, perform the following steps:
1546 @itemize @bullet
1547 @item Select @code{Files} @result{} @code{Split Window}; this will produce two windows each of which holds the original buffer (these are not copies, but rather different views of the same buffer contents)
1548 @item With the focus in one of the windows, select the desired buffer from the @code{Buffers} menu
1549 @end itemize
1551 @noindent
1552 To exit from Glide, choose @code{Files} @result{} @code{Exit}.
1553 @end ifclear
1555 @node The GNAT Compilation Model
1556 @chapter The GNAT Compilation Model
1557 @cindex GNAT compilation model
1558 @cindex Compilation model
1560 @menu
1561 * Source Representation::
1562 * Foreign Language Representation::
1563 * File Naming Rules::
1564 * Using Other File Names::
1565 * Alternative File Naming Schemes::
1566 * Generating Object Files::
1567 * Source Dependencies::
1568 * The Ada Library Information Files::
1569 * Binding an Ada Program::
1570 * Mixed Language Programming::
1571 * Building Mixed Ada & C++ Programs::
1572 * Comparison between GNAT and C/C++ Compilation Models::
1573 * Comparison between GNAT and Conventional Ada Library Models::
1574 @end menu
1576 @noindent
1577 This chapter describes the compilation model used by GNAT. Although
1578 similar to that used by other languages, such as C and C++, this model
1579 is substantially different from the traditional Ada compilation models,
1580 which are based on a library. The model is initially described without
1581 reference to the library-based model. If you have not previously used an
1582 Ada compiler, you need only read the first part of this chapter. The
1583 last section describes and discusses the differences between the GNAT
1584 model and the traditional Ada compiler models. If you have used other
1585 Ada compilers, this section will help you to understand those
1586 differences, and the advantages of the GNAT model.
1588 @node Source Representation
1589 @section Source Representation
1590 @cindex Latin-1
1592 @noindent
1593 Ada source programs are represented in standard text files, using
1594 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1595 7-bit ASCII set, plus additional characters used for
1596 representing foreign languages (@pxref{Foreign Language Representation}
1597 for support of non-USA character sets). The format effector characters
1598 are represented using their standard ASCII encodings, as follows:
1600 @table @code
1601 @item VT
1602 @findex VT
1603 Vertical tab, @code{16#0B#}
1605 @item HT
1606 @findex HT
1607 Horizontal tab, @code{16#09#}
1609 @item CR
1610 @findex CR
1611 Carriage return, @code{16#0D#}
1613 @item LF
1614 @findex LF
1615 Line feed, @code{16#0A#}
1617 @item FF
1618 @findex FF
1619 Form feed, @code{16#0C#}
1620 @end table
1622 @noindent
1623 Source files are in standard text file format. In addition, GNAT will
1624 recognize a wide variety of stream formats, in which the end of physical
1625 physical lines is marked by any of the following sequences:
1626 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1627 in accommodating files that are imported from other operating systems.
1629 @cindex End of source file
1630 @cindex Source file, end
1631 @findex SUB
1632 The end of a source file is normally represented by the physical end of
1633 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1634 recognized as signalling the end of the source file. Again, this is
1635 provided for compatibility with other operating systems where this
1636 code is used to represent the end of file.
1638 Each file contains a single Ada compilation unit, including any pragmas
1639 associated with the unit. For example, this means you must place a
1640 package declaration (a package @dfn{spec}) and the corresponding body in
1641 separate files. An Ada @dfn{compilation} (which is a sequence of
1642 compilation units) is represented using a sequence of files. Similarly,
1643 you will place each subunit or child unit in a separate file.
1645 @node Foreign Language Representation
1646 @section Foreign Language Representation
1648 @noindent
1649 GNAT supports the standard character sets defined in Ada 95 as well as
1650 several other non-standard character sets for use in localized versions
1651 of the compiler (@pxref{Character Set Control}).
1652 @menu
1653 * Latin-1::
1654 * Other 8-Bit Codes::
1655 * Wide Character Encodings::
1656 @end menu
1658 @node Latin-1
1659 @subsection Latin-1
1660 @cindex Latin-1
1662 @noindent
1663 The basic character set is Latin-1. This character set is defined by ISO
1664 standard 8859, part 1. The lower half (character codes @code{16#00#}
1665 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper half is
1666 used to represent additional characters. These include extended letters
1667 used by European languages, such as French accents, the vowels with umlauts
1668 used in German, and the extra letter A-ring used in Swedish.
1670 @findex Ada.Characters.Latin_1
1671 For a complete list of Latin-1 codes and their encodings, see the source
1672 file of library unit @code{Ada.Characters.Latin_1} in file
1673 @file{a-chlat1.ads}.
1674 You may use any of these extended characters freely in character or
1675 string literals. In addition, the extended characters that represent
1676 letters can be used in identifiers.
1678 @node Other 8-Bit Codes
1679 @subsection Other 8-Bit Codes
1681 @noindent
1682 GNAT also supports several other 8-bit coding schemes:
1684 @table @asis
1685 @cindex Latin-2
1686 @item Latin-2
1687 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1688 equivalence.
1690 @item Latin-3
1691 @cindex Latin-3
1692 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1693 equivalence.
1695 @item Latin-4
1696 @cindex Latin-4
1697 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1698 equivalence.
1700 @item Latin-5
1701 @cindex Latin-5
1702 @cindex Cyrillic
1703 Latin-4 letters (Cyrillic) allowed in identifiers, with uppercase and lowercase
1704 equivalence.
1706 @item IBM PC (code page 437)
1707 @cindex code page 437
1708 This code page is the normal default for PCs in the U.S. It corresponds
1709 to the original IBM PC character set. This set has some, but not all, of
1710 the extended Latin-1 letters, but these letters do not have the same
1711 encoding as Latin-1. In this mode, these letters are allowed in
1712 identifiers with uppercase and lowercase equivalence.
1714 @item IBM PC (code page 850)
1715 @cindex code page 850
1716 This code page is a modification of 437 extended to include all the
1717 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1718 mode, all these letters are allowed in identifiers with uppercase and
1719 lowercase equivalence.
1721 @item Full Upper 8-bit
1722 Any character in the range 80-FF allowed in identifiers, and all are
1723 considered distinct. In other words, there are no uppercase and lowercase
1724 equivalences in this range. This is useful in conjunction with
1725 certain encoding schemes used for some foreign character sets (e.g.
1726 the typical method of representing Chinese characters on the PC).
1728 @item No Upper-Half
1729 No upper-half characters in the range 80-FF are allowed in identifiers.
1730 This gives Ada 83 compatibility for identifier names.
1731 @end table
1733 @noindent
1734 For precise data on the encodings permitted, and the uppercase and lowercase
1735 equivalences that are recognized, see the file @file{csets.adb} in
1736 the GNAT compiler sources. You will need to obtain a full source release
1737 of GNAT to obtain this file.
1739 @node Wide Character Encodings
1740 @subsection Wide Character Encodings
1742 @noindent
1743 GNAT allows wide character codes to appear in character and string
1744 literals, and also optionally in identifiers, by means of the following
1745 possible encoding schemes:
1747 @table @asis
1749 @item Hex Coding
1750 In this encoding, a wide character is represented by the following five
1751 character sequence:
1753 @smallexample
1754 ESC a b c d
1755 @end smallexample
1757 @noindent
1758 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1759 characters (using uppercase letters) of the wide character code. For
1760 example, ESC A345 is used to represent the wide character with code
1761 @code{16#A345#}.
1762 This scheme is compatible with use of the full Wide_Character set.
1764 @item Upper-Half Coding
1765 @cindex Upper-Half Coding
1766 The wide character with encoding @code{16#abcd#} where the upper bit is on (in
1767 other words, "a" is in the range 8-F) is represented as two bytes,
1768 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1769 character, but is not required to be in the upper half. This method can
1770 be also used for shift-JIS or EUC, where the internal coding matches the
1771 external coding.
1773 @item Shift JIS Coding
1774 @cindex Shift JIS Coding
1775 A wide character is represented by a two-character sequence,
1776 @code{16#ab#} and
1777 @code{16#cd#}, with the restrictions described for upper-half encoding as
1778 described above. The internal character code is the corresponding JIS
1779 character according to the standard algorithm for Shift-JIS
1780 conversion. Only characters defined in the JIS code set table can be
1781 used with this encoding method.
1783 @item EUC Coding
1784 @cindex EUC Coding
1785 A wide character is represented by a two-character sequence
1786 @code{16#ab#} and
1787 @code{16#cd#}, with both characters being in the upper half. The internal
1788 character code is the corresponding JIS character according to the EUC
1789 encoding algorithm. Only characters defined in the JIS code set table
1790 can be used with this encoding method.
1792 @item UTF-8 Coding
1793 A wide character is represented using
1794 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1795 10646-1/Am.2. Depending on the character value, the representation
1796 is a one, two, or three byte sequence:
1797 @smallexample
1798 @iftex
1799 @leftskip=.7cm
1800 @end iftex
1801 16#0000#-16#007f#: 2#0xxxxxxx#
1802 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1803 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1805 @end smallexample
1807 @noindent
1808 where the xxx bits correspond to the left-padded bits of the
1809 16-bit character value. Note that all lower half ASCII characters
1810 are represented as ASCII bytes and all upper half characters and
1811 other wide characters are represented as sequences of upper-half
1812 (The full UTF-8 scheme allows for encoding 31-bit characters as
1813 6-byte sequences, but in this implementation, all UTF-8 sequences
1814 of four or more bytes length will be treated as illegal).
1815 @item Brackets Coding
1816 In this encoding, a wide character is represented by the following eight
1817 character sequence:
1819 @smallexample
1820 [ " a b c d " ]
1821 @end smallexample
1823 @noindent
1824 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1825 characters (using uppercase letters) of the wide character code. For
1826 example, ["A345"] is used to represent the wide character with code
1827 @code{16#A345#}. It is also possible (though not required) to use the
1828 Brackets coding for upper half characters. For example, the code
1829 @code{16#A3#} can be represented as @code{["A3"]}.
1831 This scheme is compatible with use of the full Wide_Character set,
1832 and is also the method used for wide character encoding in the standard
1833 ACVC (Ada Compiler Validation Capability) test suite distributions.
1835 @end table
1837 @noindent
1838 Note: Some of these coding schemes do not permit the full use of the
1839 Ada 95 character set. For example, neither Shift JIS, nor EUC allow the
1840 use of the upper half of the Latin-1 set.
1842 @node File Naming Rules
1843 @section File Naming Rules
1845 @noindent
1846 The default file name is determined by the name of the unit that the
1847 file contains. The name is formed by taking the full expanded name of
1848 the unit and replacing the separating dots with hyphens and using
1849 ^lowercase^uppercase^ for all letters.
1851 An exception arises if the file name generated by the above rules starts
1852 with one of the characters
1853 @ifset vms
1854 A,G,I, or S,
1855 @end ifset
1856 @ifclear vms
1857 a,g,i, or s,
1858 @end ifclear
1859 and the second character is a
1860 minus. In this case, the character ^tilde^dollar sign^ is used in place
1861 of the minus. The reason for this special rule is to avoid clashes with
1862 the standard names for child units of the packages System, Ada,
1863 Interfaces, and GNAT, which use the prefixes
1864 @ifset vms
1865 S- A- I- and G-
1866 @end ifset
1867 @ifclear vms
1868 s- a- i- and g-
1869 @end ifclear
1870 respectively.
1872 The file extension is @file{.ads} for a spec and
1873 @file{.adb} for a body. The following list shows some
1874 examples of these rules.
1876 @table @file
1877 @item main.ads
1878 Main (spec)
1879 @item main.adb
1880 Main (body)
1881 @item arith_functions.ads
1882 Arith_Functions (package spec)
1883 @item arith_functions.adb
1884 Arith_Functions (package body)
1885 @item func-spec.ads
1886 Func.Spec (child package spec)
1887 @item func-spec.adb
1888 Func.Spec (child package body)
1889 @item main-sub.adb
1890 Sub (subunit of Main)
1891 @item ^a~bad.adb^A$BAD.ADB^
1892 A.Bad (child package body)
1893 @end table
1895 @noindent
1896 Following these rules can result in excessively long
1897 file names if corresponding
1898 unit names are long (for example, if child units or subunits are
1899 heavily nested). An option is available to shorten such long file names
1900 (called file name "krunching"). This may be particularly useful when
1901 programs being developed with GNAT are to be used on operating systems
1902 with limited file name lengths. @xref{Using gnatkr}.
1904 Of course, no file shortening algorithm can guarantee uniqueness over
1905 all possible unit names; if file name krunching is used, it is your
1906 responsibility to ensure no name clashes occur. Alternatively you
1907 can specify the exact file names that you want used, as described
1908 in the next section. Finally, if your Ada programs are migrating from a
1909 compiler with a different naming convention, you can use the gnatchop
1910 utility to produce source files that follow the GNAT naming conventions.
1911 (For details @pxref{Renaming Files Using gnatchop}.)
1913 @node Using Other File Names
1914 @section Using Other File Names
1915 @cindex File names
1917 @noindent
1918 In the previous section, we have described the default rules used by
1919 GNAT to determine the file name in which a given unit resides. It is
1920 often convenient to follow these default rules, and if you follow them,
1921 the compiler knows without being explicitly told where to find all
1922 the files it needs.
1924 However, in some cases, particularly when a program is imported from
1925 another Ada compiler environment, it may be more convenient for the
1926 programmer to specify which file names contain which units. GNAT allows
1927 arbitrary file names to be used by means of the Source_File_Name pragma.
1928 The form of this pragma is as shown in the following examples:
1929 @cindex Source_File_Name pragma
1931 @smallexample
1932 @group
1933 @cartouche
1934 @b{pragma} Source_File_Name (My_Utilities.Stacks,
1935   Spec_File_Name => "myutilst_a.ada");
1936 @b{pragma} Source_File_name (My_Utilities.Stacks,
1937   Body_File_Name => "myutilst.ada");
1938 @end cartouche
1939 @end group
1940 @end smallexample
1942 @noindent
1943 As shown in this example, the first argument for the pragma is the unit
1944 name (in this example a child unit). The second argument has the form
1945 of a named association. The identifier
1946 indicates whether the file name is for a spec or a body;
1947 the file name itself is given by a string literal.
1949 The source file name pragma is a configuration pragma, which means that
1950 normally it will be placed in the @file{gnat.adc}
1951 file used to hold configuration
1952 pragmas that apply to a complete compilation environment.
1953 For more details on how the @file{gnat.adc} file is created and used
1954 @pxref{Handling of Configuration Pragmas}
1955 @cindex @file{gnat.adc}
1957 @ifclear vms
1958 GNAT allows completely arbitrary file names to be specified using the
1959 source file name pragma. However, if the file name specified has an
1960 extension other than @file{.ads} or @file{.adb} it is necessary to use a special
1961 syntax when compiling the file. The name in this case must be preceded
1962 by the special sequence @code{-x} followed by a space and the name of the
1963 language, here @code{ada}, as in:
1965 @smallexample
1966 $ gcc -c -x ada peculiar_file_name.sim
1967 @end smallexample
1968 @end ifclear
1970 @noindent
1971 @code{gnatmake} handles non-standard file names in the usual manner (the
1972 non-standard file name for the main program is simply used as the
1973 argument to gnatmake). Note that if the extension is also non-standard,
1974 then it must be included in the gnatmake command, it may not be omitted.
1976 @node Alternative File Naming Schemes
1977 @section Alternative File Naming Schemes
1978 @cindex File naming schemes, alternative
1979 @cindex File names
1981 In the previous section, we described the use of the @code{Source_File_Name}
1982 pragma to allow arbitrary names to be assigned to individual source files.
1983 However, this approach requires one pragma for each file, and especially in
1984 large systems can result in very long @file{gnat.adc} files, and also create
1985 a maintenance problem.
1987 GNAT also provides a facility for specifying systematic file naming schemes
1988 other than the standard default naming scheme previously described. An
1989 alternative scheme for naming is specified by the use of
1990 @code{Source_File_Name} pragmas having the following format:
1991 @cindex Source_File_Name pragma
1993 @smallexample
1994 pragma Source_File_Name (
1995    Spec_File_Name  => FILE_NAME_PATTERN
1996  [,Casing          => CASING_SPEC]
1997  [,Dot_Replacement => STRING_LITERAL]);
1999 pragma Source_File_Name (
2000    Body_File_Name  => FILE_NAME_PATTERN
2001  [,Casing          => CASING_SPEC]
2002  [,Dot_Replacement => STRING_LITERAL]);
2004 pragma Source_File_Name (
2005    Subunit_File_Name  => FILE_NAME_PATTERN
2006  [,Casing             => CASING_SPEC]
2007  [,Dot_Replacement    => STRING_LITERAL]);
2009 FILE_NAME_PATTERN ::= STRING_LITERAL
2010 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2012 @end smallexample
2014 @noindent
2015 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
2016 It contains a single asterisk character, and the unit name is substituted
2017 systematically for this asterisk. The optional parameter
2018 @code{Casing} indicates
2019 whether the unit name is to be all upper-case letters, all lower-case letters,
2020 or mixed-case. If no
2021 @code{Casing} parameter is used, then the default is all
2022 ^lower-case^upper-case^.
2024 The optional @code{Dot_Replacement} string is used to replace any periods
2025 that occur in subunit or child unit names. If no @code{Dot_Replacement}
2026 argument is used then separating dots appear unchanged in the resulting
2027 file name.
2028 Although the above syntax indicates that the
2029 @code{Casing} argument must appear
2030 before the @code{Dot_Replacement} argument, but it
2031 is also permissible to write these arguments in the opposite order.
2033 As indicated, it is possible to specify different naming schemes for
2034 bodies, specs, and subunits. Quite often the rule for subunits is the
2035 same as the rule for bodies, in which case, there is no need to give
2036 a separate @code{Subunit_File_Name} rule, and in this case the
2037 @code{Body_File_name} rule is used for subunits as well.
2039 The separate rule for subunits can also be used to implement the rather
2040 unusual case of a compilation environment (e.g. a single directory) which
2041 contains a subunit and a child unit with the same unit name. Although
2042 both units cannot appear in the same partition, the Ada Reference Manual
2043 allows (but does not require) the possibility of the two units coexisting
2044 in the same environment.
2046 The file name translation works in the following steps:
2048 @itemize @bullet
2050 @item
2051 If there is a specific @code{Source_File_Name} pragma for the given unit,
2052 then this is always used, and any general pattern rules are ignored.
2054 @item
2055 If there is a pattern type @code{Source_File_Name} pragma that applies to
2056 the unit, then the resulting file name will be used if the file exists. If
2057 more than one pattern matches, the latest one will be tried first, and the
2058 first attempt resulting in a reference to a file that exists will be used.
2060 @item
2061 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2062 for which the corresponding file exists, then the standard GNAT default
2063 naming rules are used.
2065 @end itemize
2067 @noindent
2068 As an example of the use of this mechanism, consider a commonly used scheme
2069 in which file names are all lower case, with separating periods copied
2070 unchanged to the resulting file name, and specs end with ".1.ada", and
2071 bodies end with ".2.ada". GNAT will follow this scheme if the following
2072 two pragmas appear:
2074 @smallexample
2075 pragma Source_File_Name
2076   (Spec_File_Name => "*.1.ada");
2077 pragma Source_File_Name
2078   (Body_File_Name => "*.2.ada");
2079 @end smallexample
2081 @noindent
2082 The default GNAT scheme is actually implemented by providing the following
2083 default pragmas internally:
2085 @smallexample
2086 pragma Source_File_Name
2087   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
2088 pragma Source_File_Name
2089   (Body_File_Name => "*.adb", Dot_Replacement => "-");
2090 @end smallexample
2092 @noindent
2093 Our final example implements a scheme typically used with one of the
2094 Ada 83 compilers, where the separator character for subunits was "__"
2095 (two underscores), specs were identified by adding @file{_.ADA}, bodies
2096 by adding @file{.ADA}, and subunits by
2097 adding @file{.SEP}. All file names were
2098 upper case. Child units were not present of course since this was an
2099 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2100 the same double underscore separator for child units.
2102 @smallexample
2103 pragma Source_File_Name
2104   (Spec_File_Name => "*_.ADA",
2105    Dot_Replacement => "__",
2106    Casing = Uppercase);
2107 pragma Source_File_Name
2108   (Body_File_Name => "*.ADA",
2109    Dot_Replacement => "__",
2110    Casing = Uppercase);
2111 pragma Source_File_Name
2112   (Subunit_File_Name => "*.SEP",
2113    Dot_Replacement => "__",
2114    Casing = Uppercase);
2115 @end smallexample
2117 @node Generating Object Files
2118 @section Generating Object Files
2120 @noindent
2121 An Ada program consists of a set of source files, and the first step in
2122 compiling the program is to generate the corresponding object files.
2123 These are generated by compiling a subset of these source files.
2124 The files you need to compile are the following:
2126 @itemize @bullet
2127 @item
2128 If a package spec has no body, compile the package spec to produce the
2129 object file for the package.
2131 @item
2132 If a package has both a spec and a body, compile the body to produce the
2133 object file for the package. The source file for the package spec need
2134 not be compiled in this case because there is only one object file, which
2135 contains the code for both the spec and body of the package.
2137 @item
2138 For a subprogram, compile the subprogram body to produce the object file
2139 for the subprogram. The spec, if one is present, is as usual in a
2140 separate file, and need not be compiled.
2142 @item
2143 @cindex Subunits
2144 In the case of subunits, only compile the parent unit. A single object
2145 file is generated for the entire subunit tree, which includes all the
2146 subunits.
2148 @item
2149 Compile child units independently of their parent units
2150 (though, of course, the spec of all the ancestor unit must be present in order
2151 to compile a child unit).
2153 @item
2154 @cindex Generics
2155 Compile generic units in the same manner as any other units. The object
2156 files in this case are small dummy files that contain at most the
2157 flag used for elaboration checking. This is because GNAT always handles generic
2158 instantiation by means of macro expansion. However, it is still necessary to
2159 compile generic units, for dependency checking and elaboration purposes.
2160 @end itemize
2162 @noindent
2163 The preceding rules describe the set of files that must be compiled to
2164 generate the object files for a program. Each object file has the same
2165 name as the corresponding source file, except that the extension is
2166 @file{.o} as usual.
2168 You may wish to compile other files for the purpose of checking their
2169 syntactic and semantic correctness. For example, in the case where a
2170 package has a separate spec and body, you would not normally compile the
2171 spec. However, it is convenient in practice to compile the spec to make
2172 sure it is error-free before compiling clients of this spec, because such
2173 compilations will fail if there is an error in the spec.
2175 GNAT provides an option for compiling such files purely for the
2176 purposes of checking correctness; such compilations are not required as
2177 part of the process of building a program. To compile a file in this
2178 checking mode, use the @option{-gnatc} switch.
2180 @node Source Dependencies
2181 @section Source Dependencies
2183 @noindent
2184 A given object file clearly depends on the source file which is compiled
2185 to produce it. Here we are using @dfn{depends} in the sense of a typical
2186 @code{make} utility; in other words, an object file depends on a source
2187 file if changes to the source file require the object file to be
2188 recompiled.
2189 In addition to this basic dependency, a given object may depend on
2190 additional source files as follows:
2192 @itemize @bullet
2193 @item
2194 If a file being compiled @code{with}'s a unit @var{X}, the object file
2195 depends on the file containing the spec of unit @var{X}. This includes
2196 files that are @code{with}'ed implicitly either because they are parents
2197 of @code{with}'ed child units or they are run-time units required by the
2198 language constructs used in a particular unit.
2200 @item
2201 If a file being compiled instantiates a library level generic unit, the
2202 object file depends on both the spec and body files for this generic
2203 unit.
2205 @item
2206 If a file being compiled instantiates a generic unit defined within a
2207 package, the object file depends on the body file for the package as
2208 well as the spec file.
2210 @item
2211 @findex Inline
2212 @cindex @option{-gnatn} switch
2213 If a file being compiled contains a call to a subprogram for which
2214 pragma @code{Inline} applies and inlining is activated with the
2215 @option{-gnatn} switch, the object file depends on the file containing the
2216 body of this subprogram as well as on the file containing the spec. Note
2217 that for inlining to actually occur as a result of the use of this switch,
2218 it is necessary to compile in optimizing mode.
2220 @cindex @option{-gnatN} switch
2221 The use of @option{-gnatN} activates a more extensive inlining optimization
2222 that is performed by the front end of the compiler. This inlining does
2223 not require that the code generation be optimized. Like @option{-gnatn},
2224 the use of this switch generates additional dependencies.
2226 @item
2227 If an object file O  depends on the proper body of a subunit through inlining
2228 or instantiation, it depends on the parent unit of the subunit. This means that
2229 any modification of the parent unit or one of its subunits affects the
2230 compilation of O.
2232 @item
2233 The object file for a parent unit depends on all its subunit body files.
2235 @item
2236 The previous two rules meant that for purposes of computing dependencies and
2237 recompilation, a body and all its subunits are treated as an indivisible whole.
2239 @noindent
2240 These rules are applied transitively: if unit @code{A} @code{with}'s
2241 unit @code{B}, whose elaboration calls an inlined procedure in package
2242 @code{C}, the object file for unit @code{A} will depend on the body of
2243 @code{C}, in file @file{c.adb}.
2245 The set of dependent files described by these rules includes all the
2246 files on which the unit is semantically dependent, as described in the
2247 Ada 95 Language Reference Manual. However, it is a superset of what the
2248 ARM describes, because it includes generic, inline, and subunit dependencies.
2250 An object file must be recreated by recompiling the corresponding source
2251 file if any of the source files on which it depends are modified. For
2252 example, if the @code{make} utility is used to control compilation,
2253 the rule for an Ada object file must mention all the source files on
2254 which the object file depends, according to the above definition.
2255 The determination of the necessary
2256 recompilations is done automatically when one uses @code{gnatmake}.
2257 @end itemize
2259 @node The Ada Library Information Files
2260 @section The Ada Library Information Files
2261 @cindex Ada Library Information files
2262 @cindex @file{ali} files
2264 @noindent
2265 Each compilation actually generates two output files. The first of these
2266 is the normal object file that has a @file{.o} extension. The second is a
2267 text file containing full dependency information. It has the same
2268 name as the source file, but an @file{.ali} extension.
2269 This file is known as the Ada Library Information (@file{ali}) file.
2270 The following information is contained in the @file{ali} file.
2272 @itemize @bullet
2273 @item
2274 Version information (indicates which version of GNAT was used to compile
2275 the unit(s) in question)
2277 @item
2278 Main program information (including priority and time slice settings,
2279 as well as the wide character encoding used during compilation).
2281 @item
2282 List of arguments used in the @code{gcc} command for the compilation
2284 @item
2285 Attributes of the unit, including configuration pragmas used, an indication
2286 of whether the compilation was successful, exception model used etc.
2288 @item
2289 A list of relevant restrictions applying to the unit (used for consistency)
2290 checking.
2292 @item
2293 Categorization information (e.g. use of pragma @code{Pure}).
2295 @item
2296 Information on all @code{with}'ed units, including presence of
2297 @code{Elaborate} or @code{Elaborate_All} pragmas.
2299 @item
2300 Information from any @code{Linker_Options} pragmas used in the unit
2302 @item
2303 Information on the use of @code{Body_Version} or @code{Version}
2304 attributes in the unit.
2306 @item
2307 Dependency information. This is a list of files, together with
2308 time stamp and checksum information. These are files on which
2309 the unit depends in the sense that recompilation is required
2310 if any of these units are modified.
2312 @item
2313 Cross-reference data. Contains information on all entities referenced
2314 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2315 provide cross-reference information.
2317 @end itemize
2319 @noindent
2320 For a full detailed description of the format of the @file{ali} file,
2321 see the source of the body of unit @code{Lib.Writ}, contained in file
2322 @file{lib-writ.adb} in the GNAT compiler sources.
2324 @node Binding an Ada Program
2325 @section Binding an Ada Program
2327 @noindent
2328 When using languages such as C and C++, once the source files have been
2329 compiled the only remaining step in building an executable program
2330 is linking the object modules together. This means that it is possible to
2331 link an inconsistent version of a program, in which two units have
2332 included different versions of the same header.
2334 The rules of Ada do not permit such an inconsistent program to be built.
2335 For example, if two clients have different versions of the same package,
2336 it is illegal to build a program containing these two clients.
2337 These rules are enforced by the GNAT binder, which also determines an
2338 elaboration order consistent with the Ada rules.
2340 The GNAT binder is run after all the object files for a program have
2341 been created. It is given the name of the main program unit, and from
2342 this it determines the set of units required by the program, by reading the
2343 corresponding ALI files. It generates error messages if the program is
2344 inconsistent or if no valid order of elaboration exists.
2346 If no errors are detected, the binder produces a main program, in Ada by
2347 default, that contains calls to the elaboration procedures of those
2348 compilation unit that require them, followed by
2349 a call to the main program. This Ada program is compiled to generate the
2350 object file for the main program. The name of
2351 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2352 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2353 main program unit.
2355 Finally, the linker is used to build the resulting executable program,
2356 using the object from the main program from the bind step as well as the
2357 object files for the Ada units of the program.
2359 @node Mixed Language Programming
2360 @section Mixed Language Programming
2361 @cindex Mixed Language Programming
2363 @menu
2364 * Interfacing to C::
2365 * Calling Conventions::
2366 @end menu
2368 @node Interfacing to C
2369 @subsection Interfacing to C
2370 @noindent
2371 There are two ways to
2372 build a program that contains some Ada files and some other language
2373 files depending on whether the main program is in Ada or not.
2374 If the main program is in Ada, you should proceed as follows:
2376 @enumerate
2377 @item
2378 Compile the other language files to generate object files. For instance:
2379 @smallexample
2380 gcc -c file1.c
2381 gcc -c file2.c
2382 @end smallexample
2384 @item
2385 Compile the Ada units to produce a set of object files and ALI
2386 files. For instance:
2387 @smallexample
2388 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2389 @end smallexample
2391 @item
2392 Run the Ada binder on the Ada main program. For instance:
2393 @smallexample
2394 gnatbind my_main.ali
2395 @end smallexample
2397 @item
2398 Link the Ada main program, the Ada objects and the other language
2399 objects. For instance:
2400 @smallexample
2401 gnatlink my_main.ali file1.o file2.o
2402 @end smallexample
2403 @end enumerate
2405 The three last steps can be grouped in a single command:
2406 @smallexample
2407 gnatmake my_main.adb -largs file1.o file2.o
2408 @end smallexample
2410 @cindex Binder output file
2411 @noindent
2412 If the main program is in some language other than Ada, you may
2413 have more than one entry point in the Ada subsystem. You must use a
2414 special option of the binder to generate callable routines to initialize
2415 and finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2416 Calls to the initialization and finalization routines must be inserted in
2417 the main program, or some other appropriate point in the code. The call to
2418 initialize the Ada units must occur before the first Ada subprogram is
2419 called, and the call to finalize the Ada units must occur after the last
2420 Ada subprogram returns. You use the same procedure for building the
2421 program as described previously. In this case, however, the binder
2422 only places the initialization and finalization subprograms into file
2423 @file{b~@var{xxx}.adb} instead of the main program.
2424 So, if the main program is not in Ada, you should proceed as follows:
2426 @enumerate
2427 @item
2428 Compile the other language files to generate object files. For instance:
2429 @smallexample
2430 gcc -c file1.c
2431 gcc -c file2.c
2432 @end smallexample
2434 @item
2435 Compile the Ada units to produce a set of object files and ALI
2436 files. For instance:
2437 @smallexample
2438 gnatmake ^-c^/ACTIONS=COMPILE^ entry_point1.adb
2439 gnatmake ^-c^/ACTIONS=COMPILE^ entry_point2.adb
2440 @end smallexample
2442 @item
2443 Run the Ada binder on the Ada main program. For instance:
2444 @smallexample
2445 gnatbind ^-n^/NOMAIN^ entry_point1.ali entry_point2.ali
2446 @end smallexample
2448 @item
2449 Link the Ada main program, the Ada objects and the other language
2450 objects. You only need to give the last entry point here. For instance:
2451 @smallexample
2452 gnatlink entry_point2.ali file1.o file2.o
2453 @end smallexample
2454 @end enumerate
2456 @node Calling Conventions
2457 @subsection Calling Conventions
2458 @cindex Foreign Languages
2459 @cindex Calling Conventions
2460 GNAT follows standard calling sequence conventions and will thus interface
2461 to any other language that also follows these conventions. The following
2462 Convention identifiers are recognized by GNAT:
2464 @itemize @bullet
2465 @cindex Interfacing to Ada
2466 @cindex Other Ada compilers
2467 @cindex Convention Ada
2468 @item
2469 Ada. This indicates that the standard Ada calling sequence will be
2470 used and all Ada data items may be passed without any limitations in the
2471 case where GNAT is used to generate both the caller and callee. It is also
2472 possible to mix GNAT generated code and code generated by another Ada
2473 compiler. In this case, the data types should be restricted to simple
2474 cases, including primitive types. Whether complex data types can be passed
2475 depends on the situation. Probably it is safe to pass simple arrays, such
2476 as arrays of integers or floats. Records may or may not work, depending
2477 on whether both compilers lay them out identically. Complex structures
2478 involving variant records, access parameters, tasks, or protected types,
2479 are unlikely to be able to be passed.
2481 Note that in the case of GNAT running
2482 on a platform that supports DEC Ada 83, a higher degree of compatibility
2483 can be guaranteed, and in particular records are layed out in an identical
2484 manner in the two compilers. Note also that if output from two different
2485 compilers is mixed, the program is responsible for dealing with elaboration
2486 issues. Probably the safest approach is to write the main program in the
2487 version of Ada other than GNAT, so that it takes care of its own elaboration
2488 requirements, and then call the GNAT-generated adainit procedure to ensure
2489 elaboration of the GNAT components. Consult the documentation of the other
2490 Ada compiler for further details on elaboration.
2492 However, it is not possible to mix the tasking run time of GNAT and
2493 DEC Ada 83, All the tasking operations must either be entirely within
2494 GNAT compiled sections of the program, or entirely within DEC Ada 83
2495 compiled sections of the program.
2497 @cindex Interfacing to Assembly
2498 @cindex Convention Assembler
2499 @item
2500 Assembler. Specifies assembler as the convention. In practice this has the
2501 same effect as convention Ada (but is not equivalent in the sense of being
2502 considered the same convention).
2504 @cindex Convention Asm
2505 @findex Asm
2506 @item
2507 Asm. Equivalent to Assembler.
2509 @cindex Convention Asm
2510 @findex Asm
2511 @item
2512 Asm. Equivalent to Assembly.
2514 @cindex Interfacing to COBOL
2515 @cindex Convention COBOL
2516 @findex COBOL
2517 @item
2518 COBOL. Data will be passed according to the conventions described
2519 in section B.4 of the Ada 95 Reference Manual.
2521 @findex C
2522 @cindex Interfacing to C
2523 @cindex Convention C
2524 @item
2525 C. Data will be passed according to the conventions described
2526 in section B.3 of the Ada 95 Reference Manual.
2528 @cindex Convention Default
2529 @findex Default
2530 @item
2531 Default. Equivalent to C.
2533 @cindex Convention External
2534 @findex External
2535 @item
2536 External. Equivalent to C.
2538 @findex C++
2539 @cindex Interfacing to C++
2540 @cindex Convention C++
2541 @item
2542 CPP. This stands for C++. For most purposes this is identical to C.
2543 See the separate description of the specialized GNAT pragmas relating to
2544 C++ interfacing for further details.
2546 @findex Fortran
2547 @cindex Interfacing to Fortran
2548 @cindex Convention Fortran
2549 @item
2550 Fortran. Data will be passed according to the conventions described
2551 in section B.5 of the Ada 95 Reference Manual.
2553 @item
2554 Intrinsic. This applies to an intrinsic operation, as defined in the Ada 95
2555 Reference Manual. If a a pragma Import (Intrinsic) applies to a subprogram,
2556 this means that the body of the subprogram is provided by the compiler itself,
2557 usually by means of an efficient code sequence, and that the user does not
2558 supply an explicit body for it. In an application program, the pragma can only
2559 be applied to the following two sets of names, which the GNAT compiler
2560 recognizes.
2561 @itemize @bullet
2562 @item
2563 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_-
2564 Arithmetic.  The corresponding subprogram declaration must have
2565 two formal parameters. The
2566 first one must be a signed integer type or a modular type with a binary
2567 modulus, and the second parameter must be of type Natural.
2568 The return type must be the same as the type of the first argument. The size
2569 of this type can only be 8, 16, 32, or 64.
2570 @item binary arithmetic operators: "+", "-", "*", "/"
2571 The corresponding operator declaration must have parameters and result type
2572 that have the same root numeric type (for example, all three are long_float
2573 types). This simplifies the definition of operations that use type checking
2574 to perform dimensional checks:
2575 @smallexample
2576 type Distance is new Long_Float;
2577 type Time     is new Long_Float;
2578 type Velocity is new Long_Float;
2579 function "/" (D : Distance; T : Time)
2580   return Velocity;
2581 pragma Import (Intrinsic, "/");
2582 @end smallexample
2583 @noindent
2584 This common idiom is often programmed with a generic definition and an explicit
2585 body. The pragma makes it simpler to introduce such declarations. It incurs
2586 no overhead in compilation time or code size, because it is implemented as a
2587 single machine instruction.
2588 @end itemize
2589 @noindent
2591 @findex Stdcall
2592 @cindex Convention Stdcall
2593 @item
2594 Stdcall. This is relevant only to NT/Win95 implementations of GNAT,
2595 and specifies that the Stdcall calling sequence will be used, as defined
2596 by the NT API.
2598 @findex DLL
2599 @cindex Convention DLL
2600 @item
2601 DLL. This is equivalent to Stdcall.
2603 @findex Win32
2604 @cindex Convention Win32
2605 @item
2606 Win32. This is equivalent to Stdcall.
2608 @findex Stubbed
2609 @cindex Convention Stubbed
2610 @item
2611 Stubbed. This is a special convention that indicates that the compiler
2612 should provide a stub body that raises @code{Program_Error}.
2613 @end itemize
2615 @noindent
2616 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2617 that can be used to parametrize conventions and allow additional synonyms
2618 to be specified. For example if you have legacy code in which the convention
2619 identifier Fortran77 was used for Fortran, you can use the configuration
2620 pragma:
2622 @smallexample
2623    pragma Convention_Identifier (Fortran77, Fortran);
2624 @end smallexample
2626 @noindent
2627 And from now on the identifier Fortran77 may be used as a convention
2628 identifier (for example in an @code{Import} pragma) with the same
2629 meaning as Fortran.
2631 @node Building Mixed Ada & C++ Programs
2632 @section Building Mixed Ada & C++ Programs
2634 @noindent
2635 Building a mixed application containing both Ada and C++ code may be a
2636 challenge for the unaware programmer. As a matter of fact, this
2637 interfacing has not been standardized in the Ada 95 reference manual due
2638 to the immaturity and lack of standard of C++ at the time. This
2639 section gives a few hints that should make this task easier. In
2640 particular the first section addresses the differences with
2641 interfacing with C. The second section looks into the delicate problem
2642 of linking the complete application from its Ada and C++ parts. The last
2643 section give some hints on how the GNAT run time can be adapted in order
2644 to allow inter-language dispatching with a new C++ compiler.
2646 @menu
2647 * Interfacing to C++::
2648 * Linking a Mixed C++ & Ada Program::
2649 * A Simple Example::
2650 * Adapting the Run Time to a New C++ Compiler::
2651 @end menu
2653 @node Interfacing to C++
2654 @subsection Interfacing to C++
2656 @noindent
2657 GNAT supports interfacing with C++ compilers generating code that is
2658 compatible with the standard Application Binary Interface of the given
2659 platform.
2661 @noindent
2662 Interfacing can be done at 3 levels: simple data, subprograms and
2663 classes. In the first 2 cases, GNAT offer a specific @var{Convention
2664 CPP} that behaves exactly like @var{Convention C}. Usually C++ mangle
2665 names of subprograms and currently GNAT does not provide any help to
2666 solve the demangling problem. This problem can be addressed in 2 ways:
2667 @itemize @bullet
2668 @item
2669 by modifying the C++ code in order to force a C convention using
2670 the @var{extern "C"} syntax.
2672 @item
2673 by figuring out the mangled name and use it as the Link_Name argument of
2674 the pragma import.
2675 @end itemize
2677 @noindent
2678 Interfacing at the class level can be achieved by using the GNAT specific
2679 pragmas such as @code{CPP_Class} and @code{CPP_Virtual}. See the GNAT
2680 Reference Manual for additional information.
2682 @node Linking a Mixed C++ & Ada Program
2683 @subsection Linking a Mixed C++ & Ada Program
2685 @noindent
2686 Usually the linker of the C++ development system must be used to link
2687 mixed applications because most C++ systems will resolve elaboration
2688 issues (such as calling constructors on global class instances)
2689 transparently during the link phase. GNAT has been adapted to ease the
2690 use of a foreign linker for the last phase. Three cases can be
2691 considered:
2692 @enumerate
2694 @item
2695 Using GNAT and G++ (GNU C++ compiler) from the same GCC
2696 installation. The c++ linker can simply be called by using the c++
2697 specific driver called @code{c++}. Note that this setup is not
2698 very common because it may request recompiling the whole GCC
2699 tree from sources and it does not allow to upgrade easily to a new
2700 version of one compiler for one of the two languages without taking the
2701 risk of destabilizing the other.
2703 @smallexample
2704 $ c++ -c file1.C
2705 $ c++ -c file2.C
2706 $ gnatmake ada_unit -largs file1.o file2.o --LINK=c++
2707 @end smallexample
2709 @item
2710 Using GNAT and G++ from 2 different GCC installations. If both compilers
2711 are on the PATH, the same method can be used. It is important to be
2712 aware that environment variables such as C_INCLUDE_PATH,
2713 GCC_EXEC_PREFIX, BINUTILS_ROOT or GCC_ROOT will affect both compilers at
2714 the same time and thus may make one of the 2 compilers operate
2715 improperly if they are set for the other. In particular it is important
2716 that the link command has access to the proper gcc library @file{libgcc.a},
2717 that is to say the one that is part of the C++ compiler
2718 installation. The implicit link command as suggested in the gnatmake
2719 command from the former example can be replaced by an explicit link
2720 command with full verbosity in order to verify which library is used:
2721 @smallexample
2722 $ gnatbind ada_unit
2723 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2724 @end smallexample
2725 If there is a problem due to interfering environment variables, it can
2726 be workaround by using an intermediate script. The following example
2727 shows the proper script to use when GNAT has not been installed at its
2728 default location and g++ has been installed at its default location:
2730 @smallexample
2731 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2732 $ cat ./my_script
2733 #!/bin/sh
2734 unset BINUTILS_ROOT
2735 unset GCC_ROOT
2736 c++ $*
2737 @end smallexample
2739 @item
2740 Using a non GNU C++ compiler. The same set of command as previously
2741 described can be used to insure that the c++ linker is
2742 used. Nonetheless, you need to add the path to libgcc explicitely, since some
2743 libraries needed by GNAT are located in this directory:
2745 @smallexample
2747 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2748 $ cat ./my_script
2749 #!/bin/sh
2750 CC $* `gcc -print-libgcc-file-name`
2752 @end smallexample
2754 Where CC is the name of the non GNU C++ compiler.
2756 @end enumerate
2758 @node A Simple Example
2759 @subsection  A Simple Example
2760 @noindent
2761 The following example, provided as part of the GNAT examples, show how
2762 to achieve procedural interfacing between Ada and C++ in both
2763 directions. The C++ class A has 2 methods. The first method is exported
2764 to Ada by the means of an extern C wrapper function. The second method
2765 calls an Ada subprogram. On the Ada side, The C++ calls is modelized by
2766 a limited record with a layout comparable to the C++ class. The Ada
2767 subprogram, in turn, calls the c++ method. So from the C++ main program
2768 the code goes back and forth between the 2 languages.
2770 @noindent
2771 Here are the compilation commands
2772 @ifclear vxworks
2773 for native configurations:
2774 @smallexample
2775 $ gnatmake -c simple_cpp_interface
2776 $ c++ -c cpp_main.C
2777 $ c++ -c ex7.C
2778 $ gnatbind -n simple_cpp_interface
2779 $ gnatlink simple_cpp_interface -o cpp_main --LINK=$(CPLUSPLUS)
2780       -lstdc++ ex7.o cpp_main.o
2781 @end smallexample
2782 @end ifclear
2783 @ifset vxworks
2784 for a GNAT VxWorks/PowerPC  configuration:
2785 @smallexample
2786 $ powerpc-wrs-vxworks-gnatmake -c simple_cpp_interface
2787 $ powerpc-wrs-vxworks-gnatbind -n simple_cpp_interface
2788 $ gnatlink simple_cpp_interface -o ada_part
2789 $ c++ppc -c -DCPU=PPC604  -I/usr/windppc/target/h  cpp_main.C
2790 $ c++ppc -c -DCPU=PPC604  -I/usr/windppc/target/h  ex7.C
2791 $ ldppc -r -o my_main my_main.o ex7.o ada_part
2792 @end smallexample
2793 @end ifset
2794 @noindent
2795 Here are the corresponding sources:
2796 @smallexample
2798 //cpp_main.C
2800 #include "ex7.h"
2802 extern "C" @{
2803   void adainit (void);
2804   void adafinal (void);
2805   void method1 (A *t);
2808 void method1 (A *t)
2810   t->method1 ();
2813 int main ()
2815   A obj;
2816   adainit ();
2817   obj.method2 (3030);
2818   adafinal ();
2821 //ex7.h
2823 class Origin @{
2824  public:
2825   int o_value;
2827 class A : public Origin @{
2828  public:
2829   void method1 (void);
2830   virtual void method2 (int v);
2831   A();
2832   int   a_value;
2835 //ex7.C
2837 #include "ex7.h"
2838 #include <stdio.h>
2840 extern "C" @{ void ada_method2 (A *t, int v);@}
2842 void A::method1 (void)
2844   a_value = 2020;
2845   printf ("in A::method1, a_value = %d \n",a_value);
2849 void A::method2 (int v)
2851    ada_method2 (this, v);
2852    printf ("in A::method2, a_value = %d \n",a_value);
2856 A::A(void)
2858    a_value = 1010;
2859   printf ("in A::A, a_value = %d \n",a_value);
2862 -- Ada sources
2863 @b{package} @b{body} Simple_Cpp_Interface @b{is}
2865    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer) @b{is}
2866    @b{begin}
2867       Method1 (This);
2868       This.A_Value := V;
2869    @b{end} Ada_Method2;
2871 @b{end} Simple_Cpp_Interface;
2873 @b{package} Simple_Cpp_Interface @b{is}
2874    @b{type} A @b{is} @b{limited}
2875       @b{record}
2876          O_Value : Integer;
2877          A_Value : Integer;
2878       @b{end} @b{record};
2879    @b{pragma} Convention (C, A);
2881    @b{procedure} Method1 (This : @b{in} @b{out} A);
2882    @b{pragma} Import (C, Method1);
2884    @b{procedure} Ada_Method2 (This : @b{in} @b{out} A; V : Integer);
2885    @b{pragma} Export (C, Ada_Method2);
2887 @b{end} Simple_Cpp_Interface;
2888 @end smallexample
2890 @node Adapting the Run Time to a New C++ Compiler
2891 @subsection Adapting the Run Time to a New C++ Compiler
2892 @noindent
2893 GNAT offers the capability to derive Ada 95 tagged types directly from
2894 preexisting C++ classes and . See "Interfacing with C++" in the GNAT
2895 reference manual. The mechanism used by GNAT for achieving such a goal
2896 has been made user configurable through a GNAT library unit
2897 @code{Interfaces.CPP}. The default version of this file is adapted to
2898 the GNU c++ compiler. Internal knowledge of the virtual
2899 table layout used by the new C++ compiler is needed to configure
2900 properly this unit. The Interface of this unit is known by the compiler
2901 and cannot be changed except for the value of the constants defining the
2902 characteristics of the virtual table: CPP_DT_Prologue_Size, CPP_DT_Entry_Size,
2903 CPP_TSD_Prologue_Size, CPP_TSD_Entry_Size. Read comments in the source
2904 of this unit for more details.
2906 @node Comparison between GNAT and C/C++ Compilation Models
2907 @section Comparison between GNAT and C/C++ Compilation Models
2909 @noindent
2910 The GNAT model of compilation is close to the C and C++ models. You can
2911 think of Ada specs as corresponding to header files in C. As in C, you
2912 don't need to compile specs; they are compiled when they are used. The
2913 Ada @code{with} is similar in effect to the @code{#include} of a C
2914 header.
2916 One notable difference is that, in Ada, you may compile specs separately
2917 to check them for semantic and syntactic accuracy. This is not always
2918 possible with C headers because they are fragments of programs that have
2919 less specific syntactic or semantic rules.
2921 The other major difference is the requirement for running the binder,
2922 which performs two important functions. First, it checks for
2923 consistency. In C or C++, the only defense against assembling
2924 inconsistent programs lies outside the compiler, in a makefile, for
2925 example. The binder satisfies the Ada requirement that it be impossible
2926 to construct an inconsistent program when the compiler is used in normal
2927 mode.
2929 @cindex Elaboration order control
2930 The other important function of the binder is to deal with elaboration
2931 issues. There are also elaboration issues in C++ that are handled
2932 automatically. This automatic handling has the advantage of being
2933 simpler to use, but the C++ programmer has no control over elaboration.
2934 Where @code{gnatbind} might complain there was no valid order of
2935 elaboration, a C++ compiler would simply construct a program that
2936 malfunctioned at run time.
2938 @node Comparison between GNAT and Conventional Ada Library Models
2939 @section Comparison between GNAT and Conventional Ada Library Models
2941 @noindent
2942 This section is intended to be useful to Ada programmers who have
2943 previously used an Ada compiler implementing the traditional Ada library
2944 model, as described in the Ada 95 Language Reference Manual. If you
2945 have not used such a system, please go on to the next section.
2947 @cindex GNAT library
2948 In GNAT, there is no @dfn{library} in the normal sense. Instead, the set of
2949 source files themselves acts as the library. Compiling Ada programs does
2950 not generate any centralized information, but rather an object file and
2951 a ALI file, which are of interest only to the binder and linker.
2952 In a traditional system, the compiler reads information not only from
2953 the source file being compiled, but also from the centralized library.
2954 This means that the effect of a compilation depends on what has been
2955 previously compiled. In particular:
2957 @itemize @bullet
2958 @item
2959 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2960 to the version of the unit most recently compiled into the library.
2962 @item
2963 Inlining is effective only if the necessary body has already been
2964 compiled into the library.
2966 @item
2967 Compiling a unit may obsolete other units in the library.
2968 @end itemize
2970 @noindent
2971 In GNAT, compiling one unit never affects the compilation of any other
2972 units because the compiler reads only source files. Only changes to source
2973 files can affect the results of a compilation. In particular:
2975 @itemize @bullet
2976 @item
2977 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
2978 to the source version of the unit that is currently accessible to the
2979 compiler.
2981 @item
2982 @cindex Inlining
2983 Inlining requires the appropriate source files for the package or
2984 subprogram bodies to be available to the compiler. Inlining is always
2985 effective, independent of the order in which units are complied.
2987 @item
2988 Compiling a unit never affects any other compilations. The editing of
2989 sources may cause previous compilations to be out of date if they
2990 depended on the source file being modified.
2991 @end itemize
2993 @noindent
2994 The most important result of these differences is that order of compilation
2995 is never significant in GNAT. There is no situation in which one is
2996 required to do one compilation before another. What shows up as order of
2997 compilation requirements in the traditional Ada library becomes, in
2998 GNAT, simple source dependencies; in other words, there is only a set
2999 of rules saying what source files must be present when a file is
3000 compiled.
3002 @node Compiling Using gcc
3003 @chapter Compiling Using @code{gcc}
3005 @noindent
3006 This chapter discusses how to compile Ada programs using the @code{gcc}
3007 command. It also describes the set of switches
3008 that can be used to control the behavior of the compiler.
3009 @menu
3010 * Compiling Programs::
3011 * Switches for gcc::
3012 * Search Paths and the Run-Time Library (RTL)::
3013 * Order of Compilation Issues::
3014 * Examples::
3015 @end menu
3017 @node Compiling Programs
3018 @section Compiling Programs
3020 @noindent
3021 The first step in creating an executable program is to compile the units
3022 of the program using the @code{gcc} command. You must compile the
3023 following files:
3025 @itemize @bullet
3026 @item
3027 the body file (@file{.adb}) for a library level subprogram or generic
3028 subprogram
3030 @item
3031 the spec file (@file{.ads}) for a library level package or generic
3032 package that has no body
3034 @item
3035 the body file (@file{.adb}) for a library level package
3036 or generic package that has a body
3038 @end itemize
3040 @noindent
3041 You need @emph{not} compile the following files
3043 @itemize @bullet
3045 @item
3046 the spec of a library unit which has a body
3048 @item
3049 subunits
3050 @end itemize
3052 @noindent
3053 because they are compiled as part of compiling related units. GNAT
3054 package specs
3055 when the corresponding body is compiled, and subunits when the parent is
3056 compiled.
3057 @cindex No code generated
3058 If you attempt to compile any of these files, you will get one of the
3059 following error messages (where fff is the name of the file you compiled):
3061 @smallexample
3062 No code generated for file @var{fff} (@var{package spec})
3063 No code generated for file @var{fff} (@var{subunit})
3064 @end smallexample
3066 @noindent
3067 The basic command for compiling a file containing an Ada unit is
3069 @smallexample
3070 $ gcc -c [@var{switches}] @file{file name}
3071 @end smallexample
3073 @noindent
3074 where @var{file name} is the name of the Ada file (usually
3075 having an extension
3076 @file{.ads} for a spec or @file{.adb} for a body).
3077 @ifclear vms
3078 You specify the
3079 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
3080 @end ifclear
3081 The result of a successful compilation is an object file, which has the
3082 same name as the source file but an extension of @file{.o} and an Ada
3083 Library Information (ALI) file, which also has the same name as the
3084 source file, but with @file{.ali} as the extension. GNAT creates these
3085 two output files in the current directory, but you may specify a source
3086 file in any directory using an absolute or relative path specification
3087 containing the directory information.
3089 @findex gnat1
3090 @code{gcc} is actually a driver program that looks at the extensions of
3091 the file arguments and loads the appropriate compiler. For example, the
3092 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3093 These programs are in directories known to the driver program (in some
3094 configurations via environment variables you set), but need not be in
3095 your path. The @code{gcc} driver also calls the assembler and any other
3096 utilities needed to complete the generation of the required object
3097 files.
3099 It is possible to supply several file names on the same @code{gcc}
3100 command. This causes @code{gcc} to call the appropriate compiler for
3101 each file. For example, the following command lists three separate
3102 files to be compiled:
3104 @smallexample
3105 $ gcc -c x.adb y.adb z.c
3106 @end smallexample
3108 @noindent
3109 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3110 @file{y.adb}, and @code{cc1} (the C compiler) once to compile @file{z.c}.
3111 The compiler generates three object files @file{x.o}, @file{y.o} and
3112 @file{z.o} and the two ALI files @file{x.ali} and @file{y.ali} from the
3113 Ada compilations. Any switches apply to all the files ^listed,^listed.^
3114 @ifclear vms
3115 except for
3116 @option{-gnat@var{x}} switches, which apply only to Ada compilations.
3117 @end ifclear
3119 @node Switches for gcc
3120 @section Switches for @code{gcc}
3122 @noindent
3123 The @code{gcc} command accepts switches that control the
3124 compilation process. These switches are fully described in this section.
3125 First we briefly list all the switches, in alphabetical order, then we
3126 describe the switches in more detail in functionally grouped sections.
3128 @menu
3129 * Output and Error Message Control::
3130 * Debugging and Assertion Control::
3131 * Run-Time Checks::
3132 * Stack Overflow Checking::
3133 * Run-Time Control::
3134 * Validity Checking::
3135 * Style Checking::
3136 * Using gcc for Syntax Checking::
3137 * Using gcc for Semantic Checking::
3138 * Compiling Ada 83 Programs::
3139 * Character Set Control::
3140 * File Naming Control::
3141 * Subprogram Inlining Control::
3142 * Auxiliary Output Control::
3143 * Debugging Control::
3144 * Units to Sources Mapping Files::
3145 @end menu
3147 @table @code
3148 @ifclear vms
3149 @cindex @code{-b} (@code{gcc})
3150 @item -b @var{target}
3151 Compile your program to run on @var{target}, which is the name of a
3152 system configuration. You must have a GNAT cross-compiler built if
3153 @var{target} is not the same as your host system.
3155 @item -B@var{dir}
3156 @cindex @code{-B} (@code{gcc})
3157 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3158 from @var{dir} instead of the default location. Only use this switch
3159 when multiple versions of the GNAT compiler are available. See the
3160 @code{gcc} manual page for further details. You would normally use the
3161 @code{-b} or @code{-V} switch instead.
3163 @item -c
3164 @cindex @code{-c} (@code{gcc})
3165 Compile. Always use this switch when compiling Ada programs.
3167 Note: for some other languages when using @code{gcc}, notably in
3168 the case of C and C++, it is possible to use
3169 use @code{gcc} without a @code{-c} switch to
3170 compile and link in one step. In the case of GNAT, you
3171 cannot use this approach, because the binder must be run
3172 and @code{gcc} cannot be used to run the GNAT binder.
3173 @end ifclear
3175 @item ^-g^/DEBUG^
3176 @cindex @code{^-g^/DEBUG^} (@code{gcc})
3177 Generate debugging information. This information is stored in the object
3178 file and copied from there to the final executable file by the linker,
3179 where it can be read by the debugger. You must use the
3180 @code{^-g^/DEBUG^} switch if you plan on using the debugger.
3182 @item ^-I^/SEARCH=^@var{dir}
3183 @cindex @code{^-I^/SEARCH^} (@code{gcc})
3184 @cindex RTL
3185 Direct GNAT to search the @var{dir} directory for source files needed by
3186 the current compilation
3187 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3189 @item ^-I-^/NOCURRENT_DIRECTORY^
3190 @cindex @code{^-I-^/NOCURRENT_DIRECTORY^} (@code{gcc})
3191 @cindex RTL
3192 Except for the source file named in the command line, do not look for source files
3193 in the directory containing the source file named in the command line
3194 (@pxref{Search Paths and the Run-Time Library (RTL)}).
3196 @ifclear vms
3197 @item -o @var{file}
3198 @cindex @code{-o} (@code{gcc})
3199 This switch is used in @code{gcc} to redirect the generated object file
3200 and its associated ALI file. Beware of this switch with GNAT, because it may
3201 cause the object file and ALI file to have different names which in turn
3202 may confuse the binder and the linker.
3203 @end ifclear
3205 @ifclear vms
3206 @item -O[@var{n}]
3207 @cindex @code{-O} (@code{gcc})
3208 @var{n} controls the optimization level.
3210 @table @asis
3211 @item n = 0
3212 No optimization, the default setting if no @code{-O} appears
3214 @item n = 1
3215 Normal optimization, the default if you specify @code{-O} without
3216 an operand.
3218 @item n = 2
3219 Extensive optimization
3221 @item n = 3
3222 Extensive optimization with automatic inlining. This applies only to
3223 inlining within a unit. For details on control of inter-unit inlining
3224 see @xref{Subprogram Inlining Control}.
3225 @end table
3226 @end ifclear
3228 @ifset vms
3229 @item  /NOOPTIMIZE (default)
3230 @itemx /OPTIMIZE[=(keyword[,...])]
3231 Selects the level of optimization for your program. The supported
3232 keywords are as follows:
3233 @table @code
3234 @item   ALL (default)
3235 Perform most optimizations, including those that
3236 be expensive.
3238 @item   NONE
3239 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
3241 @item SOME
3242 Perform some optimizations, but omit ones that are costly.
3244 @item   DEVELOPMENT
3245 Same as @code{SOME}.
3247 @item   INLINING
3248 Full optimization, and also attempt automatic inlining of small
3249 subprograms within a unit (@pxref{Inlining of Subprograms}).
3251 @item   UNROLL_LOOPS
3252 Try to unroll loops. This keyword may be specified together with
3253 any keyword above other than @code{NONE}. Loop unrolling
3254 usually, but not always, improves the performance of programs.
3255 @end table
3256 @end ifset
3258 @item --RTS=@var{rts-path}
3259 @cindex @code{--RTS} (@code{gcc})
3260 Specifies the default location of the runtime library. Same meaning as the
3261 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
3263 @item ^-S^/ASM^
3264 @cindex @code{^-S^/ASM^} (@code{gcc})
3265 ^Used in place of @code{-c} to^Used to^
3266 cause the assembler source file to be
3267 generated, using @file{^.s^.S^} as the extension,
3268 instead of the object file.
3269 This may be useful if you need to examine the generated assembly code.
3271 @item ^-v^/VERBOSE^
3272 @cindex @code{^-v^/VERBOSE^} (@code{gcc})
3273 Show commands generated by the @code{gcc} driver. Normally used only for
3274 debugging purposes or if you need to be sure what version of the
3275 compiler you are executing.
3277 @ifclear vms
3278 @item -V @var{ver}
3279 @cindex @code{-V} (@code{gcc})
3280 Execute @var{ver} version of the compiler. This is the @code{gcc}
3281 version, not the GNAT version.
3282 @end ifclear
3284 @item -gnata
3285 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3286 activated.
3288 @item -gnatA
3289 Avoid processing @file{gnat.adc}. If a gnat.adc file is present, it will be ignored.
3291 @item -gnatb
3292 Generate brief messages to @file{stderr} even if verbose mode set.
3294 @item -gnatc
3295 Check syntax and semantics only (no code generation attempted).
3297 @item -gnatC
3298 Compress debug information and external symbol name table entries.
3300 @item -gnatD
3301 Output expanded source files for source level debugging. This switch
3302 also suppress generation of cross-reference information (see -gnatx).
3304 @item -gnatec@var{path}
3305 Specify a configuration pragma file. (see @ref{The Configuration Pragmas Files})
3307 @item -gnatem@var{path}
3308 Specify a mapping file. (see @ref{Units to Sources Mapping Files})
3310 @item -gnatE
3311 Full dynamic elaboration checks.
3313 @item -gnatf
3314 Full errors. Multiple errors per line, all undefined references.
3316 @item -gnatF
3317 Externals names are folded to all uppercase.
3319 @item -gnatg
3320 Internal GNAT implementation mode. This should not be used for
3321 applications programs, it is intended only for use by the compiler
3322 and its run-time library. For documentation, see the GNAT sources.
3324 @item -gnatG
3325 List generated expanded code in source form.
3327 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3328 Identifier character set
3329 @ifclear vms
3330 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3331 @end ifclear
3332 @ifset vms
3333 For details of the possible selections for @var{c},
3334 see @xref{Character Set Control}.
3335 @end ifset
3337 @item ^-gnath^/HELP^
3338 Output usage information. The output is written to @file{stdout}.
3340 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
3341 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3343 @item -gnatl
3344 Output full source listing with embedded error messages.
3346 @item -gnatm^^=^@var{n}
3347 Limit number of detected errors to @var{n} (1-999).
3349 @item -gnatn
3350 Activate inlining across unit boundaries for subprograms for which
3351 pragma @code{inline} is specified.
3353 @item -gnatN
3354 Activate front end inlining.
3356 @item ^-fno-inline^/INLINE=SUPPRESS^
3357 Suppresses all inlining, even if other optimization or inlining switches
3358 are set.
3360 @ifclear vms
3361 @item -fstack-check
3362 Activates stack checking. See separate section on stack checking for
3363 details of the use of this option.
3364 @end ifclear
3366 @item -gnato
3367 Enable numeric overflow checking (which is not normally enabled by
3368 default). Not that division by zero is a separate check that is not
3369 controlled by this switch (division by zero checking is on by default).
3371 @item -gnatp
3372 Suppress all checks.
3374 @item -gnatq
3375 Don't quit; try semantics, even if parse errors.
3377 @item -gnatQ
3378 Don't quit; generate @file{ali} and tree files even if illegalities.
3380 @item -gnatP
3381 Enable polling. This is required on some systems (notably Windows NT) to
3382 obtain asynchronous abort and asynchronous transfer of control capability.
3383 See the description of pragma Polling in the GNAT Reference Manual for
3384 full details.
3386 @item -gnatR[0/1/2/3][s]
3387 Output representation information for declared types and objects.
3389 @item -gnats
3390 Syntax check only.
3392 @item -gnatt
3393 Tree output file to be generated.
3395 @item -gnatT nnn
3396 Set time slice to specified number of microseconds
3398 @item -gnatu
3399 List units for this compilation.
3401 @item -gnatU
3402 Tag all error messages with the unique string "error:"
3404 @item -gnatv
3405 Verbose mode. Full error output with source lines to @file{stdout}.
3407 @item -gnatV
3408 Control level of validity checking. See separate section describing
3409 this feature.
3411 @item ^-gnatwxxx^/WARNINGS=^@var{xxx}
3412 Warning mode where
3413 @var{xxx} is a string of options describing the exact warnings that
3414 are enabled or disabled. See separate section on warning control.
3416 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
3417 Wide character encoding method
3418 @ifclear vms
3419 (@var{e}=n/h/u/s/e/8).
3420 @end ifclear
3421 @ifset vms
3422 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
3423 @end ifset
3425 @item -gnatx
3426 Suppress generation of cross-reference information.
3428 @item ^-gnaty^/STYLE_CHECKS=(option,option..)^
3429 Enable built-in style checks. See separate section describing this feature.
3431 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
3432 Distribution stub generation and compilation
3433 @ifclear vms
3434 (@var{m}=r/c for receiver/caller stubs).
3435 @end ifclear
3436 @ifset vms
3437 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
3438 to be generated and compiled).
3439 @end ifset
3441 @item -gnat83
3442 Enforce Ada 83 restrictions.
3444 @ifclear vms
3445 @item -pass-exit-codes
3446 Catch exit codes from the compiler and use the most meaningful as
3447 exit status.
3448 @end ifclear
3449 @end table
3451 @ifclear vms
3452 You may combine a sequence of GNAT switches into a single switch. For
3453 example, the combined switch
3455 @cindex Combining GNAT switches
3456 @smallexample
3457 -gnatofi3
3458 @end smallexample
3460 @noindent
3461 is equivalent to specifying the following sequence of switches:
3463 @smallexample
3464 -gnato -gnatf -gnati3
3465 @end smallexample
3466 @end ifclear
3468 @noindent
3469 The following restrictions apply to the combination of switches
3470 in this manner:
3472 @itemize @bullet
3473 @item
3474 The switch @option{-gnatc} if combined with other switches must come
3475 first in the string.
3477 @item
3478 The switch @option{-gnats} if combined with other switches must come
3479 first in the string.
3481 @item
3482 Once a "y" appears in the string (that is a use of the @option{-gnaty}
3483 switch), then all further characters in the switch are interpreted
3484 as style modifiers (see description of @option{-gnaty}).
3486 @item
3487 Once a "d" appears in the string (that is a use of the @option{-gnatd}
3488 switch), then all further characters in the switch are interpreted
3489 as debug flags (see description of @option{-gnatd}).
3491 @item
3492 Once a "w" appears in the string (that is a use of the @option{-gnatw}
3493 switch), then all further characters in the switch are interpreted
3494 as warning mode modifiers (see description of @option{-gnatw}).
3496 @item
3497 Once a "V" appears in the string (that is a use of the @option{-gnatV}
3498 switch), then all further characters in the switch are interpreted
3499 as validity checking options (see description of @option{-gnatV}).
3501 @end itemize
3503 @node Output and Error Message Control
3504 @subsection Output and Error Message Control
3505 @findex stderr
3507 @noindent
3508 The standard default format for error messages is called "brief format."
3509 Brief format messages are written to @file{stderr} (the standard error
3510 file) and have the following form:
3512 @smallexample
3513 @iftex
3514 @leftskip=.7cm
3515 @end iftex
3516 e.adb:3:04: Incorrect spelling of keyword "function"
3517 e.adb:4:20: ";" should be "is"
3518 @end smallexample
3520 @noindent
3521 The first integer after the file name is the line number in the file,
3522 and the second integer is the column number within the line.
3523 @code{glide} can parse the error messages
3524 and point to the referenced character.
3525 The following switches provide control over the error message
3526 format:
3528 @table @code
3529 @item -gnatv
3530 @cindex @option{-gnatv} (@code{gcc})
3531 @findex stdout
3532 @ifclear vms
3533 The v stands for verbose.
3534 @end ifclear
3535 The effect of this setting is to write long-format error
3536 messages to @file{stdout} (the standard output file.
3537 The same program compiled with the
3538 @option{-gnatv} switch would generate:
3540 @smallexample
3541 @group
3542 @cartouche
3543 3. funcion X (Q : Integer)
3544    |
3545 >>> Incorrect spelling of keyword "function"
3546 4. return Integer;
3547                  |
3548 >>> ";" should be "is"
3549 @end cartouche
3550 @end group
3551 @end smallexample
3553 @noindent
3554 The vertical bar indicates the location of the error, and the @samp{>>>}
3555 prefix can be used to search for error messages. When this switch is
3556 used the only source lines output are those with errors.
3558 @item -gnatl
3559 @cindex @option{-gnatl} (@code{gcc})
3560 @ifclear vms
3561 The @code{l} stands for list.
3562 @end ifclear
3563 This switch causes a full listing of
3564 the file to be generated. The output might look as follows:
3566 @smallexample
3567 @group
3568 @cartouche
3569  1. procedure E is
3570  2.    V : Integer;
3571  3.    funcion X (Q : Integer)
3572        |
3573     >>> Incorrect spelling of keyword "function"
3574  4.     return Integer;
3575                       |
3576     >>> ";" should be "is"
3577  5.    begin
3578  6.       return Q + Q;
3579  7.    end;
3580  8. begin
3581  9.    V := X + X;
3582 10.end E;
3583 @end cartouche
3584 @end group
3585 @end smallexample
3587 @noindent
3588 @findex stderr
3589 When you specify the @option{-gnatv} or @option{-gnatl} switches and
3590 standard output is redirected, a brief summary is written to
3591 @file{stderr} (standard error) giving the number of error messages and
3592 warning messages generated.
3594 @item -gnatU
3595 @cindex @option{-gnatU} (@code{gcc})
3596 This switch forces all error messages to be preceded by the unique
3597 string "error:". This means that error messages take a few more
3598 characters in space, but allows easy searching for and identification
3599 of error messages.
3601 @item -gnatb
3602 @cindex @option{-gnatb} (@code{gcc})
3603 @ifclear vms
3604 The @code{b} stands for brief.
3605 @end ifclear
3606 This switch causes GNAT to generate the
3607 brief format error messages to @file{stderr} (the standard error
3608 file) as well as the verbose
3609 format message or full listing (which as usual is written to
3610 @file{stdout} (the standard output file).
3612 @item -gnatm^^=^@var{n}
3613 @cindex @option{-gnatm} (@code{gcc})
3614 @ifclear vms
3615 The @code{m} stands for maximum.
3616 @end ifclear
3617 @var{n} is a decimal integer in the
3618 range of 1 to 999 and limits the number of error messages to be
3619 generated. For example, using @option{-gnatm2} might yield
3621 @smallexample
3622 @iftex
3623 @leftskip=.7cm
3624 @end iftex
3625 e.adb:3:04: Incorrect spelling of keyword "function"
3626 e.adb:5:35: missing ".."
3627 fatal error: maximum errors reached
3628 compilation abandoned
3629 @end smallexample
3631 @item -gnatf
3632 @cindex @option{-gnatf} (@code{gcc})
3633 @cindex Error messages, suppressing
3634 @ifclear vms
3635 The @code{f} stands for full.
3636 @end ifclear
3637 Normally, the compiler suppresses error messages that are likely to be
3638 redundant. This switch causes all error
3639 messages to be generated. In particular, in the case of
3640 references to undefined variables. If a given variable is referenced
3641 several times, the normal format of messages is
3642 @smallexample
3643 @iftex
3644 @leftskip=.7cm
3645 @end iftex
3646 e.adb:7:07: "V" is undefined (more references follow)
3647 @end smallexample
3649 @noindent
3650 where the parenthetical comment warns that there are additional
3651 references to the variable @code{V}. Compiling the same program with the
3652 @option{-gnatf} switch yields
3654 @smallexample
3655 e.adb:7:07: "V" is undefined
3656 e.adb:8:07: "V" is undefined
3657 e.adb:8:12: "V" is undefined
3658 e.adb:8:16: "V" is undefined
3659 e.adb:9:07: "V" is undefined
3660 e.adb:9:12: "V" is undefined
3661 @end smallexample
3663 @item -gnatq
3664 @cindex @option{-gnatq} (@code{gcc})
3665 @ifclear vms
3666 The @code{q} stands for quit (really "don't quit").
3667 @end ifclear
3668 In normal operation mode, the compiler first parses the program and
3669 determines if there are any syntax errors. If there are, appropriate
3670 error messages are generated and compilation is immediately terminated.
3671 This switch tells
3672 GNAT to continue with semantic analysis even if syntax errors have been
3673 found. This may enable the detection of more errors in a single run. On
3674 the other hand, the semantic analyzer is more likely to encounter some
3675 internal fatal error when given a syntactically invalid tree.
3677 @item -gnatQ
3678 In normal operation mode, the @file{ali} file is not generated if any
3679 illegalities are detected in the program. The use of @option{-gnatQ} forces
3680 generation of the @file{ali} file. This file is marked as being in
3681 error, so it cannot be used for binding purposes, but it does contain
3682 reasonably complete cross-reference information, and thus may be useful
3683 for use by tools (e.g. semantic browsing tools or integrated development
3684 environments) that are driven from the @file{ali} file.
3686 In addition, if @option{-gnatt} is also specified, then the tree file is
3687 generated even if there are illegalities. It may be useful in this case
3688 to also specify @option{-gnatq} to ensure that full semantic processing
3689 occurs. The resulting tree file can be processed by ASIS, for the purpose
3690 of providing partial information about illegal units, but if the error
3691 causes the tree to be badly malformed, then ASIS may crash during the
3692 analysis.
3694 @end table
3696 @noindent
3697 In addition to error messages, which correspond to illegalities as defined
3698 in the Ada 95 Reference Manual, the compiler detects two kinds of warning
3699 situations.
3701 @cindex Warning messages
3702 First, the compiler considers some constructs suspicious and generates a
3703 warning message to alert you to a possible error. Second, if the
3704 compiler detects a situation that is sure to raise an exception at
3705 run time, it generates a warning message. The following shows an example
3706 of warning messages:
3707 @smallexample
3708 @iftex
3709 @leftskip=.2cm
3710 @end iftex
3711 e.adb:4:24: warning: creation of object may raise Storage_Error
3712 e.adb:10:17: warning: static value out of range
3713 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
3715 @end smallexample
3717 @noindent
3718 GNAT considers a large number of situations as appropriate
3719 for the generation of warning messages. As always, warnings are not
3720 definite indications of errors. For example, if you do an out-of-range
3721 assignment with the deliberate intention of raising a
3722 @code{Constraint_Error} exception, then the warning that may be
3723 issued does not indicate an error. Some of the situations for which GNAT
3724 issues warnings (at least some of the time) are given in the following
3725 list, which is not necessarily complete.
3727 @itemize @bullet
3728 @item
3729 Possible infinitely recursive calls
3731 @item
3732 Out-of-range values being assigned
3734 @item
3735 Possible order of elaboration problems
3737 @item
3738 Unreachable code
3740 @item
3741 Fixed-point type declarations with a null range
3743 @item
3744 Variables that are never assigned a value
3746 @item
3747 Variables that are referenced before being initialized
3749 @item
3750 Task entries with no corresponding accept statement
3752 @item
3753 Duplicate accepts for the same task entry in a select
3755 @item
3756 Objects that take too much storage
3758 @item
3759 Unchecked conversion between types of differing sizes
3761 @item
3762 Missing return statements along some execution paths in a function
3764 @item
3765 Incorrect (unrecognized) pragmas
3767 @item
3768 Incorrect external names
3770 @item
3771 Allocation from empty storage pool
3773 @item
3774 Potentially blocking operations in protected types
3776 @item
3777 Suspicious parenthesization of expressions
3779 @item
3780 Mismatching bounds in an aggregate
3782 @item
3783 Attempt to return local value by reference
3785 @item
3786 Unrecognized pragmas
3788 @item
3789 Premature instantiation of a generic body
3791 @item
3792 Attempt to pack aliased components
3794 @item
3795 Out of bounds array subscripts
3797 @item
3798 Wrong length on string assignment
3800 @item
3801 Violations of style rules if style checking is enabled
3803 @item
3804 Unused with clauses
3806 @item
3807 Bit_Order usage that does not have any effect
3809 @item
3810 Compile time biased rounding of floating-point constant
3812 @item
3813 Standard.Duration used to resolve universal fixed expression
3815 @item
3816 Dereference of possibly null value
3818 @item
3819 Declaration that is likely to cause storage error
3821 @item
3822 Internal GNAT unit with'ed by application unit
3824 @item
3825 Values known to be out of range at compile time
3827 @item
3828 Unreferenced labels and variables
3830 @item
3831 Address overlays that could clobber memory
3833 @item
3834 Unexpected initialization when address clause present
3836 @item
3837 Bad alignment for address clause
3839 @item
3840 Useless type conversions
3842 @item
3843 Redundant assignment statements
3845 @item
3846 Accidental hiding of name by child unit
3848 @item
3849 Unreachable code
3851 @item
3852 Access before elaboration detected at compile time
3854 @item
3855 A range in a @code{for} loop that is known to be null or might be null
3857 @end itemize
3859 @noindent
3860 The following switches are available to control the handling of
3861 warning messages:
3863 @table @code
3864 @item -gnatwa (activate all optional errors)
3865 @cindex @option{-gnatwa} (@code{gcc})
3866 This switch activates most optional warning messages, see remaining list
3867 in this section for details on optional warning messages that can be
3868 individually controlled. The warnings that are not turned on by this
3869 switch are @option{-gnatwb} (biased rounding),
3870 @option{-gnatwd} (implicit dereferencing),
3871 and @option{-gnatwh} (hiding). All other optional warnings are
3872 turned on.
3874 @item -gnatwA (suppress all optional errors)
3875 @cindex @option{-gnatwA} (@code{gcc})
3876 This switch suppresses all optional warning messages, see remaining list
3877 in this section for details on optional warning messages that can be
3878 individually controlled.
3880 @item -gnatwb (activate warnings on biased rounding)
3881 @cindex @option{-gnatwb} (@code{gcc})
3882 @cindex Rounding, biased
3883 @cindex Biased rounding
3884 If a static floating-point expression has a value that is exactly half
3885 way between two adjacent machine numbers, then the rules of Ada
3886 (Ada Reference Manual, section 4.9(38)) require that this rounding
3887 be done away from zero, even if the normal unbiased rounding rules
3888 at run time would require rounding towards zero. This warning message
3889 alerts you to such instances where compile-time rounding and run-time
3890 rounding are not equivalent. If it is important to get proper run-time
3891 rounding, then you can force this by making one of the operands into
3892 a variable. The default is that such warnings are not generated.
3893 Note that @option{-gnatwa} does not affect the setting of
3894 this warning option.
3896 @item -gnatwB (suppress warnings on biased rounding)
3897 @cindex @option{-gnatwB} (@code{gcc})
3898 This switch disables warnings on biased rounding.
3900 @item -gnatwc (activate warnings on conditionals)
3901 @cindex @option{-gnatwc} (@code{gcc})
3902 @cindex Conditionals, constant
3903 This switch activates warnings for conditional expressions used in
3904 tests that are known to be True or False at compile time. The default
3905 is that such warnings are not generated.
3906 This warning can also be turned on using @option{-gnatwa}.
3908 @item -gnatwC (suppress warnings on conditionals)
3909 @cindex @option{-gnatwC} (@code{gcc})
3910 This switch suppresses warnings for conditional expressions used in
3911 tests that are known to be True or False at compile time.
3913 @item -gnatwd (activate warnings on implicit dereferencing)
3914 @cindex @option{-gnatwd} (@code{gcc})
3915 If this switch is set, then the use of a prefix of an access type
3916 in an indexed component, slice, or selected component without an
3917 explicit @code{.all} will generate a warning. With this warning
3918 enabled, access checks occur only at points where an explicit
3919 @code{.all} appears in the source code (assuming no warnings are
3920 generated as a result of this switch). The default is that such
3921 warnings are not generated.
3922 Note that @option{-gnatwa} does not affect the setting of
3923 this warning option.
3925 @item -gnatwD (suppress warnings on implicit dereferencing)
3926 @cindex @option{-gnatwD} (@code{gcc})
3927 @cindex Implicit dereferencing
3928 @cindex Dereferencing, implicit
3929 This switch suppresses warnings for implicit deferences in
3930 indexed components, slices, and selected components.
3932 @item -gnatwe (treat warnings as errors)
3933 @cindex @option{-gnatwe} (@code{gcc})
3934 @cindex Warnings, treat as error
3935 This switch causes warning messages to be treated as errors.
3936 The warning string still appears, but the warning messages are counted
3937 as errors, and prevent the generation of an object file.
3939 @item -gnatwf (activate warnings on unreferenced formals)
3940 @cindex @option{-gnatwf} (@code{gcc})
3941 @cindex Formals, unreferenced
3942 This switch causes a warning to be generated if a formal parameter
3943 is not referenced in the body of the subprogram. This warning can
3944 also be turned on using @option{-gnatwa} or @option{-gnatwu}.
3946 @item -gnatwF (suppress warnings on unreferenced formals)
3947 @cindex @option{-gnatwF} (@code{gcc})
3948 This switch suppresses warnings for unreferenced formal
3949 parameters. Note that the
3950 combination @option{-gnatwu} followed by @option{-gnatwF} has the
3951 effect of warning on unreferenced entities other than subprogram
3952 formals.
3954 @item -gnatwh (activate warnings on hiding)
3955 @cindex @option{-gnatwh} (@code{gcc})
3956 @cindex Hiding of Declarations
3957 This switch activates warnings on hiding declarations.
3958 A declaration is considered hiding
3959 if it is for a non-overloadable entity, and it declares an entity with the
3960 same name as some other entity that is directly or use-visible. The default
3961 is that such warnings are not generated.
3962 Note that @option{-gnatwa} does not affect the setting of this warning option.
3964 @item -gnatwH (suppress warnings on hiding)
3965 @cindex @option{-gnatwH} (@code{gcc})
3966 This switch suppresses warnings on hiding declarations.
3968 @item -gnatwi (activate warnings on implementation units).
3969 @cindex @option{-gnatwi} (@code{gcc})
3970 This switch activates warnings for a @code{with} of an internal GNAT
3971 implementation unit, defined as any unit from the @code{Ada},
3972 @code{Interfaces}, @code{GNAT},
3973 ^^@code{DEC},^ or @code{System}
3974 hierarchies that is not
3975 documented in either the Ada Reference Manual or the GNAT
3976 Programmer's Reference Manual. Such units are intended only
3977 for internal implementation purposes and should not be @code{with}'ed
3978 by user programs. The default is that such warnings are generated
3979 This warning can also be turned on using @option{-gnatwa}.
3981 @item -gnatwI (disable warnings on implementation units).
3982 @cindex @option{-gnatwI} (@code{gcc})
3983 This switch disables warnings for a @code{with} of an internal GNAT
3984 implementation unit.
3986 @item -gnatwl (activate warnings on elaboration pragmas)
3987 @cindex @option{-gnatwl} (@code{gcc})
3988 @cindex Elaboration, warnings
3989 This switch activates warnings on missing pragma Elaborate_All statements.
3990 See the section in this guide on elaboration checking for details on
3991 when such pragma should be used. The default is that such warnings
3992 are not generated.
3993 This warning can also be turned on using @option{-gnatwa}.
3995 @item -gnatwL (suppress warnings on elaboration pragmas)
3996 @cindex @option{-gnatwL} (@code{gcc})
3997 This switch suppresses warnings on missing pragma Elaborate_All statements.
3998 See the section in this guide on elaboration checking for details on
3999 when such pragma should be used.
4001 @item -gnatwo (activate warnings on address clause overlays)
4002 @cindex @option{-gnatwo} (@code{gcc})
4003 @cindex Address Clauses, warnings
4004 This switch activates warnings for possibly unintended initialization
4005 effects of defining address clauses that cause one variable to overlap
4006 another. The default is that such warnings are generated.
4007 This warning can also be turned on using @option{-gnatwa}.
4009 @item -gnatwO (suppress warnings on address clause overlays)
4010 @cindex @option{-gnatwO} (@code{gcc})
4011 This switch suppresses warnings on possibly unintended initialization
4012 effects of defining address clauses that cause one variable to overlap
4013 another.
4015 @item -gnatwp (activate warnings on ineffective pragma Inlines)
4016 @cindex @option{-gnatwp} (@code{gcc})
4017 @cindex Inlining, warnings
4018 This switch activates warnings for failure of front end inlining
4019 (activated by @option{-gnatN}) to inline a particular call. There are
4020 many reasons for not being able to inline a call, including most
4021 commonly that the call is too complex to inline.
4022 This warning can also be turned on using @option{-gnatwa}.
4024 @item -gnatwP (suppress warnings on ineffective pragma Inlines)
4025 @cindex @option{-gnatwP} (@code{gcc})
4026 This switch suppresses warnings on ineffective pragma Inlines. If the
4027 inlining mechanism cannot inline a call, it will simply ignore the
4028 request silently.
4030 @item -gnatwr (activate warnings on redundant constructs)
4031 @cindex @option{-gnatwr} (@code{gcc})
4032 This switch activates warnings for redundant constructs. The following
4033 is the current list of constructs regarded as redundant:
4034 This warning can also be turned on using @option{-gnatwa}.
4036 @itemize @bullet
4037 @item
4038 Assignment of an item to itself.
4039 @item
4040 Type conversion that converts an expression to its own type.
4041 @item
4042 Use of the attribute @code{Base} where @code{typ'Base} is the same
4043 as @code{typ}.
4044 @item
4045 Use of pragma @code{Pack} when all components are placed by a record
4046 representation clause.
4047 @end itemize
4049 @item -gnatwR (suppress warnings on redundant constructs)
4050 @cindex @option{-gnatwR} (@code{gcc})
4051 This switch suppresses warnings for redundant constructs.
4053 @item -gnatws (suppress all warnings)
4054 @cindex @option{-gnatws} (@code{gcc})
4055 This switch completely suppresses the
4056 output of all warning messages from the GNAT front end.
4057 Note that it does not suppress warnings from the @code{gcc} back end.
4058 To suppress these back end warnings as well, use the switch @code{-w}
4059 in addition to @option{-gnatws}.
4061 @item -gnatwu (activate warnings on unused entities)
4062 @cindex @option{-gnatwu} (@code{gcc})
4063 This switch activates warnings to be generated for entities that
4064 are defined but not referenced, and for units that are @code{with}'ed
4065 and not
4066 referenced. In the case of packages, a warning is also generated if
4067 no entities in the package are referenced. This means that if the package
4068 is referenced but the only references are in @code{use}
4069 clauses or @code{renames}
4070 declarations, a warning is still generated. A warning is also generated
4071 for a generic package that is @code{with}'ed but never instantiated.
4072 In the case where a package or subprogram body is compiled, and there
4073 is a @code{with} on the corresponding spec
4074 that is only referenced in the body,
4075 a warning is also generated, noting that the
4076 @code{with} can be moved to the body. The default is that
4077 such warnings are not generated.
4078 This switch also activates warnings on unreferenced formals
4079 (it is includes the effect of @option{-gnatwf}).
4080 This warning can also be turned on using @option{-gnatwa}.
4082 @item -gnatwU (suppress warnings on unused entities)
4083 @cindex @option{-gnatwU} (@code{gcc})
4084 This switch suppresses warnings for unused entities and packages.
4085 It also turns off warnings on unreferenced formals (and thus includes
4086 the effect of @option{-gnatwF}).
4088 @noindent
4089 A string of warning parameters can be used in the same parameter. For example:
4091 @smallexample
4092 -gnatwaLe
4093 @end smallexample
4095 @noindent
4096 Would turn on all optional warnings except for elaboration pragma warnings,
4097 and also specify that warnings should be treated as errors.
4099 @item -w
4100 @cindex @code{-w}
4101 This switch suppresses warnings from the @code{gcc} backend. It may be
4102 used in conjunction with @option{-gnatws} to ensure that all warnings
4103 are suppressed during the entire compilation process.
4105 @end table
4107 @node Debugging and Assertion Control
4108 @subsection Debugging and Assertion Control
4110 @table @code
4111 @item -gnata
4112 @cindex @option{-gnata} (@code{gcc})
4113 @findex Assert
4114 @findex Debug
4115 @cindex Assertions
4117 @noindent
4118 The pragmas @code{Assert} and @code{Debug} normally have no effect and
4119 are ignored. This switch, where @samp{a} stands for assert, causes
4120 @code{Assert} and @code{Debug} pragmas to be activated.
4122 The pragmas have the form:
4124 @smallexample
4125 @group
4126 @cartouche
4127    @b{pragma} Assert (@var{Boolean-expression} [,
4128                       @var{static-string-expression}])
4129    @b{pragma} Debug (@var{procedure call})
4130 @end cartouche
4131 @end group
4132 @end smallexample
4134 @noindent
4135 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
4136 If the result is @code{True}, the pragma has no effect (other than
4137 possible side effects from evaluating the expression). If the result is
4138 @code{False}, the exception @code{Assert_Failure} declared in the package
4139 @code{System.Assertions} is
4140 raised (passing @var{static-string-expression}, if present, as the
4141 message associated with the exception). If no string expression is
4142 given the default is a string giving the file name and line number
4143 of the pragma.
4145 The @code{Debug} pragma causes @var{procedure} to be called. Note that
4146 @code{pragma Debug} may appear within a declaration sequence, allowing
4147 debugging procedures to be called between declarations.
4149 @ifset vms
4150 @item /DEBUG[=debug-level]
4151 @itemx  /NODEBUG
4152 Specifies how much debugging information is to be included in
4153 the resulting object file where 'debug-level' is one of the following:
4154 @table @code
4155 @item   TRACEBACK (default)
4156 Include both debugger symbol records and traceback
4157 the object file.
4158 @item   ALL
4159 Include both debugger symbol records and traceback in
4160 object file.
4161 @item   NONE
4162 Excludes both debugger symbol records and traceback
4163 the object file. Same as /NODEBUG.
4164 @item   SYMBOLS
4165 Includes only debugger symbol records in the object
4166 file. Note that this doesn't include traceback information.
4167 @end table
4168 @end ifset
4169 @end table
4171 @node Validity Checking
4172 @subsection Validity Checking
4173 @findex Validity Checking
4175 @noindent
4176 The Ada 95 Reference Manual has specific requirements for checking
4177 for invalid values. In particular, RM 13.9.1 requires that the
4178 evaluation of invalid values (for example from unchecked conversions),
4179 not result in erroneous execution. In GNAT, the result of such an
4180 evaluation in normal default mode is to either use the value
4181 unmodified, or to raise Constraint_Error in those cases where use
4182 of the unmodified value would cause erroneous execution. The cases
4183 where unmodified values might lead to erroneous execution are case
4184 statements (where a wild jump might result from an invalid value),
4185 and subscripts on the left hand side (where memory corruption could
4186 occur as a result of an invalid value).
4188 The @option{-gnatVx} switch allows more control over the validity checking
4189 mode. The @code{x} argument here is a string of letters which control which
4190 validity checks are performed in addition to the default checks described
4191 above.
4193 @itemize @bullet
4194 @item
4195 @option{-gnatVc} Validity checks for copies
4197 The right hand side of assignments, and the initializing values of
4198 object declarations are validity checked.
4200 @item
4201 @option{-gnatVd} Default (RM) validity checks
4203 Some validity checks are done by default following normal Ada semantics
4204 (RM 13.9.1 (9-11)).
4205 A check is done in case statements that the expression is within the range
4206 of the subtype. If it is not, Constraint_Error is raised.
4207 For assignments to array components, a check is done that the expression used
4208 as index is within the range. If it is not, Constraint_Error is raised.
4209 Both these validity checks may be turned off using switch @option{-gnatVD}.
4210 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
4211 switch @option{-gnatVd} will leave the checks turned on.
4212 Switch @option{-gnatVD} should be used only if you are sure that all such
4213 expressions have valid values. If you use this switch and invalid values
4214 are present, then the program is erroneous, and wild jumps or memory
4215 overwriting may occur.
4217 @item
4218 @option{-gnatVi} Validity checks for @code{in} mode parameters
4220 Arguments for parameters of mode @code{in} are validity checked in function
4221 and procedure calls at the point of call.
4223 @item
4224 @option{-gnatVm} Validity checks for @code{in out} mode parameters
4226 Arguments for parameters of mode @code{in out} are validity checked in
4227 procedure calls at the point of call. The @code{'m'} here stands for
4228 modify, since this concerns parameters that can be modified by the call.
4229 Note that there is no specific option to test @code{out} parameters,
4230 but any reference within the subprogram will be tested in the usual
4231 manner, and if an invalid value is copied back, any reference to it
4232 will be subject to validity checking.
4234 @item
4235 @option{-gnatVo} Validity checks for operator and attribute operands
4237 Arguments for predefined operators and attributes are validity checked.
4238 This includes all operators in package @code{Standard},
4239 the shift operators defined as intrinsic in package @code{Interfaces}
4240 and operands for attributes such as @code{Pos}.
4242 @item
4243 @option{-gnatVr} Validity checks for function returns
4245 The expression in @code{return} statements in functions is validity
4246 checked.
4248 @item
4249 @option{-gnatVs} Validity checks for subscripts
4251 All subscripts expressions are checked for validity, whether they appear
4252 on the right side or left side (in default mode only left side subscripts
4253 are validity checked).
4255 @item
4256 @option{-gnatVt} Validity checks for tests
4258 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
4259 statements are checked, as well as guard expressions in entry calls.
4261 @item
4262 @option{-gnatVf} Validity checks for floating-point values
4264 In the absence of this switch, validity checking occurs only for discrete
4265 values. If @option{-gnatVf} is specified, then validity checking also applies
4266 for floating-point values, and NaN's and infinities are considered invalid,
4267 as well as out of range values for constrained types. Note that this means
4268 that standard @code{IEEE} infinity mode is not allowed. The exact contexts
4269 in which floating-point values are checked depends on the setting of other
4270 options. For example @option{-gnatVif} or @option{-gnatVfi} (the order does
4271 not matter) specifies that floating-point parameters of mode @code{in} should
4272 be validity checked.
4274 @item
4275 @option{-gnatVa} All validity checks
4277 All the above validity checks are turned on. That is @option{-gnatVa} is
4278 equivalent to @code{gnatVcdfimorst}.
4280 @item
4281 @option{-gnatVn} No validity checks
4283 This switch turns off all validity checking, including the default checking
4284 for case statements and left hand side subscripts. Note that the use of
4285 the switch @option{-gnatp} supresses all run-time checks, including
4286 validity checks, and thus implies @option{-gnatVn}.
4288 @end itemize
4290 The @option{-gnatV} switch may be followed by a string of letters to turn on
4291 a series of validity checking options. For example, @option{-gnatVcr} specifies
4292 that in addition to the default validity checking, copies and function
4293 return expressions be validity checked. In order to make it easier to specify
4294 a set of options, the upper case letters @code{CDFIMORST} may be used to turn
4295 off the corresponding lower case option, so for example @option{-gnatVaM} turns
4296 on all validity checking options except for checking of @code{in out}
4297 procedure arguments.
4299 The specification of additional validity checking generates extra code (and
4300 in the case of @option{-gnatva} the code expansion can be substantial. However,
4301 these additional checks can be very useful in smoking out cases of
4302 uninitialized variables, incorrect use of unchecked conversion, and other
4303 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
4304 is useful in conjunction with the extra validity checking, since this
4305 ensures that wherever possible uninitialized variables have invalid values.
4307 See also the pragma @code{Validity_Checks} which allows modification of
4308 the validity checking mode at the program source level, and also allows for
4309 temporary disabling of validity checks.
4311 @node Style Checking
4312 @subsection Style Checking
4313 @findex Style checking
4315 @noindent
4316 The -gnaty@var{^x^(option,option,..)^} switch causes the compiler to
4317 enforce specified style rules. A limited set of style rules has been used
4318 in writing the GNAT sources themselves. This switch allows user programs
4319 to activate all or some of these checks. If the source program fails a
4320 specified style check, an appropriate warning message is given, preceded by
4321 the character sequence "(style)".
4322 @ifset vms
4323 (OPTION,OPTION,..) is a sequence of keywords
4324 @end ifset
4325 @ifclear vms
4326 The string @var{x} is a sequence of letters or digits
4327 @end ifclear
4328 indicating the particular style
4329 checks to be performed. The following checks are defined:
4331 @table @code
4332 @item 1-9 (specify indentation level)
4333 If a digit from 1-9 appears in the string after @option{-gnaty} then proper
4334 indentation is checked, with the digit indicating the indentation level
4335 required. The general style of required indentation is as specified by
4336 the examples in the Ada Reference Manual. Full line comments must be
4337 aligned with the @code{--} starting on a column that is a multiple of
4338 the alignment level.
4340 @item ^a^ATTRIBUTE^ (check attribute casing)
4341 If the ^letter a^word ATTRIBUTE^ appears in the string after @option{-gnaty} then
4342 attribute names, including the case of keywords such as @code{digits}
4343 used as attributes names, must be written in mixed case, that is, the
4344 initial letter and any letter following an underscore must be uppercase.
4345 All other letters must be lowercase.
4347 @item ^b^BLANKS^ (blanks not allowed at statement end)
4348 If the ^letter b^word BLANKS^ appears in the string after @option{-gnaty} then
4349 trailing blanks are not allowed at the end of statements. The purpose of this
4350 rule, together with h (no horizontal tabs), is to enforce a canonical format
4351 for the use of blanks to separate source tokens.
4353 @item ^c^COMMENTS^ (check comments)
4354 If the ^letter c^word COMMENTS^ appears in the string after @option{-gnaty} then
4355 comments must meet the following set of rules:
4357 @itemize @bullet
4359 @item
4360 The "--" that starts the column must either start in column one, or else
4361 at least one blank must precede this sequence.
4363 @item
4364 Comments that follow other tokens on a line must have at least one blank
4365 following the "--" at the start of the comment.
4367 @item
4368 Full line comments must have two blanks following the "--" that starts
4369 the comment, with the following exceptions.
4371 @item
4372 A line consisting only of the "--" characters, possibly preceded by blanks
4373 is permitted.
4375 @item
4376 A comment starting with "--x" where x is a special character is permitted.
4377 This alows proper processing of the output generated by specialized tools
4378 including @code{gnatprep} (where --! is used) and the SPARK annnotation
4379 language (where --# is used). For the purposes of this rule, a special
4380 character is defined as being in one of the ASCII ranges
4381 16#21#..16#2F# or 16#3A#..16#3F#.
4383 @item
4384 A line consisting entirely of minus signs, possibly preceded by blanks, is
4385 permitted. This allows the construction of box comments where lines of minus
4386 signs are used to form the top and bottom of the box.
4388 @item
4389 If a comment starts and ends with "--" is permitted as long as at least
4390 one blank follows the initial "--". Together with the preceding rule,
4391 this allows the construction of box comments, as shown in the following
4392 example:
4393 @smallexample
4394 ---------------------------
4395 -- This is a box comment --
4396 -- with two text lines.  --
4397 ---------------------------
4398 @end smallexample
4399 @end itemize
4401 @item ^e^END^ (check end/exit labels)
4402 If the ^letter e^word END^ appears in the string after @option{-gnaty} then
4403 optional labels on @code{end} statements ending subprograms and on
4404 @code{exit} statements exiting named loops, are required to be present.
4406 @item ^f^VTABS^ (no form feeds or vertical tabs)
4407 If the ^letter f^word VTABS^ appears in the string after @option{-gnaty} then
4408 neither form feeds nor vertical tab characters are not permitted
4409 in the source text.
4411 @item ^h^HTABS^ (no horizontal tabs)
4412 If the ^letter h^word HTABS^ appears in the string after @option{-gnaty} then
4413 horizontal tab characters are not permitted in the source text.
4414 Together with the b (no blanks at end of line) check, this
4415 enforces a canonical form for the use of blanks to separate
4416 source tokens.
4418 @item ^i^IF_THEN^ (check if-then layout)
4419 If the ^letter i^word IF_THEN^ appears in the string after @option{-gnaty},
4420 then the keyword @code{then} must appear either on the same
4421 line as corresponding @code{if}, or on a line on its own, lined
4422 up under the @code{if} with at least one non-blank line in between
4423 containing all or part of the condition to be tested.
4425 @item ^k^KEYWORD^ (check keyword casing)
4426 If the ^letter k^word KEYWORD^ appears in the string after @option{-gnaty} then
4427 all keywords must be in lower case (with the exception of keywords
4428 such as @code{digits} used as attribute names to which this check
4429 does not apply).
4431 @item ^l^LAYOUT^ (check layout)
4432 If the ^letter l^word LAYOUT^ appears in the string after @option{-gnaty} then
4433 layout of statement and declaration constructs must follow the
4434 recommendations in the Ada Reference Manual, as indicated by the
4435 form of the syntax rules. For example an @code{else} keyword must
4436 be lined up with the corresponding @code{if} keyword.
4438 There are two respects in which the style rule enforced by this check
4439 option are more liberal than those in the Ada Reference Manual. First
4440 in the case of record declarations, it is permissible to put the
4441 @code{record} keyword on the same line as the @code{type} keyword, and
4442 then the @code{end} in @code{end record} must line up under @code{type}.
4443 For example, either of the following two layouts is acceptable:
4445 @smallexample
4446 @group
4447 @cartouche
4448 @b{type} q @b{is record}
4449    a : integer;
4450    b : integer;
4451 @b{end record};
4453 @b{type} q @b{is}
4454    @b{record}
4455       a : integer;
4456       b : integer;
4457    @b{end record};
4458 @end cartouche
4459 @end group
4460 @end smallexample
4462 @noindent
4463 Second, in the case of a block statement, a permitted alternative
4464 is to put the block label on the same line as the @code{declare} or
4465 @code{begin} keyword, and then line the @code{end} keyword up under
4466 the block label. For example both the following are permitted:
4468 @smallexample
4469 @group
4470 @cartouche
4471 Block : @b{declare}
4472    A : Integer := 3;
4473 @b{begin}
4474    Proc (A, A);
4475 @b{end} Block;
4477 Block :
4478    @b{declare}
4479       A : Integer := 3;
4480    @b{begin}
4481       Proc (A, A);
4482    @b{end} Block;
4483 @end cartouche
4484 @end group
4485 @end smallexample
4487 @noindent
4488 The same alternative format is allowed for loops. For example, both of
4489 the following are permitted:
4491 @smallexample
4492 @group
4493 @cartouche
4494 Clear : @b{while} J < 10 @b{loop}
4495    A (J) := 0;
4496 @b{end loop} Clear;
4498 Clear :
4499    @b{while} J < 10 @b{loop}
4500       A (J) := 0;
4501    @b{end loop} Clear;
4502 @end cartouche
4503 @end group
4504 @end smallexample
4506 @item ^m^LINE_LENGTH^ (check maximum line length)
4507 If the ^letter m^word LINE_LENGTH^ appears in the string after @option{-gnaty}
4508 then the length of source lines must not exceed 79 characters, including
4509 any trailing blanks. The value of 79 allows convenient display on an
4510 80 character wide device or window, allowing for possible special
4511 treatment of 80 character lines.
4513 @item ^Mnnn^MAX_LENGTH=nnn^ (set maximum line length)
4514 If the sequence ^M^MAX_LENGTH=^nnn, where nnn is a decimal number, appears in
4515 the string after @option{-gnaty} then the length of lines must not exceed the
4516 given value.
4518 @item ^n^STANDARD_CASING^ (check casing of entities in Standard)
4519 If the ^letter n^word STANDARD_CASING^ appears in the string
4520 after @option{-gnaty} then any identifier from Standard must be cased
4521 to match the presentation in the Ada Reference Manual (for example,
4522 @code{Integer} and @code{ASCII.NUL}).
4524 @item ^o^ORDERED_SUBPROGRAMS^ (check order of subprogram bodies)
4525 If the ^letter o^word ORDERED_SUBPROGRAMS^ appears in the string
4526 after @option{-gnaty} then all subprogram bodies in a given scope
4527 (e.g. a package body) must be in alphabetical order. The ordering
4528 rule uses normal Ada rules for comparing strings, ignoring casing
4529 of letters, except that if there is a trailing numeric suffix, then
4530 the value of this suffix is used in the ordering (e.g. Junk2 comes
4531 before Junk10).
4533 @item ^p^PRAGMA^ (check pragma casing)
4534 If the ^letter p^word PRAGMA^ appears in the string after @option{-gnaty} then
4535 pragma names must be written in mixed case, that is, the
4536 initial letter and any letter following an underscore must be uppercase.
4537 All other letters must be lowercase.
4539 @item ^r^REFERENCES^ (check references)
4540 If the ^letter r^word REFERENCES^ appears in the string after @option{-gnaty}
4541 then all identifier references must be cased in the same way as the
4542 corresponding declaration. No specific casing style is imposed on
4543 identifiers. The only requirement is for consistency of references
4544 with declarations.
4546 @item ^s^SPECS^ (check separate specs)
4547 If the ^letter s^word SPECS^ appears in the string after @option{-gnaty} then
4548 separate declarations ("specs") are required for subprograms (a
4549 body is not allowed to serve as its own declaration). The only
4550 exception is that parameterless library level procedures are
4551 not required to have a separate declaration. This exception covers
4552 the most frequent form of main program procedures.
4554 @item ^t^TOKEN^ (check token spacing)
4555 If the ^letter t^word TOKEN^ appears in the string after @option{-gnaty} then
4556 the following token spacing rules are enforced:
4558 @itemize @bullet
4560 @item
4561 The keywords @code{abs} and @code{not} must be followed by a space.
4563 @item
4564 The token @code{=>} must be surrounded by spaces.
4566 @item
4567 The token @code{<>} must be preceded by a space or a left parenthesis.
4569 @item
4570 Binary operators other than @code{**} must be surrounded by spaces.
4571 There is no restriction on the layout of the @code{**} binary operator.
4573 @item
4574 Colon must be surrounded by spaces.
4576 @item
4577 Colon-equal (assignment) must be surrounded by spaces.
4579 @item
4580 Comma must be the first non-blank character on the line, or be
4581 immediately preceded by a non-blank character, and must be followed
4582 by a space.
4584 @item
4585 If the token preceding a left paren ends with a letter or digit, then
4586 a space must separate the two tokens.
4588 @item
4589 A right parenthesis must either be the first non-blank character on
4590 a line, or it must be preceded by a non-blank character.
4592 @item
4593 A semicolon must not be preceded by a space, and must not be followed by
4594 a non-blank character.
4596 @item
4597 A unary plus or minus may not be followed by a space.
4599 @item
4600 A vertical bar must be surrounded by spaces.
4601 @end itemize
4603 @noindent
4604 In the above rules, appearing in column one is always permitted, that is,
4605 counts as meeting either a requirement for a required preceding space,
4606 or as meeting a requirement for no preceding space.
4608 Appearing at the end of a line is also always permitted, that is, counts
4609 as meeting either a requirement for a following space, or as meeting
4610 a requirement for no following space.
4612 @end table
4614 @noindent
4615 If any of these style rules is violated, a message is generated giving
4616 details on the violation. The initial characters of such messages are
4617 always "(style)". Note that these messages are treated as warning
4618 messages, so they normally do not prevent the generation of an object
4619 file. The @option{-gnatwe} switch can be used to treat warning messages,
4620 including style messages, as fatal errors.
4622 @noindent
4623 The switch
4624 ^@option{-gnaty} on its own (that is not followed by any letters or digits),^/STYLE_CHECKS=ALL_BUILTIN^
4625 is equivalent to ^@code{gnaty3abcefhiklmprst}, that is^^ all checking
4626 options ^are^^ enabled with
4627 the exception of ^-gnatyo^ORDERED_SUBPROGRAMS^,
4628 with an indentation level of 3. This is the standard
4629 checking option that is used for the GNAT sources.
4631 @node Run-Time Checks
4632 @subsection Run-Time Checks
4633 @cindex Division by zero
4634 @cindex Access before elaboration
4635 @cindex Checks, division by zero
4636 @cindex Checks, access before elaboration
4638 @noindent
4639 If you compile with the default options, GNAT will insert many run-time
4640 checks into the compiled code, including code that performs range
4641 checking against constraints, but not arithmetic overflow checking for
4642 integer operations (including division by zero) or checks for access
4643 before elaboration on subprogram calls. All other run-time checks, as
4644 required by the Ada 95 Reference Manual, are generated by default.
4645 The following @code{gcc} switches refine this default behavior:
4647 @table @code
4648 @item -gnatp
4649 @cindex @option{-gnatp} (@code{gcc})
4650 @cindex Suppressing checks
4651 @cindex Checks, suppressing
4652 @findex Suppress
4653 Suppress all run-time checks as though @code{pragma Suppress (all_checks})
4654 had been present in the source. Validity checks are also suppressed (in
4655 other words @option{-gnatp} also implies @option{-gnatVn}.
4656 Use this switch to improve the performance
4657 of the code at the expense of safety in the presence of invalid data or
4658 program bugs.
4660 @item -gnato
4661 @cindex @option{-gnato} (@code{gcc})
4662 @cindex Overflow checks
4663 @cindex Check, overflow
4664 Enables overflow checking for integer operations.
4665 This causes GNAT to generate slower and larger executable
4666 programs by adding code to check for overflow (resulting in raising
4667 @code{Constraint_Error} as required by standard Ada
4668 semantics). These overflow checks correspond to situations in which
4669 the true value of the result of an operation may be outside the base
4670 range of the result type. The following example shows the distinction:
4672 @smallexample
4673 X1 : Integer := Integer'Last;
4674 X2 : Integer range 1 .. 5 := 5;
4676 X1 := X1 + 1;   -- @option{-gnato} required to catch the Constraint_Error
4677 X2 := X2 + 1;   -- range check, @option{-gnato} has no effect here
4678 @end smallexample
4680 @noindent
4681 Here the first addition results in a value that is outside the base range
4682 of Integer, and hence requires an overflow check for detection of the
4683 constraint error. The second increment operation results in a violation
4684 of the explicit range constraint, and such range checks are always
4685 performed. Basically the compiler can assume that in the absence of
4686 the @option{-gnato} switch that any value of type @code{xxx} is
4687 in range of the base type of @code{xxx}.
4689 @findex Machine_Overflows
4690 Note that the @option{-gnato} switch does not affect the code generated
4691 for any floating-point operations; it applies only to integer
4692 semantics).
4693 For floating-point, GNAT has the @code{Machine_Overflows}
4694 attribute set to @code{False} and the normal mode of operation is to
4695 generate IEEE NaN and infinite values on overflow or invalid operations
4696 (such as dividing 0.0 by 0.0).
4698 The reason that we distinguish overflow checking from other kinds of
4699 range constraint checking is that a failure of an overflow check can
4700 generate an incorrect value, but cannot cause erroneous behavior. This
4701 is unlike the situation with a constraint check on an array subscript,
4702 where failure to perform the check can result in random memory description,
4703 or the range check on a case statement, where failure to perform the check
4704 can cause a wild jump.
4706 Note again that @option{-gnato} is off by default, so overflow checking is
4707 not performed in default mode. This means that out of the box, with the
4708 default settings, GNAT does not do all the checks expected from the
4709 language description in the Ada Reference Manual. If you want all constraint
4710 checks to be performed, as described in this Manual, then you must
4711 explicitly use the -gnato switch either on the @code{gnatmake} or
4712 @code{gcc} command.
4714 @item -gnatE
4715 @cindex @option{-gnatE} (@code{gcc})
4716 @cindex Elaboration checks
4717 @cindex Check, elaboration
4718 Enables dynamic checks for access-before-elaboration
4719 on subprogram calls and generic instantiations.
4720 For full details of the effect and use of this switch,
4721 @xref{Compiling Using gcc}.
4722 @end table
4724 @findex Unsuppress
4725 @noindent
4726 The setting of these switches only controls the default setting of the
4727 checks. You may modify them using either @code{Suppress} (to remove
4728 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
4729 the program source.
4731 @node Stack Overflow Checking
4732 @subsection Stack Overflow Checking
4733 @cindex Stack Overflow Checking
4734 @cindex -fstack-check
4736 @noindent
4737 For most operating systems, @code{gcc} does not perform stack overflow
4738 checking by default. This means that if the main environment task or
4739 some other task exceeds the available stack space, then unpredictable
4740 behavior will occur.
4742 To activate stack checking, compile all units with the gcc option
4743 @code{-fstack-check}. For example:
4745 @smallexample
4746 gcc -c -fstack-check package1.adb
4747 @end smallexample
4749 @noindent
4750 Units compiled with this option will generate extra instructions to check
4751 that any use of the stack (for procedure calls or for declaring local
4752 variables in declare blocks) do not exceed the available stack space.
4753 If the space is exceeded, then a @code{Storage_Error} exception is raised.
4755 For declared tasks, the stack size is always controlled by the size
4756 given in an applicable @code{Storage_Size} pragma (or is set to
4757 the default size if no pragma is used.
4759 For the environment task, the stack size depends on
4760 system defaults and is unknown to the compiler. The stack
4761 may even dynamically grow on some systems, precluding the
4762 normal Ada semantics for stack overflow. In the worst case,
4763 unbounded stack usage, causes unbounded stack expansion
4764 resulting in the system running out of virtual memory.
4766 The stack checking may still work correctly if a fixed
4767 size stack is allocated, but this cannot be guaranteed.
4768 To ensure that a clean exception is signalled for stack
4769 overflow, set the environment variable
4770 @code{GNAT_STACK_LIMIT} to indicate the maximum
4771 stack area that can be used, as in:
4772 @cindex GNAT_STACK_LIMIT
4774 @smallexample
4775 SET GNAT_STACK_LIMIT 1600
4776 @end smallexample
4778 @noindent
4779 The limit is given in kilobytes, so the above declaration would
4780 set the stack limit of the environment task to 1.6 megabytes.
4781 Note that the only purpose of this usage is to limit the amount
4782 of stack used by the environment task. If it is necessary to
4783 increase the amount of stack for the environment task, then this
4784 is an operating systems issue, and must be addressed with the
4785 appropriate operating systems commands.
4787 @node Run-Time Control
4788 @subsection Run-Time Control
4790 @table @code
4791 @item -gnatT nnn
4792 @cindex @option{-gnatT} (@code{gcc})
4793 @cindex Time Slicing
4795 @noindent
4796 The @code{gnatT} switch can be used to specify the time-slicing value
4797 to be used for task switching between equal priority tasks. The value
4798 @code{nnn} is given in microseconds as a decimal integer.
4800 Setting the time-slicing value is only effective if the underlying thread
4801 control system can accommodate time slicing. Check the documentation of
4802 your operating system for details. Note that the time-slicing value can
4803 also be set by use of pragma @code{Time_Slice} or by use of the
4804 @code{t} switch in the gnatbind step. The pragma overrides a command
4805 line argument if both are present, and the @code{t} switch for gnatbind
4806 overrides both the pragma and the @code{gcc} command line switch.
4807 @end table
4809 @node Using gcc for Syntax Checking
4810 @subsection Using @code{gcc} for Syntax Checking
4811 @table @code
4812 @item -gnats
4813 @cindex @option{-gnats} (@code{gcc})
4814 @ifclear vms
4816 @noindent
4817 The @code{s} stands for syntax.
4818 @end ifclear
4820 Run GNAT in syntax checking only mode. For
4821 example, the command
4823 @smallexample
4824 $ gcc -c -gnats x.adb
4825 @end smallexample
4827 @noindent
4828 compiles file @file{x.adb} in syntax-check-only mode. You can check a
4829 series of files in a single command
4830 @ifclear vms
4831 , and can use wild cards to specify such a group of files.
4832 Note that you must specify the @code{-c} (compile
4833 only) flag in addition to the @option{-gnats} flag.
4834 @end ifclear
4837 You may use other switches in conjunction with @option{-gnats}. In
4838 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
4839 format of any generated error messages.
4841 The output is simply the error messages, if any. No object file or ALI
4842 file is generated by a syntax-only compilation. Also, no units other
4843 than the one specified are accessed. For example, if a unit @code{X}
4844 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
4845 check only mode does not access the source file containing unit
4846 @code{Y}.
4848 @cindex Multiple units, syntax checking
4849 Normally, GNAT allows only a single unit in a source file. However, this
4850 restriction does not apply in syntax-check-only mode, and it is possible
4851 to check a file containing multiple compilation units concatenated
4852 together. This is primarily used by the @code{gnatchop} utility
4853 (@pxref{Renaming Files Using gnatchop}).
4854 @end table
4856 @node Using gcc for Semantic Checking
4857 @subsection Using @code{gcc} for Semantic Checking
4858 @table @code
4859 @item -gnatc
4860 @cindex @option{-gnatc} (@code{gcc})
4862 @ifclear vms
4863 @noindent
4864 The @code{c} stands for check.
4865 @end ifclear
4866 Causes the compiler to operate in semantic check mode,
4867 with full checking for all illegalities specified in the
4868 Ada 95 Reference Manual, but without generation of any object code
4869 (no object file is generated).
4871 Because dependent files must be accessed, you must follow the GNAT
4872 semantic restrictions on file structuring to operate in this mode:
4874 @itemize @bullet
4875 @item
4876 The needed source files must be accessible
4877 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4879 @item
4880 Each file must contain only one compilation unit.
4882 @item
4883 The file name and unit name must match (@pxref{File Naming Rules}).
4884 @end itemize
4886 The output consists of error messages as appropriate. No object file is
4887 generated. An @file{ALI} file is generated for use in the context of
4888 cross-reference tools, but this file is marked as not being suitable
4889 for binding (since no object file is generated).
4890 The checking corresponds exactly to the notion of
4891 legality in the Ada 95 Reference Manual.
4893 Any unit can be compiled in semantics-checking-only mode, including
4894 units that would not normally be compiled (subunits,
4895 and specifications where a separate body is present).
4896 @end table
4898 @node Compiling Ada 83 Programs
4899 @subsection Compiling Ada 83 Programs
4900 @table @code
4901 @cindex Ada 83 compatibility
4902 @item -gnat83
4903 @cindex @option{-gnat83} (@code{gcc})
4904 @cindex ACVC, Ada 83 tests
4906 @noindent
4907 Although GNAT is primarily an Ada 95 compiler, it accepts this switch to
4908 specify that an Ada 83 program is to be compiled in Ada83 mode. If you specify
4909 this switch, GNAT rejects most Ada 95 extensions and applies Ada 83 semantics
4910 where this can be done easily.
4911 It is not possible to guarantee this switch does a perfect
4912 job; for example, some subtle tests, such as are
4913 found in earlier ACVC tests (that have been removed from the ACVC suite for Ada
4914 95), may not compile correctly. However, for most purposes, using
4915 this switch should help to ensure that programs that compile correctly
4916 under the @option{-gnat83} switch can be ported easily to an Ada 83
4917 compiler. This is the main use of the switch.
4919 With few exceptions (most notably the need to use @code{<>} on
4920 @cindex Generic formal parameters
4921 unconstrained generic formal parameters, the use of the new Ada 95
4922 keywords, and the use of packages
4923 with optional bodies), it is not necessary to use the
4924 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
4925 exceptions, Ada 95 is upwardly compatible with Ada 83. This
4926 means that a correct Ada 83 program is usually also a correct Ada 95
4927 program.
4929 @end table
4931 @node Character Set Control
4932 @subsection Character Set Control
4933 @table @code
4934 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4935 @cindex @code{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@code{gcc})
4937 @noindent
4938 Normally GNAT recognizes the Latin-1 character set in source program
4939 identifiers, as described in the Ada 95 Reference Manual.
4940 This switch causes
4941 GNAT to recognize alternate character sets in identifiers. @var{c} is a
4942 single character ^^or word^ indicating the character set, as follows:
4944 @table @code
4945 @item 1
4946 Latin-1 identifiers
4948 @item 2
4949 Latin-2 letters allowed in identifiers
4951 @item 3
4952 Latin-3 letters allowed in identifiers
4954 @item 4
4955 Latin-4 letters allowed in identifiers
4957 @item 5
4958 Latin-5 (Cyrillic) letters allowed in identifiers
4960 @item 9
4961 Latin-9 letters allowed in identifiers
4963 @item ^p^PC^
4964 IBM PC letters (code page 437) allowed in identifiers
4966 @item ^8^PC850^
4967 IBM PC letters (code page 850) allowed in identifiers
4969 @item ^f^FULL_UPPER^
4970 Full upper-half codes allowed in identifiers
4972 @item ^n^NO_UPPER^
4973 No upper-half codes allowed in identifiers
4975 @item ^w^WIDE^
4976 Wide-character codes (that is, codes greater than 255)
4977 allowed in identifiers
4978 @end table
4980 @xref{Foreign Language Representation}, for full details on the
4981 implementation of these character sets.
4983 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4984 @cindex @code{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@code{gcc})
4985 Specify the method of encoding for wide characters.
4986 @var{e} is one of the following:
4988 @table @code
4990 @item ^h^HEX^
4991 Hex encoding (brackets coding also recognized)
4993 @item ^u^UPPER^
4994 Upper half encoding (brackets encoding also recognized)
4996 @item ^s^SHIFT_JIS^
4997 Shift/JIS encoding (brackets encoding also recognized)
4999 @item ^e^EUC^
5000 EUC encoding (brackets encoding also recognized)
5002 @item ^8^UTF8^
5003 UTF-8 encoding (brackets encoding also recognized)
5005 @item ^b^BRACKETS^
5006 Brackets encoding only (default value)
5007 @end table
5008 For full details on the these encoding
5009 methods see @xref{Wide Character Encodings}.
5010 Note that brackets coding is always accepted, even if one of the other
5011 options is specified, so for example @option{-gnatW8} specifies that both
5012 brackets and @code{UTF-8} encodings will be recognized. The units that are
5013 with'ed directly or indirectly will be scanned using the specified
5014 representation scheme, and so if one of the non-brackets scheme is
5015 used, it must be used consistently throughout the program. However,
5016 since brackets encoding is always recognized, it may be conveniently
5017 used in standard libraries, allowing these libraries to be used with
5018 any of the available coding schemes.
5019 scheme. If no @option{-gnatW?} parameter is present, then the default
5020 representation is Brackets encoding only.
5022 Note that the wide character representation that is specified (explicitly
5023 or by default) for the main program also acts as the default encoding used
5024 for Wide_Text_IO files if not specifically overridden by a WCEM form
5025 parameter.
5027 @end table
5028 @node File Naming Control
5029 @subsection File Naming Control
5031 @table @code
5032 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
5033 @cindex @option{-gnatk} (@code{gcc})
5034 Activates file name "krunching". @var{n}, a decimal integer in the range
5035 1-999, indicates the maximum allowable length of a file name (not
5036 including the @file{.ads} or @file{.adb} extension). The default is not
5037 to enable file name krunching.
5039 For the source file naming rules, @xref{File Naming Rules}.
5040 @end table
5042 @node Subprogram Inlining Control
5043 @subsection Subprogram Inlining Control
5045 @table @code
5046 @item -gnatn
5047 @cindex @option{-gnatn} (@code{gcc})
5048 @ifclear vms
5049 The @code{n} here is intended to suggest the first syllable of the
5050 word "inline".
5051 @end ifclear
5052 GNAT recognizes and processes @code{Inline} pragmas. However, for the
5053 inlining to actually occur, optimization must be enabled. To enable
5054 inlining across unit boundaries, this is, inlining a call in one unit of
5055 a subprogram declared in a @code{with}'ed unit, you must also specify
5056 this switch.
5057 In the absence of this switch, GNAT does not attempt
5058 inlining across units and does not need to access the bodies of
5059 subprograms for which @code{pragma Inline} is specified if they are not
5060 in the current unit.
5062 If you specify this switch the compiler will access these bodies,
5063 creating an extra source dependency for the resulting object file, and
5064 where possible, the call will be inlined.
5065 For further details on when inlining is possible
5066 see @xref{Inlining of Subprograms}.
5068 @item -gnatN
5069 @cindex @option{-gnatN} (@code{gcc})
5070 The front end inlining activated by this switch is generally more extensive,
5071 and quite often more effective than the standard @option{-gnatn} inlining mode.
5072 It will also generate additional dependencies.
5074 @end table
5076 @node Auxiliary Output Control
5077 @subsection Auxiliary Output Control
5079 @table @code
5080 @item -gnatt
5081 @cindex @option{-gnatt} (@code{gcc})
5082 @cindex Writing internal trees
5083 @cindex Internal trees, writing to file
5084 Causes GNAT to write the internal tree for a unit to a file (with the
5085 extension @file{.adt}.
5086 This not normally required, but is used by separate analysis tools.
5087 Typically
5088 these tools do the necessary compilations automatically, so you should
5089 not have to specify this switch in normal operation.
5091 @item -gnatu
5092 @cindex @option{-gnatu} (@code{gcc})
5093 Print a list of units required by this compilation on @file{stdout}.
5094 The listing includes all units on which the unit being compiled depends
5095 either directly or indirectly.
5097 @ifclear vms
5098 @item -pass-exit-codes
5099 @cindex @code{-pass-exit-codes} (@code{gcc})
5100 If this switch is not used, the exit code returned by @code{gcc} when
5101 compiling multiple files indicates whether all source files have
5102 been successfully used to generate object files or not.
5104 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
5105 exit status and allows an integrated development environment to better
5106 react to a compilation failure. Those exit status are:
5108 @table @asis
5109 @item 5
5110 There was an error in at least one source file.
5111 @item 3
5112 At least one source file did not generate an object file.
5113 @item 2
5114 The compiler died unexpectedly (internal error for example).
5115 @item 0
5116 An object file has been generated for every source file.
5117 @end table
5118 @end ifclear
5119 @end table
5121 @node Debugging Control
5122 @subsection Debugging Control
5124 @table @code
5125 @cindex Debugging options
5126 @ifclear vms
5127 @item -gnatd@var{x}
5128 Activate internal debugging switches. @var{x} is a letter or digit, or
5129 string of letters or digits, which specifies the type of debugging
5130 outputs desired. Normally these are used only for internal development
5131 or system debugging purposes. You can find full documentation for these
5132 switches in the body of the @code{Debug} unit in the compiler source
5133 file @file{debug.adb}.
5134 @end ifclear
5136 @item -gnatG
5137 @cindex @option{-gnatG} (@code{gcc})
5138 This switch causes the compiler to generate auxiliary output containing
5139 a pseudo-source listing of the generated expanded code. Like most Ada
5140 compilers, GNAT works by first transforming the high level Ada code into
5141 lower level constructs. For example, tasking operations are transformed
5142 into calls to the tasking run-time routines. A unique capability of GNAT
5143 is to list this expanded code in a form very close to normal Ada source.
5144 This is very useful in understanding the implications of various Ada
5145 usage on the efficiency of the generated code. There are many cases in
5146 Ada (e.g. the use of controlled types), where simple Ada statements can
5147 generate a lot of run-time code. By using @option{-gnatG} you can identify
5148 these cases, and consider whether it may be desirable to modify the coding
5149 approach to improve efficiency.
5151 The format of the output is very similar to standard Ada source, and is
5152 easily understood by an Ada programmer. The following special syntactic
5153 additions correspond to low level features used in the generated code that
5154 do not have any exact analogies in pure Ada source form. The following
5155 is a partial list of these special constructions. See the specification
5156 of package @code{Sprint} in file @file{sprint.ads} for a full list.
5158 @table @code
5159 @item new @var{xxx} [storage_pool = @var{yyy}]
5160 Shows the storage pool being used for an allocator.
5162 @item at end @var{procedure-name};
5163 Shows the finalization (cleanup) procedure for a scope.
5165 @item (if @var{expr} then @var{expr} else @var{expr})
5166 Conditional expression equivalent to the @code{x?y:z} construction in C.
5168 @item @var{target}^^^(@var{source})
5169 A conversion with floating-point truncation instead of rounding.
5171 @item @var{target}?(@var{source})
5172 A conversion that bypasses normal Ada semantic checking. In particular
5173 enumeration types and fixed-point types are treated simply as integers.
5175 @item @var{target}?^^^(@var{source})
5176 Combines the above two cases.
5178 @item @var{x} #/ @var{y}
5179 @itemx @var{x} #mod @var{y}
5180 @itemx @var{x} #* @var{y}
5181 @itemx @var{x} #rem @var{y}
5182 A division or multiplication of fixed-point values which are treated as
5183 integers without any kind of scaling.
5185 @item free @var{expr} [storage_pool = @var{xxx}]
5186 Shows the storage pool associated with a @code{free} statement.
5188 @item freeze @var{typename} [@var{actions}]
5189 Shows the point at which @var{typename} is frozen, with possible
5190 associated actions to be performed at the freeze point.
5192 @item reference @var{itype}
5193 Reference (and hence definition) to internal type @var{itype}.
5195 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
5196 Intrinsic function call.
5198 @item @var{labelname} : label
5199 Declaration of label @var{labelname}.
5201 @item @var{expr} && @var{expr} && @var{expr} ... && @var{expr}
5202 A multiple concatenation (same effect as @var{expr} & @var{expr} &
5203 @var{expr}, but handled more efficiently).
5205 @item [constraint_error]
5206 Raise the @code{Constraint_Error} exception.
5208 @item @var{expression}'reference
5209 A pointer to the result of evaluating @var{expression}.
5211 @item @var{target-type}!(@var{source-expression})
5212 An unchecked conversion of @var{source-expression} to @var{target-type}.
5214 @item [@var{numerator}/@var{denominator}]
5215 Used to represent internal real literals (that) have no exact
5216 representation in base 2-16 (for example, the result of compile time
5217 evaluation of the expression 1.0/27.0).
5219 @item -gnatD
5220 @cindex @option{-gnatD} (@code{gcc})
5221 This switch is used in conjunction with @option{-gnatG} to cause the expanded
5222 source, as described above to be written to files with names
5223 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
5224 for example, if the source file name is @file{hello.adb},
5225 then a file @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.
5226 The debugging information generated
5227 by the @code{gcc} @code{^-g^/DEBUG^} switch will refer to the generated
5228 @file{^xxx.dg^XXX_DG^} file. This allows you to do source level debugging using
5229 the generated code which is sometimes useful for complex code, for example
5230 to find out exactly which part of a complex construction raised an
5231 exception. This switch also suppress generation of cross-reference
5232 information (see -gnatx).
5234 @item -gnatC
5235 @cindex @option{-gnatE} (@code{gcc})
5236 In the generated debugging information, and also in the case of long external
5237 names, the compiler uses a compression mechanism if the name is very long.
5238 This compression method uses a checksum, and avoids trouble on some operating
5239 systems which have difficulty with very long names. The @option{-gnatC} switch
5240 forces this compression approach to be used on all external names and names
5241 in the debugging information tables. This reduces the size of the generated
5242 executable, at the expense of making the naming scheme more complex. The
5243 compression only affects the qualification of the name. Thus a name in
5244 the source:
5246 @smallexample
5247 Very_Long_Package.Very_Long_Inner_Package.Var
5248 @end smallexample
5250 @noindent
5251 would normally appear in these tables as:
5253 @smallexample
5254 very_long_package__very_long_inner_package__var
5255 @end smallexample
5257 @noindent
5258 but if the @option{-gnatC} switch is used, then the name appears as
5260 @smallexample
5261 XCb7e0c705__var
5262 @end smallexample
5264 @noindent
5265 Here b7e0c705 is a compressed encoding of the qualification prefix.
5266 The GNAT Ada aware version of GDB understands these encoded prefixes, so if this
5267 debugger is used, the encoding is largely hidden from the user of the compiler.
5269 @end table
5271 @item -gnatR[0|1|2|3][s]
5272 @cindex @option{-gnatR} (@code{gcc})
5273 This switch controls output from the compiler of a listing showing
5274 representation information for declared types and objects. For
5275 @option{-gnatR0}, no information is output (equivalent to omitting
5276 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
5277 so @option{-gnatR} with no parameter has the same effect), size and alignment
5278 information is listed for declared array and record types. For
5279 @option{-gnatR2}, size and alignment information is listed for all
5280 expression information for values that are computed at run time for
5281 variant records. These symbolic expressions have a mostly obvious
5282 format with #n being used to represent the value of the n'th
5283 discriminant. See source files @file{repinfo.ads/adb} in the
5284 @code{GNAT} sources for full detalis on the format of @option{-gnatR3}
5285 output. If the switch is followed by an s (e.g. @option{-gnatR2s}), then
5286 the output is to a file with the name @file{^file.rep^file_REP^} where
5287 file is the name of the corresponding source file.
5289 @item -gnatx
5290 @cindex @option{-gnatx} (@code{gcc})
5291 Normally the compiler generates full cross-referencing information in
5292 the @file{ALI} file. This information is used by a number of tools,
5293 including @code{gnatfind} and @code{gnatxref}. The -gnatx switch
5294 suppresses this information. This saves some space and may slightly
5295 speed up compilation, but means that these tools cannot be used.
5296 @end table
5298 @node Units to Sources Mapping Files
5299 @subsection Units to Sources Mapping Files
5301 @table @code
5303 @item -gnatem@var{path}
5304 @cindex @option{-gnatem} (@code{gcc})
5305 A mapping file is a way to communicate to the compiler two mappings:
5306 from unit names to file names (without any directory information) and from
5307 file names to path names (with full directory information). These mappings
5308 are used by the compiler to short-circuit the path search.
5310 A mapping file is a sequence of sets of three lines. In each set,
5311 the first line is the unit name, in lower case, with "%s" appended for
5312 specifications and "%b" appended for bodies; the second line is the file
5313 name; and the third line is the path name.
5315 Example:
5316 @smallexample
5317    main%b
5318    main.2.ada
5319    /gnat/project1/sources/main.2.ada
5320 @end smallexample
5322 When the switch @option{-gnatem} is specified, the compiler will create
5323 in memory the two mappings from the specified file. If there is any problem
5324 (non existent file, truncated file or duplicate entries), no mapping
5325 will be created.
5327 Several @option{-gnatem} switches may be specified; however, only the last
5328 one on the command line will be taken into account.
5330 When using a project file, @code{gnatmake} create a temporary mapping file
5331 and communicates it to the compiler using this switch.
5333 @end table
5335 @node Search Paths and the Run-Time Library (RTL)
5336 @section Search Paths and the Run-Time Library (RTL)
5338 @noindent
5339 With the GNAT source-based library system, the compiler must be able to
5340 find source files for units that are needed by the unit being compiled.
5341 Search paths are used to guide this process.
5343 The compiler compiles one source file whose name must be given
5344 explicitly on the command line. In other words, no searching is done
5345 for this file. To find all other source files that are needed (the most
5346 common being the specs of units), the compiler examines the following
5347 directories, in the following order:
5349 @enumerate
5350 @item
5351 The directory containing the source file of the main unit being compiled
5352 (the file name on the command line).
5354 @item
5355 Each directory named by an @code{^-I^/SOURCE_SEARCH^} switch given on the @code{gcc}
5356 command line, in the order given.
5358 @item
5359 @findex ADA_INCLUDE_PATH
5360 Each of the directories listed in the value of the
5361 @code{ADA_INCLUDE_PATH} ^environment variable^logical name^.
5362 @ifclear vms
5363 Construct this value
5364 exactly as the @code{PATH} environment variable: a list of directory
5365 names separated by colons (semicolons when working with the NT version).
5366 @end ifclear
5367 @ifset vms
5368 Normally, define this value as a logical name containing a comma separated
5369 list of directory names.
5371 This variable can also be defined by means of an environment string
5372 (an argument to the DEC C exec* set of functions).
5374 Logical Name:
5375 @smallexample
5376 DEFINE ANOTHER_PATH FOO:[BAG]
5377 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
5378 @end smallexample
5380 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
5381 first, followed by the standard Ada 95
5382 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
5383 If this is not redefined, the user will obtain the DEC Ada83 IO packages
5384 (Text_IO, Sequential_IO, etc)
5385 instead of the Ada95 packages. Thus, in order to get the Ada 95
5386 packages by default, ADA_INCLUDE_PATH must be redefined.
5387 @end ifset
5388 @item
5389 The content of the "ada_source_path" file which is part of the GNAT
5390 installation tree and is used to store standard libraries such as the
5391 GNAT Run Time Library (RTL) source files.
5392 @ifclear vms
5393 @ref{Installing an Ada Library}
5394 @end ifclear
5395 @end enumerate
5397 @noindent
5398 Specifying the switch @code{^-I-^/NOCURRENT_DIRECTORY^}
5399 inhibits the use of the directory
5400 containing the source file named in the command line. You can still
5401 have this directory on your search path, but in this case it must be
5402 explicitly requested with a @code{^-I^/SOURCE_SEARCH^} switch.
5404 Specifying the switch @code{-nostdinc}
5405 inhibits the search of the default location for the GNAT Run Time
5406 Library (RTL) source files.
5408 The compiler outputs its object files and ALI files in the current
5409 working directory.
5410 @ifclear vms
5411 Caution: The object file can be redirected with the @code{-o} switch;
5412 however, @code{gcc} and @code{gnat1} have not been coordinated on this
5413 so the ALI file will not go to the right place. Therefore, you should
5414 avoid using the @code{-o} switch.
5415 @end ifclear
5417 @findex System.IO
5418 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
5419 children make up the GNAT RTL, together with the simple @code{System.IO}
5420 package used in the "Hello World" example. The sources for these units
5421 are needed by the compiler and are kept together in one directory. Not
5422 all of the bodies are needed, but all of the sources are kept together
5423 anyway. In a normal installation, you need not specify these directory
5424 names when compiling or binding. Either the environment variables or
5425 the built-in defaults cause these files to be found.
5427 In addition to the language-defined hierarchies (System, Ada and
5428 Interfaces), the GNAT distribution provides a fourth hierarchy,
5429 consisting of child units of GNAT. This is a collection of generally
5430 useful routines. See the GNAT Reference Manual for further details.
5432 Besides simplifying access to the RTL, a major use of search paths is
5433 in compiling sources from multiple directories. This can make
5434 development environments much more flexible.
5436 @node Order of Compilation Issues
5437 @section Order of Compilation Issues
5439 @noindent
5440 If, in our earlier example, there was a spec for the @code{hello}
5441 procedure, it would be contained in the file @file{hello.ads}; yet this
5442 file would not have to be explicitly compiled. This is the result of the
5443 model we chose to implement library management. Some of the consequences
5444 of this model are as follows:
5446 @itemize @bullet
5447 @item
5448 There is no point in compiling specs (except for package
5449 specs with no bodies) because these are compiled as needed by clients. If
5450 you attempt a useless compilation, you will receive an error message.
5451 It is also useless to compile subunits because they are compiled as needed
5452 by the parent.
5454 @item
5455 There are no order of compilation requirements: performing a
5456 compilation never obsoletes anything. The only way you can obsolete
5457 something and require recompilations is to modify one of the
5458 source files on which it depends.
5460 @item
5461 There is no library as such, apart from the ALI files
5462 (@pxref{The Ada Library Information Files}, for information on the format of these
5463 files). For now we find it convenient to create separate ALI files, but
5464 eventually the information therein may be incorporated into the object
5465 file directly.
5467 @item
5468 When you compile a unit, the source files for the specs of all units
5469 that it @code{with}'s, all its subunits, and the bodies of any generics it
5470 instantiates must be available (reachable by the search-paths mechanism
5471 described above), or you will receive a fatal error message.
5472 @end itemize
5474 @node Examples
5475 @section Examples
5477 @noindent
5478 The following are some typical Ada compilation command line examples:
5480 @table @code
5481 @item $ gcc -c xyz.adb
5482 Compile body in file @file{xyz.adb} with all default options.
5484 @ifclear vms
5485 @item $ gcc -c -O2 -gnata xyz-def.adb
5486 @end ifclear
5487 @ifset vms
5488 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
5489 @end ifset
5491 Compile the child unit package in file @file{xyz-def.adb} with extensive
5492 optimizations, and pragma @code{Assert}/@code{Debug} statements
5493 enabled.
5495 @item $ gcc -c -gnatc abc-def.adb
5496 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
5497 mode.
5498 @end table
5500 @node Binding Using gnatbind
5501 @chapter Binding Using @code{gnatbind}
5502 @findex gnatbind
5504 @menu
5505 * Running gnatbind::
5506 * Generating the Binder Program in C::
5507 * Consistency-Checking Modes::
5508 * Binder Error Message Control::
5509 * Elaboration Control::
5510 * Output Control::
5511 * Binding with Non-Ada Main Programs::
5512 * Binding Programs with No Main Subprogram::
5513 * Summary of Binder Switches::
5514 * Command-Line Access::
5515 * Search Paths for gnatbind::
5516 * Examples of gnatbind Usage::
5517 @end menu
5519 @noindent
5520 This chapter describes the GNAT binder, @code{gnatbind}, which is used
5521 to bind compiled GNAT objects. The @code{gnatbind} program performs
5522 four separate functions:
5524 @enumerate
5525 @item
5526 Checks that a program is consistent, in accordance with the rules in
5527 Chapter 10 of the Ada 95 Reference Manual. In particular, error
5528 messages are generated if a program uses inconsistent versions of a
5529 given unit.
5531 @item
5532 Checks that an acceptable order of elaboration exists for the program
5533 and issues an error message if it cannot find an order of elaboration
5534 that satisfies the rules in Chapter 10 of the Ada 95 Language Manual.
5536 @item
5537 Generates a main program incorporating the given elaboration order.
5538 This program is a small Ada package (body and spec) that
5539 must be subsequently compiled
5540 using the GNAT compiler. The necessary compilation step is usually
5541 performed automatically by @code{gnatlink}. The two most important
5542 functions of this program
5543 are to call the elaboration routines of units in an appropriate order
5544 and to call the main program.
5546 @item
5547 Determines the set of object files required by the given main program.
5548 This information is output in the forms of comments in the generated program,
5549 to be read by the @code{gnatlink} utility used to link the Ada application.
5550 @end enumerate
5552 @node Running gnatbind
5553 @section Running @code{gnatbind}
5555 @noindent
5556 The form of the @code{gnatbind} command is
5558 @smallexample
5559 $ gnatbind [@var{switches}] @var{mainprog}[.ali] [@var{switches}]
5560 @end smallexample
5562 @noindent
5563 where @var{mainprog}.adb is the Ada file containing the main program
5564 unit body. If no switches are specified, @code{gnatbind} constructs an Ada
5565 package in two files which names are
5566 @file{b~@var{ada_main}.ads}, and @file{b~@var{ada_main}.adb}.
5567 For example, if given the
5568 parameter @samp{hello.ali}, for a main program contained in file
5569 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
5570 and @file{b~hello.adb}.
5572 When doing consistency checking, the binder takes into consideration
5573 any source files it can locate. For example, if the binder determines
5574 that the given main program requires the package @code{Pack}, whose
5575 @file{.ali}
5576 file is @file{pack.ali} and whose corresponding source spec file is
5577 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
5578 (using the same search path conventions as previously described for the
5579 @code{gcc} command). If it can locate this source file, it checks that
5580 the time stamps
5581 or source checksums of the source and its references to in @file{ali} files
5582 match. In other words, any @file{ali} files that mentions this spec must have
5583 resulted from compiling this version of the source file (or in the case
5584 where the source checksums match, a version close enough that the
5585 difference does not matter).
5587 @cindex Source files, use by binder
5588 The effect of this consistency checking, which includes source files, is
5589 that the binder ensures that the program is consistent with the latest
5590 version of the source files that can be located at bind time. Editing a
5591 source file without compiling files that depend on the source file cause
5592 error messages to be generated by the binder.
5594 For example, suppose you have a main program @file{hello.adb} and a
5595 package @code{P}, from file @file{p.ads} and you perform the following
5596 steps:
5598 @enumerate
5599 @item
5600 Enter @code{gcc -c hello.adb} to compile the main program.
5602 @item
5603 Enter @code{gcc -c p.ads} to compile package @code{P}.
5605 @item
5606 Edit file @file{p.ads}.
5608 @item
5609 Enter @code{gnatbind hello}.
5610 @end enumerate
5612 At this point, the file @file{p.ali} contains an out-of-date time stamp
5613 because the file @file{p.ads} has been edited. The attempt at binding
5614 fails, and the binder generates the following error messages:
5616 @smallexample
5617 error: "hello.adb" must be recompiled ("p.ads" has been modified)
5618 error: "p.ads" has been modified and must be recompiled
5619 @end smallexample
5621 @noindent
5622 Now both files must be recompiled as indicated, and then the bind can
5623 succeed, generating a main program. You need not normally be concerned
5624 with the contents of this file, but it is similar to the following which
5625 is the binder file generated for a simple "hello world" program.
5627 @smallexample
5628 @iftex
5629 @leftskip=0cm
5630 @end iftex
5631 --  The package is called Ada_Main unless this name is actually used
5632 --  as a unit name in the partition, in which case some other unique
5633 --  name is used.
5635 with System;
5636 package ada_main is
5638    Elab_Final_Code : Integer;
5639    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
5641    --  The main program saves the parameters (argument count,
5642    --  argument values, environment pointer) in global variables
5643    --  for later access by other units including
5644    --  Ada.Command_Line.
5646    gnat_argc : Integer;
5647    gnat_argv : System.Address;
5648    gnat_envp : System.Address;
5650    --  The actual variables are stored in a library routine. This
5651    --  is useful for some shared library situations, where there
5652    --  are problems if variables are not in the library.
5654    pragma Import (C, gnat_argc);
5655    pragma Import (C, gnat_argv);
5656    pragma Import (C, gnat_envp);
5658    --  The exit status is similarly an external location
5660    gnat_exit_status : Integer;
5661    pragma Import (C, gnat_exit_status);
5663    GNAT_Version : constant String :=
5664                     "GNAT Version: 3.15w (20010315)";
5665    pragma Export (C, GNAT_Version, "__gnat_version");
5667    --  This is the generated adafinal routine that performs
5668    --  finalization at the end of execution. In the case where
5669    --  Ada is the main program, this main program makes a call
5670    --  to adafinal at program termination.
5672    procedure adafinal;
5673    pragma Export (C, adafinal, "adafinal");
5675    --  This is the generated adainit routine that performs
5676    --  initialization at the start of execution. In the case
5677    --  where Ada is the main program, this main program makes
5678    --  a call to adainit at program startup.
5680    procedure adainit;
5681    pragma Export (C, adainit, "adainit");
5683    --  This routine is called at the start of execution. It is
5684    --  a dummy routine that is used by the debugger to breakpoint
5685    --  at the start of execution.
5687    procedure Break_Start;
5688    pragma Import (C, Break_Start, "__gnat_break_start");
5690    --  This is the actual generated main program (it would be
5691    --  suppressed if the no main program switch were used). As
5692    --  required by standard system conventions, this program has
5693    --  the external name main.
5695    function main
5696      (argc : Integer;
5697       argv : System.Address;
5698       envp : System.Address)
5699       return Integer;
5700    pragma Export (C, main, "main");
5702    --  The following set of constants give the version
5703    --  identification values for every unit in the bound
5704    --  partition. This identification is computed from all
5705    --  dependent semantic units, and corresponds to the
5706    --  string that would be returned by use of the
5707    --  Body_Version or Version attributes.
5709    type Version_32 is mod 2 ** 32;
5710    u00001 : constant Version_32 := 16#7880BEB3#;
5711    u00002 : constant Version_32 := 16#0D24CBD0#;
5712    u00003 : constant Version_32 := 16#3283DBEB#;
5713    u00004 : constant Version_32 := 16#2359F9ED#;
5714    u00005 : constant Version_32 := 16#664FB847#;
5715    u00006 : constant Version_32 := 16#68E803DF#;
5716    u00007 : constant Version_32 := 16#5572E604#;
5717    u00008 : constant Version_32 := 16#46B173D8#;
5718    u00009 : constant Version_32 := 16#156A40CF#;
5719    u00010 : constant Version_32 := 16#033DABE0#;
5720    u00011 : constant Version_32 := 16#6AB38FEA#;
5721    u00012 : constant Version_32 := 16#22B6217D#;
5722    u00013 : constant Version_32 := 16#68A22947#;
5723    u00014 : constant Version_32 := 16#18CC4A56#;
5724    u00015 : constant Version_32 := 16#08258E1B#;
5725    u00016 : constant Version_32 := 16#367D5222#;
5726    u00017 : constant Version_32 := 16#20C9ECA4#;
5727    u00018 : constant Version_32 := 16#50D32CB6#;
5728    u00019 : constant Version_32 := 16#39A8BB77#;
5729    u00020 : constant Version_32 := 16#5CF8FA2B#;
5730    u00021 : constant Version_32 := 16#2F1EB794#;
5731    u00022 : constant Version_32 := 16#31AB6444#;
5732    u00023 : constant Version_32 := 16#1574B6E9#;
5733    u00024 : constant Version_32 := 16#5109C189#;
5734    u00025 : constant Version_32 := 16#56D770CD#;
5735    u00026 : constant Version_32 := 16#02F9DE3D#;
5736    u00027 : constant Version_32 := 16#08AB6B2C#;
5737    u00028 : constant Version_32 := 16#3FA37670#;
5738    u00029 : constant Version_32 := 16#476457A0#;
5739    u00030 : constant Version_32 := 16#731E1B6E#;
5740    u00031 : constant Version_32 := 16#23C2E789#;
5741    u00032 : constant Version_32 := 16#0F1BD6A1#;
5742    u00033 : constant Version_32 := 16#7C25DE96#;
5743    u00034 : constant Version_32 := 16#39ADFFA2#;
5744    u00035 : constant Version_32 := 16#571DE3E7#;
5745    u00036 : constant Version_32 := 16#5EB646AB#;
5746    u00037 : constant Version_32 := 16#4249379B#;
5747    u00038 : constant Version_32 := 16#0357E00A#;
5748    u00039 : constant Version_32 := 16#3784FB72#;
5749    u00040 : constant Version_32 := 16#2E723019#;
5750    u00041 : constant Version_32 := 16#623358EA#;
5751    u00042 : constant Version_32 := 16#107F9465#;
5752    u00043 : constant Version_32 := 16#6843F68A#;
5753    u00044 : constant Version_32 := 16#63305874#;
5754    u00045 : constant Version_32 := 16#31E56CE1#;
5755    u00046 : constant Version_32 := 16#02917970#;
5756    u00047 : constant Version_32 := 16#6CCBA70E#;
5757    u00048 : constant Version_32 := 16#41CD4204#;
5758    u00049 : constant Version_32 := 16#572E3F58#;
5759    u00050 : constant Version_32 := 16#20729FF5#;
5760    u00051 : constant Version_32 := 16#1D4F93E8#;
5761    u00052 : constant Version_32 := 16#30B2EC3D#;
5762    u00053 : constant Version_32 := 16#34054F96#;
5763    u00054 : constant Version_32 := 16#5A199860#;
5764    u00055 : constant Version_32 := 16#0E7F912B#;
5765    u00056 : constant Version_32 := 16#5760634A#;
5766    u00057 : constant Version_32 := 16#5D851835#;
5768    --  The following Export pragmas export the version numbers
5769    --  with symbolic names ending in B (for body) or S
5770    --  (for spec) so that they can be located in a link. The
5771    --  information provided here is sufficient to track down
5772    --  the exact versions of units used in a given build.
5774    pragma Export (C, u00001, "helloB");
5775    pragma Export (C, u00002, "system__standard_libraryB");
5776    pragma Export (C, u00003, "system__standard_libraryS");
5777    pragma Export (C, u00004, "adaS");
5778    pragma Export (C, u00005, "ada__text_ioB");
5779    pragma Export (C, u00006, "ada__text_ioS");
5780    pragma Export (C, u00007, "ada__exceptionsB");
5781    pragma Export (C, u00008, "ada__exceptionsS");
5782    pragma Export (C, u00009, "gnatS");
5783    pragma Export (C, u00010, "gnat__heap_sort_aB");
5784    pragma Export (C, u00011, "gnat__heap_sort_aS");
5785    pragma Export (C, u00012, "systemS");
5786    pragma Export (C, u00013, "system__exception_tableB");
5787    pragma Export (C, u00014, "system__exception_tableS");
5788    pragma Export (C, u00015, "gnat__htableB");
5789    pragma Export (C, u00016, "gnat__htableS");
5790    pragma Export (C, u00017, "system__exceptionsS");
5791    pragma Export (C, u00018, "system__machine_state_operationsB");
5792    pragma Export (C, u00019, "system__machine_state_operationsS");
5793    pragma Export (C, u00020, "system__machine_codeS");
5794    pragma Export (C, u00021, "system__storage_elementsB");
5795    pragma Export (C, u00022, "system__storage_elementsS");
5796    pragma Export (C, u00023, "system__secondary_stackB");
5797    pragma Export (C, u00024, "system__secondary_stackS");
5798    pragma Export (C, u00025, "system__parametersB");
5799    pragma Export (C, u00026, "system__parametersS");
5800    pragma Export (C, u00027, "system__soft_linksB");
5801    pragma Export (C, u00028, "system__soft_linksS");
5802    pragma Export (C, u00029, "system__stack_checkingB");
5803    pragma Export (C, u00030, "system__stack_checkingS");
5804    pragma Export (C, u00031, "system__tracebackB");
5805    pragma Export (C, u00032, "system__tracebackS");
5806    pragma Export (C, u00033, "ada__streamsS");
5807    pragma Export (C, u00034, "ada__tagsB");
5808    pragma Export (C, u00035, "ada__tagsS");
5809    pragma Export (C, u00036, "system__string_opsB");
5810    pragma Export (C, u00037, "system__string_opsS");
5811    pragma Export (C, u00038, "interfacesS");
5812    pragma Export (C, u00039, "interfaces__c_streamsB");
5813    pragma Export (C, u00040, "interfaces__c_streamsS");
5814    pragma Export (C, u00041, "system__file_ioB");
5815    pragma Export (C, u00042, "system__file_ioS");
5816    pragma Export (C, u00043, "ada__finalizationB");
5817    pragma Export (C, u00044, "ada__finalizationS");
5818    pragma Export (C, u00045, "system__finalization_rootB");
5819    pragma Export (C, u00046, "system__finalization_rootS");
5820    pragma Export (C, u00047, "system__finalization_implementationB");
5821    pragma Export (C, u00048, "system__finalization_implementationS");
5822    pragma Export (C, u00049, "system__string_ops_concat_3B");
5823    pragma Export (C, u00050, "system__string_ops_concat_3S");
5824    pragma Export (C, u00051, "system__stream_attributesB");
5825    pragma Export (C, u00052, "system__stream_attributesS");
5826    pragma Export (C, u00053, "ada__io_exceptionsS");
5827    pragma Export (C, u00054, "system__unsigned_typesS");
5828    pragma Export (C, u00055, "system__file_control_blockS");
5829    pragma Export (C, u00056, "ada__finalization__list_controllerB");
5830    pragma Export (C, u00057, "ada__finalization__list_controllerS");
5832    -- BEGIN ELABORATION ORDER
5833    -- ada (spec)
5834    -- gnat (spec)
5835    -- gnat.heap_sort_a (spec)
5836    -- gnat.heap_sort_a (body)
5837    -- gnat.htable (spec)
5838    -- gnat.htable (body)
5839    -- interfaces (spec)
5840    -- system (spec)
5841    -- system.machine_code (spec)
5842    -- system.parameters (spec)
5843    -- system.parameters (body)
5844    -- interfaces.c_streams (spec)
5845    -- interfaces.c_streams (body)
5846    -- system.standard_library (spec)
5847    -- ada.exceptions (spec)
5848    -- system.exception_table (spec)
5849    -- system.exception_table (body)
5850    -- ada.io_exceptions (spec)
5851    -- system.exceptions (spec)
5852    -- system.storage_elements (spec)
5853    -- system.storage_elements (body)
5854    -- system.machine_state_operations (spec)
5855    -- system.machine_state_operations (body)
5856    -- system.secondary_stack (spec)
5857    -- system.stack_checking (spec)
5858    -- system.soft_links (spec)
5859    -- system.soft_links (body)
5860    -- system.stack_checking (body)
5861    -- system.secondary_stack (body)
5862    -- system.standard_library (body)
5863    -- system.string_ops (spec)
5864    -- system.string_ops (body)
5865    -- ada.tags (spec)
5866    -- ada.tags (body)
5867    -- ada.streams (spec)
5868    -- system.finalization_root (spec)
5869    -- system.finalization_root (body)
5870    -- system.string_ops_concat_3 (spec)
5871    -- system.string_ops_concat_3 (body)
5872    -- system.traceback (spec)
5873    -- system.traceback (body)
5874    -- ada.exceptions (body)
5875    -- system.unsigned_types (spec)
5876    -- system.stream_attributes (spec)
5877    -- system.stream_attributes (body)
5878    -- system.finalization_implementation (spec)
5879    -- system.finalization_implementation (body)
5880    -- ada.finalization (spec)
5881    -- ada.finalization (body)
5882    -- ada.finalization.list_controller (spec)
5883    -- ada.finalization.list_controller (body)
5884    -- system.file_control_block (spec)
5885    -- system.file_io (spec)
5886    -- system.file_io (body)
5887    -- ada.text_io (spec)
5888    -- ada.text_io (body)
5889    -- hello (body)
5890    -- END ELABORATION ORDER
5892 end ada_main;
5894 --  The following source file name pragmas allow the generated file
5895 --  names to be unique for different main programs. They are needed
5896 --  since the package name will always be Ada_Main.
5898 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
5899 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
5901 --  Generated package body for Ada_Main starts here
5903 package body ada_main is
5905    --  The actual finalization is performed by calling the
5906    --  library routine in System.Standard_Library.Adafinal
5908    procedure Do_Finalize;
5909    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
5911    -------------
5912    -- adainit --
5913    -------------
5915 @findex adainit
5916    procedure adainit is
5918       --  These booleans are set to True once the associated unit has
5919       --  been elaborated. It is also used to avoid elaborating the
5920       --  same unit twice.
5922       E040 : Boolean; pragma Import (Ada, E040, "interfaces__c_streams_E");
5923       E008 : Boolean; pragma Import (Ada, E008, "ada__exceptions_E");
5924       E014 : Boolean; pragma Import (Ada, E014, "system__exception_table_E");
5925       E053 : Boolean; pragma Import (Ada, E053, "ada__io_exceptions_E");
5926       E017 : Boolean; pragma Import (Ada, E017, "system__exceptions_E");
5927       E024 : Boolean; pragma Import (Ada, E024, "system__secondary_stack_E");
5928       E030 : Boolean; pragma Import (Ada, E030, "system__stack_checking_E");
5929       E028 : Boolean; pragma Import (Ada, E028, "system__soft_links_E");
5930       E035 : Boolean; pragma Import (Ada, E035, "ada__tags_E");
5931       E033 : Boolean; pragma Import (Ada, E033, "ada__streams_E");
5932       E046 : Boolean; pragma Import (Ada, E046, "system__finalization_root_E");
5933       E048 : Boolean; pragma Import (Ada, E048, "system__finalization_implementation_E");
5934       E044 : Boolean; pragma Import (Ada, E044, "ada__finalization_E");
5935       E057 : Boolean; pragma Import (Ada, E057, "ada__finalization__list_controller_E");
5936       E055 : Boolean; pragma Import (Ada, E055, "system__file_control_block_E");
5937       E042 : Boolean; pragma Import (Ada, E042, "system__file_io_E");
5938       E006 : Boolean; pragma Import (Ada, E006, "ada__text_io_E");
5940       --  Set_Globals is a library routine that stores away the
5941       --  value of the indicated set of global values in global
5942       --  variables within the library.
5944       procedure Set_Globals
5945         (Main_Priority            : Integer;
5946          Time_Slice_Value         : Integer;
5947          WC_Encoding              : Character;
5948          Locking_Policy           : Character;
5949          Queuing_Policy           : Character;
5950          Task_Dispatching_Policy  : Character;
5951          Adafinal                 : System.Address;
5952          Unreserve_All_Interrupts : Integer;
5953          Exception_Tracebacks     : Integer);
5954 @findex __gnat_set_globals
5955       pragma Import (C, Set_Globals, "__gnat_set_globals");
5957       --  SDP_Table_Build is a library routine used to build the
5958       --  exception tables. See unit Ada.Exceptions in files
5959       --  a-except.ads/adb for full details of how zero cost
5960       --  exception handling works. This procedure, the call to
5961       --  it, and the two following tables are all omitted if the
5962       --  build is in longjmp/setjump exception mode.
5964 @findex SDP_Table_Build
5965 @findex Zero Cost Exceptions
5966       procedure SDP_Table_Build
5967         (SDP_Addresses   : System.Address;
5968          SDP_Count       : Natural;
5969          Elab_Addresses  : System.Address;
5970          Elab_Addr_Count : Natural);
5971       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
5973       --  Table of Unit_Exception_Table addresses. Used for zero
5974       --  cost exception handling to build the top level table.
5976       ST : aliased constant array (1 .. 23) of System.Address := (
5977         Hello'UET_Address,
5978         Ada.Text_Io'UET_Address,
5979         Ada.Exceptions'UET_Address,
5980         Gnat.Heap_Sort_A'UET_Address,
5981         System.Exception_Table'UET_Address,
5982         System.Machine_State_Operations'UET_Address,
5983         System.Secondary_Stack'UET_Address,
5984         System.Parameters'UET_Address,
5985         System.Soft_Links'UET_Address,
5986         System.Stack_Checking'UET_Address,
5987         System.Traceback'UET_Address,
5988         Ada.Streams'UET_Address,
5989         Ada.Tags'UET_Address,
5990         System.String_Ops'UET_Address,
5991         Interfaces.C_Streams'UET_Address,
5992         System.File_Io'UET_Address,
5993         Ada.Finalization'UET_Address,
5994         System.Finalization_Root'UET_Address,
5995         System.Finalization_Implementation'UET_Address,
5996         System.String_Ops_Concat_3'UET_Address,
5997         System.Stream_Attributes'UET_Address,
5998         System.File_Control_Block'UET_Address,
5999         Ada.Finalization.List_Controller'UET_Address);
6001       --  Table of addresses of elaboration routines. Used for
6002       --  zero cost exception handling to make sure these
6003       --  addresses are included in the top level procedure
6004       --  address table.
6006       EA : aliased constant array (1 .. 23) of System.Address := (
6007         adainit'Code_Address,
6008         Do_Finalize'Code_Address,
6009         Ada.Exceptions'Elab_Spec'Address,
6010         System.Exceptions'Elab_Spec'Address,
6011         Interfaces.C_Streams'Elab_Spec'Address,
6012         System.Exception_Table'Elab_Body'Address,
6013         Ada.Io_Exceptions'Elab_Spec'Address,
6014         System.Stack_Checking'Elab_Spec'Address,
6015         System.Soft_Links'Elab_Body'Address,
6016         System.Secondary_Stack'Elab_Body'Address,
6017         Ada.Tags'Elab_Spec'Address,
6018         Ada.Tags'Elab_Body'Address,
6019         Ada.Streams'Elab_Spec'Address,
6020         System.Finalization_Root'Elab_Spec'Address,
6021         Ada.Exceptions'Elab_Body'Address,
6022         System.Finalization_Implementation'Elab_Spec'Address,
6023         System.Finalization_Implementation'Elab_Body'Address,
6024         Ada.Finalization'Elab_Spec'Address,
6025         Ada.Finalization.List_Controller'Elab_Spec'Address,
6026         System.File_Control_Block'Elab_Spec'Address,
6027         System.File_Io'Elab_Body'Address,
6028         Ada.Text_Io'Elab_Spec'Address,
6029         Ada.Text_Io'Elab_Body'Address);
6031    --  Start of processing for adainit
6033    begin
6035       --  Call SDP_Table_Build to build the top level procedure
6036       --  table for zero cost exception handling (omitted in
6037       --  longjmp/setjump mode).
6039       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
6041       --  Call Set_Globals to record various information for
6042       --  this partition.  The values are derived by the binder
6043       --  from information stored in the ali files by the compiler.
6045 @findex __gnat_set_globals
6046       Set_Globals
6047         (Main_Priority            => -1,
6048          --  Priority of main program, -1 if no pragma Priority used
6050          Time_Slice_Value         => -1,
6051          --  Time slice from Time_Slice pragma, -1 if none used
6053          WC_Encoding              => 'b',
6054          --  Wide_Character encoding used, default is brackets
6056          Locking_Policy           => ' ',
6057          --  Locking_Policy used, default of space means not
6058          --  specified, otherwise it is the first character of
6059          --  the policy name.
6061          Queuing_Policy           => ' ',
6062          --  Queuing_Policy used, default of space means not
6063          --  specified, otherwise it is the first character of
6064          --  the policy name.
6066          Task_Dispatching_Policy  => ' ',
6067          --  Task_Dispatching_Policy used, default of space means
6068          --  not specified, otherwise first character of the
6069          --  policy name.
6071          Adafinal                 => System.Null_Address,
6072          --  Address of Adafinal routine, not used anymore
6074          Unreserve_All_Interrupts => 0,
6075          --  Set true if pragma Unreserve_All_Interrupts was used
6077          Exception_Tracebacks     => 0);
6078          --  Indicates if exception tracebacks are enabled
6080       Elab_Final_Code := 1;
6082       --  Now we have the elaboration calls for all units in the partition.
6083       --  The Elab_Spec and Elab_Body attributes generate references to the
6084       --  implicit elaboration procedures generated by the compiler for
6085       --  each unit that requires elaboration.
6087       if not E040 then
6088          Interfaces.C_Streams'Elab_Spec;
6089       end if;
6090       E040 := True;
6091       if not E008 then
6092          Ada.Exceptions'Elab_Spec;
6093       end if;
6094       if not E014 then
6095          System.Exception_Table'Elab_Body;
6096          E014 := True;
6097       end if;
6098       if not E053 then
6099          Ada.Io_Exceptions'Elab_Spec;
6100          E053 := True;
6101       end if;
6102       if not E017 then
6103          System.Exceptions'Elab_Spec;
6104          E017 := True;
6105       end if;
6106       if not E030 then
6107          System.Stack_Checking'Elab_Spec;
6108       end if;
6109       if not E028 then
6110          System.Soft_Links'Elab_Body;
6111          E028 := True;
6112       end if;
6113       E030 := True;
6114       if not E024 then
6115          System.Secondary_Stack'Elab_Body;
6116          E024 := True;
6117       end if;
6118       if not E035 then
6119          Ada.Tags'Elab_Spec;
6120       end if;
6121       if not E035 then
6122          Ada.Tags'Elab_Body;
6123          E035 := True;
6124       end if;
6125       if not E033 then
6126          Ada.Streams'Elab_Spec;
6127          E033 := True;
6128       end if;
6129       if not E046 then
6130          System.Finalization_Root'Elab_Spec;
6131       end if;
6132       E046 := True;
6133       if not E008 then
6134          Ada.Exceptions'Elab_Body;
6135          E008 := True;
6136       end if;
6137       if not E048 then
6138          System.Finalization_Implementation'Elab_Spec;
6139       end if;
6140       if not E048 then
6141          System.Finalization_Implementation'Elab_Body;
6142          E048 := True;
6143       end if;
6144       if not E044 then
6145          Ada.Finalization'Elab_Spec;
6146       end if;
6147       E044 := True;
6148       if not E057 then
6149          Ada.Finalization.List_Controller'Elab_Spec;
6150       end if;
6151       E057 := True;
6152       if not E055 then
6153          System.File_Control_Block'Elab_Spec;
6154          E055 := True;
6155       end if;
6156       if not E042 then
6157          System.File_Io'Elab_Body;
6158          E042 := True;
6159       end if;
6160       if not E006 then
6161          Ada.Text_Io'Elab_Spec;
6162       end if;
6163       if not E006 then
6164          Ada.Text_Io'Elab_Body;
6165          E006 := True;
6166       end if;
6168       Elab_Final_Code := 0;
6169    end adainit;
6171    --------------
6172    -- adafinal --
6173    --------------
6175 @findex adafinal
6176    procedure adafinal is
6177    begin
6178       Do_Finalize;
6179    end adafinal;
6181    ----------
6182    -- main --
6183    ----------
6185    --  main is actually a function, as in the ANSI C standard,
6186    --  defined to return the exit status. The three parameters
6187    --  are the argument count, argument values and environment
6188    --  pointer.
6190 @findex Main Program
6191    function main
6192      (argc : Integer;
6193       argv : System.Address;
6194       envp : System.Address)
6195       return Integer
6196    is
6197       --  The initialize routine performs low level system
6198       --  initialization using a standard library routine which
6199       --  sets up signal handling and performs any other
6200       --  required setup. The routine can be found in file
6201       --  a-init.c.
6203 @findex __gnat_initialize
6204       procedure initialize;
6205       pragma Import (C, initialize, "__gnat_initialize");
6207       --  The finalize routine performs low level system
6208       --  finalization using a standard library routine. The
6209       --  routine is found in file a-final.c and in the standard
6210       --  distribution is a dummy routine that does nothing, so
6211       --  really this is a hook for special user finalization.
6213 @findex __gnat_finalize
6214       procedure finalize;
6215       pragma Import (C, finalize, "__gnat_finalize");
6217       --  We get to the main program of the partition by using
6218       --  pragma Import because if we try to with the unit and
6219       --  call it Ada style, then not only do we waste time
6220       --  recompiling it, but also, we don't really know the right
6221       --  switches (e.g. identifier character set) to be used
6222       --  to compile it.
6224       procedure Ada_Main_Program;
6225       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
6227    --  Start of processing for main
6229    begin
6230       --  Save global variables
6232       gnat_argc := argc;
6233       gnat_argv := argv;
6234       gnat_envp := envp;
6236       --  Call low level system initialization
6238       Initialize;
6240       --  Call our generated Ada initialization routine
6242       adainit;
6244       --  This is the point at which we want the debugger to get
6245       --  control
6247       Break_Start;
6249       --  Now we call the main program of the partition
6251       Ada_Main_Program;
6253       --  Perform Ada finalization
6255       adafinal;
6257       --  Perform low level system finalization
6259       Finalize;
6261       --  Return the proper exit status
6262       return (gnat_exit_status);
6263    end;
6265 --  This section is entirely comments, so it has no effect on the
6266 --  compilation of the Ada_Main package. It provides the list of
6267 --  object files and linker options, as well as some standard
6268 --  libraries needed for the link. The gnatlink utility parses
6269 --  this b~hello.adb file to read these comment lines to generate
6270 --  the appropriate command line arguments for the call to the
6271 --  system linker. The BEGIN/END lines are used for sentinels for
6272 --  this parsing operation.
6274 --  The exact file names will of course depend on the environment,
6275 --  host/target and location of files on the host system.
6277 @findex Object file list
6278 -- BEGIN Object file/option list
6279    --   ./hello.o
6280    --   -L./
6281    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
6282    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
6283 -- END Object file/option list
6285 end ada_main;
6287 @end smallexample
6289 @noindent
6290 The Ada code in the above example is exactly what is generated by the
6291 binder. We have added comments to more clearly indicate the function
6292 of each part of the generated @code{Ada_Main} package.
6294 The code is standard Ada in all respects, and can be processed by any
6295 tools that handle Ada. In particular, it is possible to use the debugger
6296 in Ada mode to debug the generated Ada_Main package. For example, suppose
6297 that for reasons that you do not understand, your program is blowing up
6298 during elaboration of the body of @code{Ada.Text_IO}. To chase this bug
6299 down, you can place a breakpoint on the call:
6301 @smallexample
6302 Ada.Text_Io'Elab_Body;
6303 @end smallexample
6305 @noindent
6306 and trace the elaboration routine for this package to find out where
6307 the problem might be (more usually of course you would be debugging
6308 elaboration code in your own application).
6310 @node Generating the Binder Program in C
6311 @section Generating the Binder Program in C
6312 @noindent
6313 In most normal usage, the default mode of @code{gnatbind} which is to
6314 generate the main package in Ada, as described in the previous section.
6315 In particular, this means that any Ada programmer can read and understand
6316 the generated main program. It can also be debugged just like any other
6317 Ada code provided the @code{-g} switch is used for @code{gnatbind}
6318 and @code{gnatlink}.
6320 However for some purposes it may be convenient to generate the main
6321 program in C rather than Ada. This may for example be helpful when you
6322 are generating a mixed language program with the main program in C. The
6323 GNAT compiler itself is an example. The use of the @code{-C} switch
6324 for both @code{gnatbind} and @code{gnatlink} will cause the program to
6325 be generated in C (and compiled using the gnu C compiler). The
6326 following shows the C code generated for the same "Hello World"
6327 program:
6329 @smallexample
6331 #ifdef __STDC__
6332 #define PARAMS(paramlist) paramlist
6333 #else
6334 #define PARAMS(paramlist) ()
6335 #endif
6337 extern void __gnat_set_globals
6338  PARAMS ((int, int, int, int, int, int,
6339           void (*) PARAMS ((void)), int, int));
6340 extern void adafinal PARAMS ((void));
6341 extern void adainit PARAMS ((void));
6342 extern void system__standard_library__adafinal PARAMS ((void));
6343 extern int main PARAMS ((int, char **, char **));
6344 extern void exit PARAMS ((int));
6345 extern void __gnat_break_start PARAMS ((void));
6346 extern void _ada_hello PARAMS ((void));
6347 extern void __gnat_initialize PARAMS ((void));
6348 extern void __gnat_finalize PARAMS ((void));
6350 extern void ada__exceptions___elabs PARAMS ((void));
6351 extern void system__exceptions___elabs PARAMS ((void));
6352 extern void interfaces__c_streams___elabs PARAMS ((void));
6353 extern void system__exception_table___elabb PARAMS ((void));
6354 extern void ada__io_exceptions___elabs PARAMS ((void));
6355 extern void system__stack_checking___elabs PARAMS ((void));
6356 extern void system__soft_links___elabb PARAMS ((void));
6357 extern void system__secondary_stack___elabb PARAMS ((void));
6358 extern void ada__tags___elabs PARAMS ((void));
6359 extern void ada__tags___elabb PARAMS ((void));
6360 extern void ada__streams___elabs PARAMS ((void));
6361 extern void system__finalization_root___elabs PARAMS ((void));
6362 extern void ada__exceptions___elabb PARAMS ((void));
6363 extern void system__finalization_implementation___elabs PARAMS ((void));
6364 extern void system__finalization_implementation___elabb PARAMS ((void));
6365 extern void ada__finalization___elabs PARAMS ((void));
6366 extern void ada__finalization__list_controller___elabs PARAMS ((void));
6367 extern void system__file_control_block___elabs PARAMS ((void));
6368 extern void system__file_io___elabb PARAMS ((void));
6369 extern void ada__text_io___elabs PARAMS ((void));
6370 extern void ada__text_io___elabb PARAMS ((void));
6372 extern int __gnat_inside_elab_final_code;
6374 extern int gnat_argc;
6375 extern char **gnat_argv;
6376 extern char **gnat_envp;
6377 extern int gnat_exit_status;
6379 char __gnat_version[] = "GNAT Version: 3.15w (20010315)";
6380 void adafinal () @{
6381    system__standard_library__adafinal ();
6384 void adainit ()
6386    extern char ada__exceptions_E;
6387    extern char system__exceptions_E;
6388    extern char interfaces__c_streams_E;
6389    extern char system__exception_table_E;
6390    extern char ada__io_exceptions_E;
6391    extern char system__secondary_stack_E;
6392    extern char system__stack_checking_E;
6393    extern char system__soft_links_E;
6394    extern char ada__tags_E;
6395    extern char ada__streams_E;
6396    extern char system__finalization_root_E;
6397    extern char system__finalization_implementation_E;
6398    extern char ada__finalization_E;
6399    extern char ada__finalization__list_controller_E;
6400    extern char system__file_control_block_E;
6401    extern char system__file_io_E;
6402    extern char ada__text_io_E;
6404    extern void *__gnat_hello__SDP;
6405    extern void *__gnat_ada__text_io__SDP;
6406    extern void *__gnat_ada__exceptions__SDP;
6407    extern void *__gnat_gnat__heap_sort_a__SDP;
6408    extern void *__gnat_system__exception_table__SDP;
6409    extern void *__gnat_system__machine_state_operations__SDP;
6410    extern void *__gnat_system__secondary_stack__SDP;
6411    extern void *__gnat_system__parameters__SDP;
6412    extern void *__gnat_system__soft_links__SDP;
6413    extern void *__gnat_system__stack_checking__SDP;
6414    extern void *__gnat_system__traceback__SDP;
6415    extern void *__gnat_ada__streams__SDP;
6416    extern void *__gnat_ada__tags__SDP;
6417    extern void *__gnat_system__string_ops__SDP;
6418    extern void *__gnat_interfaces__c_streams__SDP;
6419    extern void *__gnat_system__file_io__SDP;
6420    extern void *__gnat_ada__finalization__SDP;
6421    extern void *__gnat_system__finalization_root__SDP;
6422    extern void *__gnat_system__finalization_implementation__SDP;
6423    extern void *__gnat_system__string_ops_concat_3__SDP;
6424    extern void *__gnat_system__stream_attributes__SDP;
6425    extern void *__gnat_system__file_control_block__SDP;
6426    extern void *__gnat_ada__finalization__list_controller__SDP;
6428    void **st[23] = @{
6429      &__gnat_hello__SDP,
6430      &__gnat_ada__text_io__SDP,
6431      &__gnat_ada__exceptions__SDP,
6432      &__gnat_gnat__heap_sort_a__SDP,
6433      &__gnat_system__exception_table__SDP,
6434      &__gnat_system__machine_state_operations__SDP,
6435      &__gnat_system__secondary_stack__SDP,
6436      &__gnat_system__parameters__SDP,
6437      &__gnat_system__soft_links__SDP,
6438      &__gnat_system__stack_checking__SDP,
6439      &__gnat_system__traceback__SDP,
6440      &__gnat_ada__streams__SDP,
6441      &__gnat_ada__tags__SDP,
6442      &__gnat_system__string_ops__SDP,
6443      &__gnat_interfaces__c_streams__SDP,
6444      &__gnat_system__file_io__SDP,
6445      &__gnat_ada__finalization__SDP,
6446      &__gnat_system__finalization_root__SDP,
6447      &__gnat_system__finalization_implementation__SDP,
6448      &__gnat_system__string_ops_concat_3__SDP,
6449      &__gnat_system__stream_attributes__SDP,
6450      &__gnat_system__file_control_block__SDP,
6451      &__gnat_ada__finalization__list_controller__SDP@};
6453    extern void ada__exceptions___elabs ();
6454    extern void system__exceptions___elabs ();
6455    extern void interfaces__c_streams___elabs ();
6456    extern void system__exception_table___elabb ();
6457    extern void ada__io_exceptions___elabs ();
6458    extern void system__stack_checking___elabs ();
6459    extern void system__soft_links___elabb ();
6460    extern void system__secondary_stack___elabb ();
6461    extern void ada__tags___elabs ();
6462    extern void ada__tags___elabb ();
6463    extern void ada__streams___elabs ();
6464    extern void system__finalization_root___elabs ();
6465    extern void ada__exceptions___elabb ();
6466    extern void system__finalization_implementation___elabs ();
6467    extern void system__finalization_implementation___elabb ();
6468    extern void ada__finalization___elabs ();
6469    extern void ada__finalization__list_controller___elabs ();
6470    extern void system__file_control_block___elabs ();
6471    extern void system__file_io___elabb ();
6472    extern void ada__text_io___elabs ();
6473    extern void ada__text_io___elabb ();
6475    void (*ea[23]) () = @{
6476      adainit,
6477      system__standard_library__adafinal,
6478      ada__exceptions___elabs,
6479      system__exceptions___elabs,
6480      interfaces__c_streams___elabs,
6481      system__exception_table___elabb,
6482      ada__io_exceptions___elabs,
6483      system__stack_checking___elabs,
6484      system__soft_links___elabb,
6485      system__secondary_stack___elabb,
6486      ada__tags___elabs,
6487      ada__tags___elabb,
6488      ada__streams___elabs,
6489      system__finalization_root___elabs,
6490      ada__exceptions___elabb,
6491      system__finalization_implementation___elabs,
6492      system__finalization_implementation___elabb,
6493      ada__finalization___elabs,
6494      ada__finalization__list_controller___elabs,
6495      system__file_control_block___elabs,
6496      system__file_io___elabb,
6497      ada__text_io___elabs,
6498      ada__text_io___elabb@};
6500    __gnat_SDP_Table_Build (&st, 23, ea, 23);
6501    __gnat_set_globals (
6502       -1,      /* Main_Priority              */
6503       -1,      /* Time_Slice_Value           */
6504       'b',     /* WC_Encoding                */
6505       ' ',     /* Locking_Policy             */
6506       ' ',     /* Queuing_Policy             */
6507       ' ',     /* Tasking_Dispatching_Policy */
6508       0,       /* Finalization routine address, not used anymore */
6509       0,       /* Unreserve_All_Interrupts */
6510       0);      /* Exception_Tracebacks */
6512    __gnat_inside_elab_final_code = 1;
6514    if (ada__exceptions_E == 0) @{
6515       ada__exceptions___elabs ();
6516    @}
6517    if (system__exceptions_E == 0) @{
6518       system__exceptions___elabs ();
6519       system__exceptions_E++;
6520    @}
6521    if (interfaces__c_streams_E == 0) @{
6522       interfaces__c_streams___elabs ();
6523    @}
6524    interfaces__c_streams_E = 1;
6525    if (system__exception_table_E == 0) @{
6526       system__exception_table___elabb ();
6527       system__exception_table_E++;
6528    @}
6529    if (ada__io_exceptions_E == 0) @{
6530       ada__io_exceptions___elabs ();
6531       ada__io_exceptions_E++;
6532    @}
6533    if (system__stack_checking_E == 0) @{
6534       system__stack_checking___elabs ();
6535    @}
6536    if (system__soft_links_E == 0) @{
6537       system__soft_links___elabb ();
6538       system__soft_links_E++;
6539    @}
6540    system__stack_checking_E = 1;
6541    if (system__secondary_stack_E == 0) @{
6542       system__secondary_stack___elabb ();
6543       system__secondary_stack_E++;
6544    @}
6545    if (ada__tags_E == 0) @{
6546       ada__tags___elabs ();
6547    @}
6548    if (ada__tags_E == 0) @{
6549       ada__tags___elabb ();
6550       ada__tags_E++;
6551    @}
6552    if (ada__streams_E == 0) @{
6553       ada__streams___elabs ();
6554       ada__streams_E++;
6555    @}
6556    if (system__finalization_root_E == 0) @{
6557       system__finalization_root___elabs ();
6558    @}
6559    system__finalization_root_E = 1;
6560    if (ada__exceptions_E == 0) @{
6561       ada__exceptions___elabb ();
6562       ada__exceptions_E++;
6563    @}
6564    if (system__finalization_implementation_E == 0) @{
6565       system__finalization_implementation___elabs ();
6566    @}
6567    if (system__finalization_implementation_E == 0) @{
6568       system__finalization_implementation___elabb ();
6569       system__finalization_implementation_E++;
6570    @}
6571    if (ada__finalization_E == 0) @{
6572       ada__finalization___elabs ();
6573    @}
6574    ada__finalization_E = 1;
6575    if (ada__finalization__list_controller_E == 0) @{
6576       ada__finalization__list_controller___elabs ();
6577    @}
6578    ada__finalization__list_controller_E = 1;
6579    if (system__file_control_block_E == 0) @{
6580       system__file_control_block___elabs ();
6581       system__file_control_block_E++;
6582    @}
6583    if (system__file_io_E == 0) @{
6584       system__file_io___elabb ();
6585       system__file_io_E++;
6586    @}
6587    if (ada__text_io_E == 0) @{
6588       ada__text_io___elabs ();
6589    @}
6590    if (ada__text_io_E == 0) @{
6591       ada__text_io___elabb ();
6592       ada__text_io_E++;
6593    @}
6595    __gnat_inside_elab_final_code = 0;
6597 int main (argc, argv, envp)
6598     int argc;
6599     char **argv;
6600     char **envp;
6602    gnat_argc = argc;
6603    gnat_argv = argv;
6604    gnat_envp = envp;
6606    __gnat_initialize ();
6607    adainit ();
6608    __gnat_break_start ();
6610    _ada_hello ();
6612    system__standard_library__adafinal ();
6613    __gnat_finalize ();
6614    exit (gnat_exit_status);
6616 unsigned helloB = 0x7880BEB3;
6617 unsigned system__standard_libraryB = 0x0D24CBD0;
6618 unsigned system__standard_libraryS = 0x3283DBEB;
6619 unsigned adaS = 0x2359F9ED;
6620 unsigned ada__text_ioB = 0x47C85FC4;
6621 unsigned ada__text_ioS = 0x496FE45C;
6622 unsigned ada__exceptionsB = 0x74F50187;
6623 unsigned ada__exceptionsS = 0x6736945B;
6624 unsigned gnatS = 0x156A40CF;
6625 unsigned gnat__heap_sort_aB = 0x033DABE0;
6626 unsigned gnat__heap_sort_aS = 0x6AB38FEA;
6627 unsigned systemS = 0x0331C6FE;
6628 unsigned system__exceptionsS = 0x20C9ECA4;
6629 unsigned system__exception_tableB = 0x68A22947;
6630 unsigned system__exception_tableS = 0x394BADD5;
6631 unsigned gnat__htableB = 0x08258E1B;
6632 unsigned gnat__htableS = 0x367D5222;
6633 unsigned system__machine_state_operationsB = 0x4F3B7492;
6634 unsigned system__machine_state_operationsS = 0x182F5CF4;
6635 unsigned system__storage_elementsB = 0x2F1EB794;
6636 unsigned system__storage_elementsS = 0x102C83C7;
6637 unsigned system__secondary_stackB = 0x1574B6E9;
6638 unsigned system__secondary_stackS = 0x708E260A;
6639 unsigned system__parametersB = 0x56D770CD;
6640 unsigned system__parametersS = 0x237E39BE;
6641 unsigned system__soft_linksB = 0x08AB6B2C;
6642 unsigned system__soft_linksS = 0x1E2491F3;
6643 unsigned system__stack_checkingB = 0x476457A0;
6644 unsigned system__stack_checkingS = 0x5299FCED;
6645 unsigned system__tracebackB = 0x2971EBDE;
6646 unsigned system__tracebackS = 0x2E9C3122;
6647 unsigned ada__streamsS = 0x7C25DE96;
6648 unsigned ada__tagsB = 0x39ADFFA2;
6649 unsigned ada__tagsS = 0x769A0464;
6650 unsigned system__string_opsB = 0x5EB646AB;
6651 unsigned system__string_opsS = 0x63CED018;
6652 unsigned interfacesS = 0x0357E00A;
6653 unsigned interfaces__c_streamsB = 0x3784FB72;
6654 unsigned interfaces__c_streamsS = 0x2E723019;
6655 unsigned system__file_ioB = 0x623358EA;
6656 unsigned system__file_ioS = 0x31F873E6;
6657 unsigned ada__finalizationB = 0x6843F68A;
6658 unsigned ada__finalizationS = 0x63305874;
6659 unsigned system__finalization_rootB = 0x31E56CE1;
6660 unsigned system__finalization_rootS = 0x23169EF3;
6661 unsigned system__finalization_implementationB = 0x6CCBA70E;
6662 unsigned system__finalization_implementationS = 0x604AA587;
6663 unsigned system__string_ops_concat_3B = 0x572E3F58;
6664 unsigned system__string_ops_concat_3S = 0x01F57876;
6665 unsigned system__stream_attributesB = 0x1D4F93E8;
6666 unsigned system__stream_attributesS = 0x30B2EC3D;
6667 unsigned ada__io_exceptionsS = 0x34054F96;
6668 unsigned system__unsigned_typesS = 0x7B9E7FE3;
6669 unsigned system__file_control_blockS = 0x2FF876A8;
6670 unsigned ada__finalization__list_controllerB = 0x5760634A;
6671 unsigned ada__finalization__list_controllerS = 0x5D851835;
6673 /* BEGIN ELABORATION ORDER
6674 ada (spec)
6675 gnat (spec)
6676 gnat.heap_sort_a (spec)
6677 gnat.htable (spec)
6678 gnat.htable (body)
6679 interfaces (spec)
6680 system (spec)
6681 system.parameters (spec)
6682 system.standard_library (spec)
6683 ada.exceptions (spec)
6684 system.exceptions (spec)
6685 system.parameters (body)
6686 gnat.heap_sort_a (body)
6687 interfaces.c_streams (spec)
6688 interfaces.c_streams (body)
6689 system.exception_table (spec)
6690 system.exception_table (body)
6691 ada.io_exceptions (spec)
6692 system.storage_elements (spec)
6693 system.storage_elements (body)
6694 system.machine_state_operations (spec)
6695 system.machine_state_operations (body)
6696 system.secondary_stack (spec)
6697 system.stack_checking (spec)
6698 system.soft_links (spec)
6699 system.soft_links (body)
6700 system.stack_checking (body)
6701 system.secondary_stack (body)
6702 system.standard_library (body)
6703 system.string_ops (spec)
6704 system.string_ops (body)
6705 ada.tags (spec)
6706 ada.tags (body)
6707 ada.streams (spec)
6708 system.finalization_root (spec)
6709 system.finalization_root (body)
6710 system.string_ops_concat_3 (spec)
6711 system.string_ops_concat_3 (body)
6712 system.traceback (spec)
6713 system.traceback (body)
6714 ada.exceptions (body)
6715 system.unsigned_types (spec)
6716 system.stream_attributes (spec)
6717 system.stream_attributes (body)
6718 system.finalization_implementation (spec)
6719 system.finalization_implementation (body)
6720 ada.finalization (spec)
6721 ada.finalization (body)
6722 ada.finalization.list_controller (spec)
6723 ada.finalization.list_controller (body)
6724 system.file_control_block (spec)
6725 system.file_io (spec)
6726 system.file_io (body)
6727 ada.text_io (spec)
6728 ada.text_io (body)
6729 hello (body)
6730    END ELABORATION ORDER */
6732 /* BEGIN Object file/option list
6733 ./hello.o
6734 -L./
6735 -L/usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/
6736 /usr/local/gnat/lib/gcc-lib/alpha-dec-osf5.1/2.8.1/adalib/libgnat.a
6737 -lexc
6738    END Object file/option list */
6740 @end smallexample
6742 @noindent
6743 Here again, the C code is exactly what is generated by the binder. The
6744 functions of the various parts of this code correspond in an obvious
6745 manner with the commented Ada code shown in the example in the previous
6746 section.
6748 @node Consistency-Checking Modes
6749 @section Consistency-Checking Modes
6751 @noindent
6752 As described in the previous section, by default @code{gnatbind} checks
6753 that object files are consistent with one another and are consistent
6754 with any source files it can locate. The following switches control binder
6755 access to sources.
6757 @table @code
6758 @item ^-s^/READ_SOURCES=ALL^
6759 @cindex @code{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
6760 Require source files to be present. In this mode, the binder must be
6761 able to locate all source files that are referenced, in order to check
6762 their consistency. In normal mode, if a source file cannot be located it
6763 is simply ignored. If you specify this switch, a missing source
6764 file is an error.
6766 @item ^-x^/READ_SOURCES=NONE^
6767 @cindex @code{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
6768 Exclude source files. In this mode, the binder only checks that ALI
6769 files are consistent with one another. Source files are not accessed.
6770 The binder runs faster in this mode, and there is still a guarantee that
6771 the resulting program is self-consistent.
6772 If a source file has been edited since it was last compiled, and you
6773 specify this switch, the binder will not detect that the object
6774 file is out of date with respect to the source file. Note that this is the
6775 mode that is automatically used by @code{gnatmake} because in this
6776 case the checking against sources has already been performed by
6777 @code{gnatmake} in the course of compilation (i.e. before binding).
6779 @ifset vms
6780 @item /READ_SOURCES=AVAILABLE
6781 This is the default mode in which source files are checked if they are
6782 available, and ignored if they are not available.
6783 @end ifset
6784 @end table
6786 @node Binder Error Message Control
6787 @section Binder Error Message Control
6789 @noindent
6790 The following switches provide control over the generation of error
6791 messages from the binder:
6793 @table @code
6794 @item ^-v^/REPORT_ERRORS=VERBOSE^
6795 @cindex @code{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
6796 Verbose mode. In the normal mode, brief error messages are generated to
6797 @file{stderr}. If this switch is present, a header is written
6798 to @file{stdout} and any error messages are directed to @file{stdout}.
6799 All that is written to @file{stderr} is a brief summary message.
6801 @item ^-b^/REPORT_ERRORS=BRIEF^
6802 @cindex @code{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
6803 Generate brief error messages to @file{stderr} even if verbose mode is
6804 specified. This is relevant only when used with the
6805 @code{^-v^/REPORT_ERRORS=VERBOSE^} switch.
6807 @ifclear vms
6808 @item -m@var{n}
6809 @cindex @code{-m} (@code{gnatbind})
6810 Limits the number of error messages to @var{n}, a decimal integer in the
6811 range 1-999. The binder terminates immediately if this limit is reached.
6813 @item -M@var{xxx}
6814 @cindex @code{-M} (@code{gnatbind})
6815 Renames the generated main program from @code{main} to @code{xxx}.
6816 This is useful in the case of some cross-building environments, where
6817 the actual main program is separate from the one generated
6818 by @code{gnatbind}.
6819 @end ifclear
6821 @item ^-ws^/WARNINGS=SUPPRESS^
6822 @cindex @code{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
6823 @cindex Warnings
6824 Suppress all warning messages.
6826 @item ^-we^/WARNINGS=ERROR^
6827 @cindex @code{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
6828 Treat any warning messages as fatal errors.
6830 @ifset vms
6831 @item /WARNINGS=NORMAL
6832 Standard mode with warnings generated, but warnings do not get treated
6833 as errors.
6834 @end ifset
6836 @item ^-t^/NOTIME_STAMP_CHECK^
6837 @cindex @code{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
6838 @cindex Time stamp checks, in binder
6839 @cindex Binder consistency checks
6840 @cindex Consistency checks, in binder
6841 The binder performs a number of consistency checks including:
6843 @itemize @bullet
6844 @item
6845 Check that time stamps of a given source unit are consistent
6846 @item
6847 Check that checksums of a given source unit are consistent
6848 @item
6849 Check that consistent versions of @code{GNAT} were used for compilation
6850 @item
6851 Check consistency of configuration pragmas as required
6852 @end itemize
6854 @noindent
6855 Normally failure of such checks, in accordance with the consistency
6856 requirements of the Ada Reference Manual, causes error messages to be
6857 generated which abort the binder and prevent the output of a binder
6858 file and subsequent link to obtain an executable.
6860 The @code{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
6861 into warnings, so that
6862 binding and linking can continue to completion even in the presence of such
6863 errors. The result may be a failed link (due to missing symbols), or a
6864 non-functional executable which has undefined semantics.
6865 @emph{This means that
6866 @code{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
6867 with extreme care.}
6868 @end table
6870 @node Elaboration Control
6871 @section Elaboration Control
6873 @noindent
6874 The following switches provide additional control over the elaboration
6875 order. For full details see @xref{Elaboration Order Handling in GNAT}.
6877 @table @code
6878 @item ^-p^/PESSIMISTIC_ELABORATION^
6879 @cindex @code{^-h^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
6880 Normally the binder attempts to choose an elaboration order that is
6881 likely to minimize the likelihood of an elaboration order error resulting
6882 in raising a @code{Program_Error} exception. This switch reverses the
6883 action of the binder, and requests that it deliberately choose an order
6884 that is likely to maximize the likelihood of an elaboration error.
6885 This is useful in ensuring portability and avoiding dependence on
6886 accidental fortuitous elaboration ordering.
6888 Normally it only makes sense to use the @code{-p} switch if dynamic
6889 elaboration checking is used (@option{-gnatE} switch used for compilation).
6890 This is because in the default static elaboration mode, all necessary
6891 @code{Elaborate_All} pragmas are implicitly inserted. These implicit
6892 pragmas are still respected by the binder in @code{-p} mode, so a
6893 safe elaboration order is assured.
6894 @end table
6896 @node Output Control
6897 @section Output Control
6899 @noindent
6900 The following switches allow additional control over the output
6901 generated by the binder.
6903 @table @code
6905 @item ^-A^/BIND_FILE=ADA^
6906 @cindex @code{^-A^/BIND_FILE=ADA^} (@code{gnatbind})
6907 Generate binder program in Ada (default). The binder program is named
6908 @file{b~@var{mainprog}.adb} by default. This can be changed with
6909 @code{-o} @code{gnatbind} option.
6911 @item ^-c^/NOOUTPUT^
6912 @cindex @code{^-c^/NOOUTPUT^} (@code{gnatbind})
6913 Check only. Do not generate the binder output file. In this mode the
6914 binder performs all error checks but does not generate an output file.
6916 @item ^-C^/BIND_FILE=C^
6917 @cindex @code{^-C^/BIND_FILE=C^} (@code{gnatbind})
6918 Generate binder program in C. The binder program is named
6919 @file{b_@var{mainprog}.c}. This can be changed with @code{-o} @code{gnatbind}
6920 option.
6922 @item ^-e^/ELABORATION_DEPENDENCIES^
6923 @cindex @code{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
6924 Output complete list of elaboration-order dependencies, showing the
6925 reason for each dependency. This output can be rather extensive but may
6926 be useful in diagnosing problems with elaboration order. The output is
6927 written to @file{stdout}.
6929 @item ^-h^/HELP^
6930 @cindex @code{^-h^/HELP^} (@code{gnatbind})
6931 Output usage information. The output is written to @file{stdout}.
6933 @item ^-K^/LINKER_OPTION_LIST^
6934 @cindex @code{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
6935 Output linker options to @file{stdout}. Includes library search paths,
6936 contents of pragmas Ident and Linker_Options, and libraries added
6937 by @code{gnatbind}.
6939 @item ^-l^/ORDER_OF_ELABORATION^
6940 @cindex @code{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
6941 Output chosen elaboration order. The output is written to @file{stdout}.
6943 @item ^-O^/OBJECT_LIST^
6944 @cindex @code{^-O^/OBJECT_LIST^} (@code{gnatbind})
6945 Output full names of all the object files that must be linked to provide
6946 the Ada component of the program. The output is written to @file{stdout}.
6947 This list includes the files explicitly supplied and referenced by the user
6948 as well as implicitly referenced run-time unit files. The latter are
6949 omitted if the corresponding units reside in shared libraries. The
6950 directory names for the run-time units depend on the system configuration.
6952 @item ^-o ^/OUTPUT=^@var{file}
6953 @cindex @code{^-o^/OUTPUT^} (@code{gnatbind})
6954 Set name of output file to @var{file} instead of the normal
6955 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
6956 binder generated body filename. In C mode you would normally give
6957 @var{file} an extension of @file{.c} because it will be a C source program.
6958 Note that if this option is used, then linking must be done manually.
6959 It is not possible to use gnatlink in this case, since it cannot locate
6960 the binder file.
6962 @item ^-r^/RESTRICTION_LIST^
6963 @cindex @code{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
6964 Generate list of @code{pragma Rerstrictions} that could be applied to
6965 the current unit. This is useful for code audit purposes, and also may
6966 be used to improve code generation in some cases.
6968 @end table
6970 @node Binding with Non-Ada Main Programs
6971 @section Binding with Non-Ada Main Programs
6973 @noindent
6974 In our description so far we have assumed that the main
6975 program is in Ada, and that the task of the binder is to generate a
6976 corresponding function @code{main} that invokes this Ada main
6977 program. GNAT also supports the building of executable programs where
6978 the main program is not in Ada, but some of the called routines are
6979 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
6980 The following switch is used in this situation:
6982 @table @code
6983 @item ^-n^/NOMAIN^
6984 @cindex @code{^-n^/NOMAIN^} (@code{gnatbind})
6985 No main program. The main program is not in Ada.
6986 @end table
6988 @noindent
6989 In this case, most of the functions of the binder are still required,
6990 but instead of generating a main program, the binder generates a file
6991 containing the following callable routines:
6993 @table @code
6994 @item adainit
6995 @findex adainit
6996 You must call this routine to initialize the Ada part of the program by
6997 calling the necessary elaboration routines. A call to @code{adainit} is
6998 required before the first call to an Ada subprogram.
7000 Note that it is assumed that the basic execution environment must be setup
7001 to be appropriate for Ada execution at the point where the first Ada
7002 subprogram is called. In particular, if the Ada code will do any
7003 floating-point operations, then the FPU must be setup in an appropriate
7004 manner. For the case of the x86, for example, full precision mode is
7005 required. The procedure GNAT.Float_Control.Reset may be used to ensure
7006 that the FPU is in the right state.
7008 @item adafinal
7009 @findex adafinal
7010 You must call this routine to perform any library-level finalization
7011 required by the Ada subprograms. A call to @code{adafinal} is required
7012 after the last call to an Ada subprogram, and before the program
7013 terminates.
7014 @end table
7016 @noindent
7017 If the @code{^-n^/NOMAIN^} switch
7018 @cindex Binder, multiple input files
7019 is given, more than one ALI file may appear on
7020 the command line for @code{gnatbind}. The normal @dfn{closure}
7021 calculation is performed for each of the specified units. Calculating
7022 the closure means finding out the set of units involved by tracing
7023 @code{with} references. The reason it is necessary to be able to
7024 specify more than one ALI file is that a given program may invoke two or
7025 more quite separate groups of Ada units.
7027 The binder takes the name of its output file from the last specified ALI
7028 file, unless overridden by the use of the @code{^-o file^/OUTPUT=file^}.
7029 The output is an Ada unit in source form that can
7030 be compiled with GNAT unless the -C switch is used in which case the
7031 output is a C source file, which must be compiled using the C compiler.
7032 This compilation occurs automatically as part of the @code{gnatlink}
7033 processing.
7035 Currently the GNAT run time requires a FPU using 80 bits mode
7036 precision. Under targets where this is not the default it is required to
7037 call GNAT.Float_Control.Reset before using floating point numbers (this
7038 include float computation, float input and output) in the Ada code. A
7039 side effect is that this could be the wrong mode for the foreign code
7040 where floating point computation could be broken after this call.
7042 @node Binding Programs with No Main Subprogram
7043 @section Binding Programs with No Main Subprogram
7045 @noindent
7046 It is possible to have an Ada program which does not have a main
7047 subprogram. This program will call the elaboration routines of all the
7048 packages, then the finalization routines.
7050 The following switch is used to bind programs organized in this manner:
7052 @table @code
7053 @item ^-z^/ZERO_MAIN^
7054 @cindex @code{^-z^/ZERO_MAIN^} (@code{gnatbind})
7055 Normally the binder checks that the unit name given on the command line
7056 corresponds to a suitable main subprogram. When this switch is used,
7057 a list of ALI files can be given, and the execution of the program
7058 consists of elaboration of these units in an appropriate order.
7059 @end table
7061 @node Summary of Binder Switches
7062 @section Summary of Binder Switches
7064 @noindent
7065 The following are the switches available with @code{gnatbind}:
7067 @table @code
7068 @item ^-aO^/OBJECT_SEARCH^
7069 Specify directory to be searched for ALI files.
7071 @item ^-aI^/SOURCE_SEARCH^
7072 Specify directory to be searched for source file.
7074 @item ^-A^/BIND_FILE=ADA^
7075 Generate binder program in Ada (default)
7077 @item ^-b^/REPORT_ERRORS=BRIEF^
7078 Generate brief messages to @file{stderr} even if verbose mode set.
7080 @item ^-c^/NOOUTPUT^
7081 Check only, no generation of binder output file.
7083 @item ^-C^/BIND_FILE=C^
7084 Generate binder program in C
7086 @item ^-e^/ELABORATION_DEPENDENCIES^
7087 Output complete list of elaboration-order dependencies.
7089 @item -E
7090 Store tracebacks in exception occurrences when the target supports it.
7091 This is the default with the zero cost exception mechanism.
7092 This option is currently supported on the following targets:
7093 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
7094 See also the packages @code{GNAT.Traceback} and
7095 @code{GNAT.Traceback.Symbolic} for more information.
7096 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
7097 @code{gcc} option.
7099 @item -h
7100 Output usage (help) information
7102 @item ^-I^/SEARCH^
7103 Specify directory to be searched for source and ALI files.
7105 @item ^-I-^/NOCURRENT_DIRECTORY^
7106 Do not look for sources in the current directory where @code{gnatbind} was
7107 invoked, and do not look for ALI files in the directory containing the
7108 ALI file named in the @code{gnatbind} command line.
7110 @item ^-l^/ORDER_OF_ELABORATION^
7111 Output chosen elaboration order.
7113 @item -Lxxx
7114 Binds the units for library building. In this case the adainit and
7115 adafinal procedures (See @pxref{Binding with Non-Ada Main Programs})
7116 are renamed to xxxinit and xxxfinal. Implies -n.
7117 @ifclear vms
7118 See @pxref{GNAT and Libraries} for more details.
7119 @end ifclear
7121 @item -Mxyz
7122 Rename generated main program from main to xyz
7124 @item ^-m^/ERROR_LIMIT=^@var{n}
7125 Limit number of detected errors to @var{n} (1-999).
7126 @ifset wnt
7127 Furthermore, under Windows, the sources pointed to by the libraries path
7128 set in the registry are not searched for.
7129 @end ifset
7131 @item ^-n^/NOMAIN^
7132 No main program.
7134 @item -nostdinc
7135 Do not look for sources in the system default directory.
7137 @item -nostdlib
7138 Do not look for library files in the system default directory.
7140 @item --RTS=@var{rts-path}
7141 @cindex @code{--RTS} (@code{gnatbind})
7142 Specifies the default location of the runtime library. Same meaning as the
7143 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
7145 @item ^-o ^/OUTPUT=^@var{file}
7146 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
7147 Note that if this option is used, then linking must be done manually,
7148 gnatlink cannot be used.
7150 @item ^-O^/OBJECT_LIST^
7151 Output object list.
7153 @item -p
7154 Pessimistic (worst-case) elaboration order
7156 @item ^-s^/READ_SOURCES=ALL^
7157 Require all source files to be present.
7159 @ifclear vms
7160 @item -static
7161 Link against a static GNAT run time.
7163 @item -shared
7164 Link against a shared GNAT run time when available.
7165 @end ifclear
7167 @item ^-t^/NOTIME_STAMP_CHECK^
7168 Tolerate time stamp and other consistency errors
7170 @item -T@var{n}
7171 Set the time slice value to n microseconds. A value of zero means no time
7172 slicing and also indicates to the tasking run time to match as close as
7173 possible to the annex D requirements of the RM.
7175 @item ^-v^/REPORT_ERRORS=VERBOSE^
7176 Verbose mode. Write error messages, header, summary output to
7177 @file{stdout}.
7179 @ifclear vms
7180 @item -w@var{x}
7181 Warning mode (@var{x}=s/e for suppress/treat as error)
7182 @end ifclear
7184 @ifset vms
7185 @item /WARNINGS=NORMAL
7186 Normal warnings mode. Warnings are issued but ignored
7188 @item /WARNINGS=SUPPRESS
7189 All warning messages are suppressed
7191 @item /WARNINGS=ERROR
7192 Warning messages are treated as fatal errors
7193 @end ifset
7195 @item ^-x^/READ_SOURCES=NONE^
7196 Exclude source files (check object consistency only).
7198 @ifset vms
7199 @item /READ_SOURCES=AVAILABLE
7200 Default mode, in which sources are checked for consistency only if
7201 they are available.
7202 @end ifset
7204 @item ^-z^/ZERO_MAIN^
7205 No main subprogram.
7207 @end table
7209 @ifclear vms
7210 You may obtain this listing by running the program @code{gnatbind} with
7211 no arguments.
7212 @end ifclear
7214 @node Command-Line Access
7215 @section Command-Line Access
7217 @noindent
7218 The package @code{Ada.Command_Line} provides access to the command-line
7219 arguments and program name. In order for this interface to operate
7220 correctly, the two variables
7222 @smallexample
7223 @group
7224 @cartouche
7225 int gnat_argc;
7226 char **gnat_argv;
7227 @end cartouche
7228 @end group
7229 @end smallexample
7231 @noindent
7232 @findex gnat_argv
7233 @findex gnat_argc
7234 are declared in one of the GNAT library routines. These variables must
7235 be set from the actual @code{argc} and @code{argv} values passed to the
7236 main program. With no @code{^n^/NOMAIN^} present, @code{gnatbind}
7237 generates the C main program to automatically set these variables.
7238 If the @code{^n^/NOMAIN^} switch is used, there is no automatic way to
7239 set these variables. If they are not set, the procedures in
7240 @code{Ada.Command_Line} will not be available, and any attempt to use
7241 them will raise @code{Constraint_Error}. If command line access is
7242 required, your main program must set @code{gnat_argc} and
7243 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
7246 @node Search Paths for gnatbind
7247 @section Search Paths for @code{gnatbind}
7249 @noindent
7250 The binder takes the name of an ALI file as its argument and needs to
7251 locate source files as well as other ALI files to verify object consistency.
7253 For source files, it follows exactly the same search rules as @code{gcc}
7254 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
7255 directories searched are:
7257 @enumerate
7258 @item
7259 The directory containing the ALI file named in the command line, unless
7260 the switch @code{^-I-^/NOCURRENT_DIRECTORY^} is specified.
7262 @item
7263 All directories specified by @code{^-I^/SEARCH^}
7264 switches on the @code{gnatbind}
7265 command line, in the order given.
7267 @item
7268 @findex ADA_OBJECTS_PATH
7269 Each of the directories listed in the value of the
7270 @code{ADA_OBJECTS_PATH} ^environment variable^logical name^.
7271 @ifclear vms
7272 Construct this value
7273 exactly as the @code{PATH} environment variable: a list of directory
7274 names separated by colons (semicolons when working with the NT version
7275 of GNAT).
7276 @end ifclear
7277 @ifset vms
7278 Normally, define this value as a logical name containing a comma separated
7279 list of directory names.
7281 This variable can also be defined by means of an environment string
7282 (an argument to the DEC C exec* set of functions).
7284 Logical Name:
7285 @smallexample
7286 DEFINE ANOTHER_PATH FOO:[BAG]
7287 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7288 @end smallexample
7290 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7291 first, followed by the standard Ada 95
7292 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
7293 If this is not redefined, the user will obtain the DEC Ada83 IO packages
7294 (Text_IO, Sequential_IO, etc)
7295 instead of the Ada95 packages. Thus, in order to get the Ada 95
7296 packages by default, ADA_OBJECTS_PATH must be redefined.
7297 @end ifset
7299 @item
7300 The content of the "ada_object_path" file which is part of the GNAT
7301 installation tree and is used to store standard libraries such as the
7302 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
7303 specified.
7304 @ifclear vms
7305 @ref{Installing an Ada Library}
7306 @end ifclear
7307 @end enumerate
7309 @noindent
7310 In the binder the switch @code{^-I^/SEARCH^}
7311 is used to specify both source and
7312 library file paths. Use @code{^-aI^/SOURCE_SEARCH^}
7313 instead if you want to specify
7314 source paths only, and @code{^-aO^/LIBRARY_SEARCH^}
7315 if you want to specify library paths
7316 only. This means that for the binder
7317 @code{^-I^/SEARCH=^}@var{dir} is equivalent to
7318 @code{^-aI^/SOURCE_SEARCH=^}@var{dir}
7319 @code{^-aO^/OBJECT_SEARCH=^}@var{dir}.
7320 The binder generates the bind file (a C language source file) in the
7321 current working directory.
7323 @findex Ada
7324 @findex System
7325 @findex Interfaces
7326 @findex GNAT
7327 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7328 children make up the GNAT Run-Time Library, together with the package
7329 GNAT and its children, which contain a set of useful additional
7330 library functions provided by GNAT. The sources for these units are
7331 needed by the compiler and are kept together in one directory. The ALI
7332 files and object files generated by compiling the RTL are needed by the
7333 binder and the linker and are kept together in one directory, typically
7334 different from the directory containing the sources. In a normal
7335 installation, you need not specify these directory names when compiling
7336 or binding. Either the environment variables or the built-in defaults
7337 cause these files to be found.
7339 Besides simplifying access to the RTL, a major use of search paths is
7340 in compiling sources from multiple directories. This can make
7341 development environments much more flexible.
7343 @node Examples of gnatbind Usage
7344 @section Examples of @code{gnatbind} Usage
7346 @noindent
7347 This section contains a number of examples of using the GNAT binding
7348 utility @code{gnatbind}.
7350 @table @code
7351 @item gnatbind hello
7352 The main program @code{Hello} (source program in @file{hello.adb}) is
7353 bound using the standard switch settings. The generated main program is
7354 @file{b~hello.adb}. This is the normal, default use of the binder.
7356 @ifclear vms
7357 @item gnatbind hello -o mainprog.adb
7358 @end ifclear
7359 @ifset vms
7360 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
7361 @end ifset
7362 The main program @code{Hello} (source program in @file{hello.adb}) is
7363 bound using the standard switch settings. The generated main program is
7364 @file{mainprog.adb} with the associated spec in
7365 @file{mainprog.ads}. Note that you must specify the body here not the
7366 spec, in the case where the output is in Ada. Note that if this option
7367 is used, then linking must be done manually, since gnatlink will not
7368 be able to find the generated file.
7370 @ifclear vms
7371 @item gnatbind main -C -o mainprog.c -x
7372 @end ifclear
7373 @ifset vms
7374 @item gnatbind MAIN.ALI /BIND_FILE=C /OUTPUT=Mainprog.C /READ_SOURCES=NONE
7375 @end ifset
7376 The main program @code{Main} (source program in
7377 @file{main.adb}) is bound, excluding source files from the
7378 consistency checking, generating
7379 the file @file{mainprog.c}.
7381 @ifclear vms
7382 @item gnatbind -x main_program -C -o mainprog.c
7383 This command is exactly the same as the previous example. Switches may
7384 appear anywhere in the command line, and single letter switches may be
7385 combined into a single switch.
7386 @end ifclear
7388 @ifclear vms
7389 @item gnatbind -n math dbase -C -o ada-control.c
7390 @end ifclear
7391 @ifset vms
7392 @item gnatbind /NOMAIN math dbase /BIND_FILE=C /OUTPUT=ada-control.c
7393 @end ifset
7394 The main program is in a language other than Ada, but calls to
7395 subprograms in packages @code{Math} and @code{Dbase} appear. This call
7396 to @code{gnatbind} generates the file @file{ada-control.c} containing
7397 the @code{adainit} and @code{adafinal} routines to be called before and
7398 after accessing the Ada units.
7399 @end table
7401 @node Linking Using gnatlink
7402 @chapter Linking Using @code{gnatlink}
7403 @findex gnatlink
7405 @noindent
7406 This chapter discusses @code{gnatlink}, a utility program used to link
7407 Ada programs and build an executable file. This is a simple program
7408 that invokes the Unix linker (via the @code{gcc}
7409 command) with a correct list of object files and library references.
7410 @code{gnatlink} automatically determines the list of files and
7411 references for the Ada part of a program. It uses the binder file
7412 generated by the binder to determine this list.
7414 @menu
7415 * Running gnatlink::
7416 * Switches for gnatlink::
7417 * Setting Stack Size from gnatlink::
7418 * Setting Heap Size from gnatlink::
7419 @end menu
7421 @node Running gnatlink
7422 @section Running @code{gnatlink}
7424 @noindent
7425 The form of the @code{gnatlink} command is
7427 @smallexample
7428 $ gnatlink [@var{switches}] @var{mainprog}[.ali] [@var{non-Ada objects}]
7429       [@var{linker options}]
7430 @end smallexample
7432 @noindent
7433 @file{@var{mainprog}.ali} references the ALI file of the main program.
7434 The @file{.ali} extension of this file can be omitted. From this
7435 reference, @code{gnatlink} locates the corresponding binder file
7436 @file{b~@var{mainprog}.adb} and, using the information in this file along
7437 with the list of non-Ada objects and linker options, constructs a Unix
7438 linker command file to create the executable.
7440 The arguments following @file{@var{mainprog}.ali} are passed to the
7441 linker uninterpreted. They typically include the names of object files
7442 for units written in other languages than Ada and any library references
7443 required to resolve references in any of these foreign language units,
7444 or in @code{pragma Import} statements in any Ada units.
7446 @var{linker options} is an optional list of linker specific
7447 switches. The default linker called by gnatlink is @var{gcc} which in
7448 turn calls the appropriate system linker usually called
7449 @var{ld}. Standard options for the linker such as @code{-lmy_lib} or
7450 @code{-Ldir} can be added as is. For options that are not recognized by
7451 @var{gcc} as linker options, the @var{gcc} switches @code{-Xlinker} or
7452 @code{-Wl,} shall be used. Refer to the GCC documentation for
7453 details. Here is an example showing how to generate a linker map
7454 assuming that the underlying linker is GNU ld:
7456 @smallexample
7457 $ gnatlink my_prog -Wl,-Map,MAPFILE
7458 @end smallexample
7460 Using @var{linker options} it is possible to set the program stack and
7461 heap size. See @pxref{Setting Stack Size from gnatlink} and
7462 @pxref{Setting Heap Size from gnatlink}.
7464 @code{gnatlink} determines the list of objects required by the Ada
7465 program and prepends them to the list of objects passed to the linker.
7466 @code{gnatlink} also gathers any arguments set by the use of
7467 @code{pragma Linker_Options} and adds them to the list of arguments
7468 presented to the linker.
7470 @ifset vms
7471 @code{gnatlink} accepts the following types of extra files on the command
7472 line: objects (.OBJ), libraries (.OLB), shareable images (.EXE), and
7473 options files (.OPT). These are recognized and handled according to their
7474 extension.
7475 @end ifset
7477 @node Switches for gnatlink
7478 @section Switches for @code{gnatlink}
7480 @noindent
7481 The following switches are available with the @code{gnatlink} utility:
7483 @table @code
7485 @item ^-A^/BIND_FILE=ADA^
7486 @cindex @code{^-A^/BIND_FILE=ADA^} (@code{gnatlink})
7487 The binder has generated code in Ada. This is the default.
7489 @item ^-C^/BIND_FILE=C^
7490 @cindex @code{^-C^/BIND_FILE=C^} (@code{gnatlink})
7491 If instead of generating a file in Ada, the binder has generated one in
7492 C, then the linker needs to know about it. Use this switch to signal
7493 to @code{gnatlink} that the binder has generated C code rather than
7494 Ada code.
7496 @item -f
7497 @cindex Command line length
7498 @cindex @code{-f} (@code{gnatlink})
7499 On some targets, the command line length is limited, and @code{gnatlink}
7500 will generate a separate file for the linker if the list of object files
7501 is too long. The @code{-f} flag forces this file to be generated even if
7502 the limit is not exceeded. This is useful in some cases to deal with
7503 special situations where the command line length is exceeded.
7505 @item ^-g^/DEBUG^
7506 @cindex Debugging information, including
7507 @cindex @code{^-g^/DEBUG^} (@code{gnatlink})
7508 The option to include debugging information causes the Ada bind file (in
7509 other words, @file{b~@var{mainprog}.adb}) to be compiled with
7510 @code{^-g^/DEBUG^}.
7511 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
7512 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
7513 Without @code{^-g^/DEBUG^}, the binder removes these files by
7514 default. The same procedure apply if a C bind file was generated using
7515 @code{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames are
7516 @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
7518 @ifclear vms
7519 @item -n
7520 @cindex @code{-n} (@code{gnatlink})
7521 Do not compile the file generated by the binder. This may be used when
7522 a link is rerun with different options, but there is no need to recompile
7523 the binder file.
7524 @end ifclear
7526 @item ^-v^/VERBOSE^
7527 @cindex @code{^-v^/VERBOSE^} (@code{gnatlink})
7528 Causes additional information to be output, including a full list of the
7529 included object files. This switch option is most useful when you want
7530 to see what set of object files are being used in the link step.
7532 @ifclear vms
7533 @item -v -v
7534 @cindex @code{-v -v} (@code{gnatlink})
7535 Very verbose mode. Requests that the compiler operate in verbose mode when
7536 it compiles the binder file, and that the system linker run in verbose mode.
7537 @end ifclear
7539 @item ^-o ^/EXECUTABLE=^@var{exec-name}
7540 @cindex @code{^-o^/EXECUTABLE^} (@code{gnatlink})
7541 @var{exec-name} specifies an alternate name for the generated
7542 executable program. If this switch is omitted, the executable has the same
7543 name as the main unit. For example, @code{gnatlink try.ali} creates
7544 an executable called @file{^try^TRY.EXE^}.
7546 @ifclear vms
7547 @item -b @var{target}
7548 @cindex @code{-b} (@code{gnatlink})
7549 Compile your program to run on @var{target}, which is the name of a
7550 system configuration. You must have a GNAT cross-compiler built if
7551 @var{target} is not the same as your host system.
7553 @item -B@var{dir}
7554 @cindex @code{-B} (@code{gnatlink})
7555 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
7556 from @var{dir} instead of the default location. Only use this switch
7557 when multiple versions of the GNAT compiler are available. See the
7558 @code{gcc} manual page for further details. You would normally use the
7559 @code{-b} or @code{-V} switch instead.
7561 @item --GCC=@var{compiler_name}
7562 @cindex @code{--GCC=compiler_name} (@code{gnatlink})
7563 Program used for compiling the binder file. The default is
7564 `@code{gcc}'. You need to use quotes around @var{compiler_name} if
7565 @code{compiler_name} contains spaces or other separator characters. As
7566 an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to use
7567 @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
7568 inserted after your command name. Thus in the above example the compiler
7569 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
7570 If several @code{--GCC=compiler_name} are used, only the last
7571 @var{compiler_name} is taken into account. However, all the additional
7572 switches are also taken into account. Thus,
7573 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7574 @code{--GCC="bar -x -y -z -t"}.
7576 @item --LINK=@var{name}
7577 @cindex @code{--LINK=} (@code{gnatlink})
7578 @var{name} is the name of the linker to be invoked. This is especially
7579 useful in mixed language programs since languages such as c++ require
7580 their own linker to be used. When this switch is omitted, the default
7581 name for the linker is (@file{gcc}). When this switch is used, the
7582 specified linker is called instead of (@file{gcc}) with exactly the same
7583 parameters that would have been passed to (@file{gcc}) so if the desired
7584 linker requires different parameters it is necessary to use a wrapper
7585 script that massages the parameters before invoking the real linker. It
7586 may be useful to control the exact invocation by using the verbose
7587 switch.
7589 @end ifclear
7591 @ifset vms
7592 @item /DEBUG=TRACEBACK
7593 @cindex @code{/DEBUG=TRACEBACK} (@code{gnatlink})
7594 This qualifier causes sufficient information to be included in the
7595 executable file to allow a traceback, but does not include the full
7596 symbol information needed by the debugger.
7598 @item /IDENTIFICATION="<string>"
7599 "<string>" specifies the string to be stored in the image file identification
7600 field in the image header. It overrides any pragma Ident specified string.
7602 @item /NOINHIBIT-EXEC
7603 Generate the executable file even if there are linker warnings.
7605 @item /NOSTART_FILES
7606 Don't link in the object file containing the "main" transfer address.
7607 Used when linking with a foreign language main program compiled with a
7608 Digital compiler.
7610 @item /STATIC
7611 Prefer linking with object libraries over shareable images, even without
7612 /DEBUG.
7613 @end ifset
7615 @end table
7617 @node Setting Stack Size from gnatlink
7618 @section Setting Stack Size from @code{gnatlink}
7620 @noindent
7621 It is possible to specify the program stack size from @code{gnatlink}.
7622 Assuming that the underlying linker is GNU ld there is two ways to do so:
7624 @itemize @bullet
7626 @item using @code{-Xlinker} linker option
7628 @smallexample
7629 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
7630 @end smallexample
7632 This set the stack reserve size to 0x10000 bytes and the stack commit
7633 size to 0x1000 bytes.
7635 @item using @code{-Wl} linker option
7637 @smallexample
7638 $ gnatlink hello -Wl,--stack=0x1000000
7639 @end smallexample
7641 This set the stack reserve size to 0x1000000 bytes. Note that with
7642 @code{-Wl} option it is not possible to set the stack commit size
7643 because the coma is a separator for this option.
7645 @end itemize
7647 @node Setting Heap Size from gnatlink
7648 @section Setting Heap Size from @code{gnatlink}
7650 @noindent
7651 It is possible to specify the program heap size from @code{gnatlink}.
7652 Assuming that the underlying linker is GNU ld there is two ways to do so:
7654 @itemize @bullet
7656 @item using @code{-Xlinker} linker option
7658 @smallexample
7659 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
7660 @end smallexample
7662 This set the heap reserve size to 0x10000 bytes and the heap commit
7663 size to 0x1000 bytes.
7665 @item using @code{-Wl} linker option
7667 @smallexample
7668 $ gnatlink hello -Wl,--heap=0x1000000
7669 @end smallexample
7671 This set the heap reserve size to 0x1000000 bytes. Note that with
7672 @code{-Wl} option it is not possible to set the heap commit size
7673 because the coma is a separator for this option.
7675 @end itemize
7677 @node The GNAT Make Program gnatmake
7678 @chapter The GNAT Make Program @code{gnatmake}
7679 @findex gnatmake
7681 @menu
7682 * Running gnatmake::
7683 * Switches for gnatmake::
7684 * Mode Switches for gnatmake::
7685 * Notes on the Command Line::
7686 * How gnatmake Works::
7687 * Examples of gnatmake Usage::
7688 @end menu
7689 @noindent
7690 A typical development cycle when working on an Ada program consists of
7691 the following steps:
7693 @enumerate
7694 @item
7695 Edit some sources to fix bugs.
7697 @item
7698 Add enhancements.
7700 @item
7701 Compile all sources affected.
7703 @item
7704 Rebind and relink.
7706 @item
7707 Test.
7708 @end enumerate
7710 @noindent
7711 The third step can be tricky, because not only do the modified files
7712 @cindex Dependency rules
7713 have to be compiled, but any files depending on these files must also be
7714 recompiled. The dependency rules in Ada can be quite complex, especially
7715 in the presence of overloading, @code{use} clauses, generics and inlined
7716 subprograms.
7718 @code{gnatmake} automatically takes care of the third and fourth steps
7719 of this process. It determines which sources need to be compiled,
7720 compiles them, and binds and links the resulting object files.
7722 Unlike some other Ada make programs, the dependencies are always
7723 accurately recomputed from the new sources. The source based approach of
7724 the GNAT compilation model makes this possible. This means that if
7725 changes to the source program cause corresponding changes in
7726 dependencies, they will always be tracked exactly correctly by
7727 @code{gnatmake}.
7729 @node Running gnatmake
7730 @section Running @code{gnatmake}
7732 @noindent
7733 The usual form of the @code{gnatmake} command is
7735 @smallexample
7736 $ gnatmake [@var{switches}] @var{file_name} [@var{file_names}] [@var{mode_switches}]
7737 @end smallexample
7739 @noindent
7740 The only required argument is one @var{file_name}, which specifies
7741 a compilation unit that is a main program. Several @var{file_names} can be
7742 specified: this will result in several executables being built.
7743 If @code{switches} are present, they can be placed before the first
7744 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
7745 If @var{mode_switches} are present, they must always be placed after
7746 the last @var{file_name} and all @code{switches}.
7748 If you are using standard file extensions (.adb and .ads), then the
7749 extension may be omitted from the @var{file_name} arguments. However, if
7750 you are using non-standard extensions, then it is required that the
7751 extension be given. A relative or absolute directory path can be
7752 specified in a @var{file_name}, in which case, the input source file will
7753 be searched for in the specified directory only. Otherwise, the input
7754 source file will first be searched in the directory where
7755 @code{gnatmake} was invoked and if it is not found, it will be search on
7756 the source path of the compiler as described in
7757 @ref{Search Paths and the Run-Time Library (RTL)}.
7759 When several @var{file_names} are specified, if an executable needs to be
7760 rebuilt and relinked, all subsequent executables will be rebuilt and
7761 relinked, even if this would not be absolutely necessary.
7763 All @code{gnatmake} output (except when you specify
7764 @code{^-M^/DEPENDENCIES_LIST^}) is to
7765 @file{stderr}. The output produced by the
7766 @code{^-M^/DEPENDENCIES_LIST^} switch is send to
7767 @file{stdout}.
7769 @node Switches for gnatmake
7770 @section Switches for @code{gnatmake}
7772 @noindent
7773 You may specify any of the following switches to @code{gnatmake}:
7775 @table @code
7776 @ifclear vms
7777 @item --GCC=@var{compiler_name}
7778 @cindex @code{--GCC=compiler_name} (@code{gnatmake})
7779 Program used for compiling. The default is `@code{gcc}'. You need to use
7780 quotes around @var{compiler_name} if @code{compiler_name} contains
7781 spaces or other separator characters. As an example @code{--GCC="foo -x
7782 -y"} will instruct @code{gnatmake} to use @code{foo -x -y} as your
7783 compiler. Note that switch @code{-c} is always inserted after your
7784 command name. Thus in the above example the compiler command that will
7785 be used by @code{gnatmake} will be @code{foo -c -x -y}.
7786 If several @code{--GCC=compiler_name} are used, only the last
7787 @var{compiler_name} is taken into account. However, all the additional
7788 switches are also taken into account. Thus,
7789 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7790 @code{--GCC="bar -x -y -z -t"}.
7792 @item --GNATBIND=@var{binder_name}
7793 @cindex @code{--GNATBIND=binder_name} (@code{gnatmake})
7794 Program used for binding. The default is `@code{gnatbind}'. You need to
7795 use quotes around @var{binder_name} if @var{binder_name} contains spaces
7796 or other separator characters. As an example @code{--GNATBIND="bar -x
7797 -y"} will instruct @code{gnatmake} to use @code{bar -x -y} as your
7798 binder. Binder switches that are normally appended by @code{gnatmake} to
7799 `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
7801 @item --GNATLINK=@var{linker_name}
7802 @cindex @code{--GNATLINK=linker_name} (@code{gnatmake})
7803 Program used for linking. The default is `@code{gnatlink}'. You need to
7804 use quotes around @var{linker_name} if @var{linker_name} contains spaces
7805 or other separator characters. As an example @code{--GNATLINK="lan -x
7806 -y"} will instruct @code{gnatmake} to use @code{lan -x -y} as your
7807 linker. Linker switches that are normally appended by @code{gnatmake} to
7808 `@code{gnatlink}' are now appended to the end of @code{lan -x -y}.
7810 @end ifclear
7812 @item ^-a^/ALL_FILES^
7813 @cindex @code{^-a^/ALL_FILES^} (@code{gnatmake})
7814 Consider all files in the make process, even the GNAT internal system
7815 files (for example, the predefined Ada library files), as well as any
7816 locked files. Locked files are files whose ALI file is write-protected.
7817 By default,
7818 @code{gnatmake} does not check these files,
7819 because the assumption is that the GNAT internal files are properly up
7820 to date, and also that any write protected ALI files have been properly
7821 installed. Note that if there is an installation problem, such that one
7822 of these files is not up to date, it will be properly caught by the
7823 binder.
7824 You may have to specify this switch if you are working on GNAT
7825 itself. @code{^-a^/ALL_FILES^} is also useful in conjunction with
7826 @code{^-f^/FORCE_COMPILE^}
7827 if you need to recompile an entire application,
7828 including run-time files, using special configuration pragma settings,
7829 such as a non-standard @code{Float_Representation} pragma.
7830 By default
7831 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
7832 internal files with
7833 @ifclear vms
7834 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7835 @end ifclear
7836 @ifset vms
7837 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
7838 @end ifset
7840 @item ^-b^/ACTIONS=BIND^
7841 @cindex @code{^-b^/ACTIONS=BIND^} (@code{gnatmake})
7842 Bind only. Can be combined with @code{^-c^/ACTIONS=COMPILE^} to do compilation
7843 and binding, but no link. Can be combined with @code{^-l^/ACTIONS=LINK^}
7844 to do binding and linking. When not combined with @code{^-c^/ACTIONS=COMPILE^}
7845 all the units in the closure of the main program must have been previously
7846 compiled and must be up to date. The root unit specified by @var{file_name}
7847 may be given without extension, with the source extension or, if no GNAT
7848 Project File is specified, with the ALI file extension.
7850 @item ^-c^/ACTIONS=COMPILE^
7851 @cindex @code{^-c^/ACTIONS=COMPILE^} (@code{gnatmake})
7852 Compile only. Do not perform binding, except when @code{^-b^/ACTIONS=BIND^}
7853 is also specified. Do not perform linking, except if both
7854 @code{^-b^/ACTIONS=BIND^} and
7855  @code{^-l^/ACTIONS=LINK^} are also specified.
7856 If the root unit specified by @var{file_name} is not a main unit, this is the
7857 default. Otherwise @code{gnatmake} will attempt binding and linking
7858 unless all objects are up to date and the executable is more recent than
7859 the objects.
7861 @item ^-C^/MAPPING^
7862 @cindex @code{^-C^/MAPPING^} (@code{gnatmake})
7863 Use a mapping file. A mapping file is a way to communicate to the compiler
7864 two mappings: from unit names to file names (without any directory information)
7865 and from file names to path names (with full directory information).
7866 These mappings are used by the compiler to short-circuit the path search.
7867 When @code{gnatmake} is invoked with this switch, it will create a mapping
7868 file, initially populated by the project manager, if @code{-P} is used,
7869 otherwise initially empty. Each invocation of the compiler will add the newly
7870 accessed sources to the mapping file. This will improve the source search
7871 during the next invocation of the compiler.
7873 @item ^-f^/FORCE_COMPILE^
7874 @cindex @code{^-f^/FORCE_COMPILE^} (@code{gnatmake})
7875 Force recompilations. Recompile all sources, even though some object
7876 files may be up to date, but don't recompile predefined or GNAT internal
7877 files or locked files (files with a write-protected ALI file),
7878 unless the @code{^-a^/ALL_FILES^} switch is also specified.
7880 @item
7881 @item ^-i^/IN_PLACE^
7882 @cindex @code{^-i^/IN_PLACE^} (@code{gnatmake})
7883 In normal mode, @code{gnatmake} compiles all object files and ALI files
7884 into the current directory. If the @code{^-i^/IN_PLACE^} switch is used,
7885 then instead object files and ALI files that already exist are overwritten
7886 in place. This means that once a large project is organized into separate
7887 directories in the desired manner, then @code{gnatmake} will automatically
7888 maintain and update this organization. If no ALI files are found on the
7889 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
7890 the new object and ALI files are created in the
7891 directory containing the source being compiled. If another organization
7892 is desired, where objects and sources are kept in different directories,
7893 a useful technique is to create dummy ALI files in the desired directories.
7894 When detecting such a dummy file, @code{gnatmake} will be forced to recompile
7895 the corresponding source file, and it will be put the resulting object
7896 and ALI files in the directory where it found the dummy file.
7898 @item ^-j^/PROCESSES=^@var{n}
7899 @cindex @code{^-j^/PROCESSES^} (@code{gnatmake})
7900 @cindex Parallel make
7901 Use @var{n} processes to carry out the (re)compilations. On a
7902 multiprocessor machine compilations will occur in parallel. In the
7903 event of compilation errors, messages from various compilations might
7904 get interspersed (but @code{gnatmake} will give you the full ordered
7905 list of failing compiles at the end). If this is problematic, rerun
7906 the make process with n set to 1 to get a clean list of messages.
7908 @item ^-k^/CONTINUE_ON_ERROR^
7909 @cindex @code{^-k^/CONTINUE_ON_ERROR^} (@code{gnatmake})
7910 Keep going. Continue as much as possible after a compilation error. To
7911 ease the programmer's task in case of compilation errors, the list of
7912 sources for which the compile fails is given when @code{gnatmake}
7913 terminates.
7915 If @code{gnatmake} is invoked with several @file{file_names} and with this
7916 switch, if there are compilation errors when building an executable,
7917 @code{gnatmake} will not attempt to build the following executables.
7919 @item ^-l^/ACTIONS=LINK^
7920 @cindex @code{^-l^/ACTIONS=LINK^} (@code{gnatmake})
7921 Link only. Can be combined with @code{^-b^/ACTIONS=BIND^} to binding
7922 and linking. Linking will not be performed if combined with
7923 @code{^-c^/ACTIONS=COMPILE^}
7924 but not with @code{^-b^/ACTIONS=BIND^}.
7925 When not combined with @code{^-b^/ACTIONS=BIND^}
7926 all the units in the closure of the main program must have been previously
7927 compiled and must be up to date, and the main program need to have been bound.
7928 The root unit specified by @var{file_name}
7929 may be given without extension, with the source extension or, if no GNAT
7930 Project File is specified, with the ALI file extension.
7932 @item ^-m^/MINIMAL_RECOMPILATION^
7933 @cindex @code{^-m^/MINIMAL_RECOMPILATION^} (@code{gnatmake})
7934 Specifies that the minimum necessary amount of recompilations
7935 be performed. In this mode @code{gnatmake} ignores time
7936 stamp differences when the only
7937 modifications to a source file consist in adding/removing comments,
7938 empty lines, spaces or tabs. This means that if you have changed the
7939 comments in a source file or have simply reformatted it, using this
7940 switch will tell gnatmake not to recompile files that depend on it
7941 (provided other sources on which these files depend have undergone no
7942 semantic modifications). Note that the debugging information may be
7943 out of date with respect to the sources if the @code{-m} switch causes
7944 a compilation to be switched, so the use of this switch represents a
7945 trade-off between compilation time and accurate debugging information.
7947 @item ^-M^/DEPENDENCIES_LIST^
7948 @cindex Dependencies, producing list
7949 @cindex @code{^-M^/DEPENDENCIES_LIST^} (@code{gnatmake})
7950 Check if all objects are up to date. If they are, output the object
7951 dependences to @file{stdout} in a form that can be directly exploited in
7952 a @file{Makefile}. By default, each source file is prefixed with its
7953 (relative or absolute) directory name. This name is whatever you
7954 specified in the various @code{^-aI^/SOURCE_SEARCH^}
7955 and @code{^-I^/SEARCH^} switches. If you use
7956 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
7957 @code{^-q^/QUIET^}
7958 (see below), only the source file names,
7959 without relative paths, are output. If you just specify the
7960 @code{^-M^/DEPENDENCIES_LIST^}
7961 switch, dependencies of the GNAT internal system files are omitted. This
7962 is typically what you want. If you also specify
7963 the @code{^-a^/ALL_FILES^} switch,
7964 dependencies of the GNAT internal files are also listed. Note that
7965 dependencies of the objects in external Ada libraries (see switch
7966 @code{^-aL^/SKIP_MISSING=^}@var{dir} in the following list) are never reported.
7968 @item ^-n^/DO_OBJECT_CHECK^
7969 @cindex @code{^-n^/DO_OBJECT_CHECK^} (@code{gnatmake})
7970 Don't compile, bind, or link. Checks if all objects are up to date.
7971 If they are not, the full name of the first file that needs to be
7972 recompiled is printed.
7973 Repeated use of this option, followed by compiling the indicated source
7974 file, will eventually result in recompiling all required units.
7976 @item ^-o ^/EXECUTABLE=^@var{exec_name}
7977 @cindex @code{^-o^/EXECUTABLE^} (@code{gnatmake})
7978 Output executable name. The name of the final executable program will be
7979 @var{exec_name}. If the @code{^-o^/EXECUTABLE^} switch is omitted the default
7980 name for the executable will be the name of the input file in appropriate form
7981 for an executable file on the host system.
7983 This switch cannot be used when invoking @code{gnatmake} with several
7984 @file{file_names}.
7986 @item ^-q^/QUIET^
7987 @cindex @code{^-q^/QUIET^} (@code{gnatmake})
7988 Quiet. When this flag is not set, the commands carried out by
7989 @code{gnatmake} are displayed.
7991 @item ^-s^/SWITCH_CHECK/^
7992 @cindex @code{^-s^/SWITCH_CHECK^} (@code{gnatmake})
7993 Recompile if compiler switches have changed since last compilation.
7994 All compiler switches but -I and -o are taken into account in the
7995 following way:
7996 orders between different ``first letter'' switches are ignored, but
7997 orders between same switches are taken into account. For example,
7998 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O} is equivalent
7999 to @code{-O -g}.
8001 @item ^-u^/UNIQUE^
8002 @cindex @code{^-u^/UNIQUE^} (@code{gnatmake})
8003 Unique. Recompile at most the main file. It implies -c. Combined with
8004 -f, it is equivalent to calling the compiler directly.
8006 @item ^-v^/REASONS^
8007 @cindex @code{^-v^/REASONS^} (@code{gnatmake})
8008 Verbose. Displays the reason for all recompilations @code{gnatmake}
8009 decides are necessary.
8011 @item ^-z^/NOMAIN^
8012 @cindex @code{^-z^/NOMAIN^} (@code{gnatmake})
8013 No main subprogram. Bind and link the program even if the unit name
8014 given on the command line is a package name. The resulting executable
8015 will execute the elaboration routines of the package and its closure,
8016 then the finalization routines.
8018 @item @code{gcc} @asis{switches}
8019 @ifclear vms
8020 The switch @code{-g} or any uppercase switch (other than @code{-A},
8021 @code{-L} or
8022 @code{-S}) or any switch that is more than one character is passed to
8023 @code{gcc} (e.g. @code{-O}, @option{-gnato,} etc.)
8024 @end ifclear
8025 @ifset vms
8026 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
8027 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
8028 automatically treated as a compiler switch, and passed on to all
8029 compilations that are carried out.
8030 @end ifset
8031 @end table
8033 @noindent
8034 Source and library search path switches:
8036 @table @code
8037 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
8038 @cindex @code{^-aI^/SOURCE_SEARCH^} (@code{gnatmake})
8039 When looking for source files also look in directory @var{dir}.
8040 The order in which source files search is undertaken is
8041 described in @ref{Search Paths and the Run-Time Library (RTL)}.
8043 @item ^-aL^/SKIP_MISSING=^@var{dir}
8044 @cindex @code{^-aL^/SKIP_MISSING^} (@code{gnatmake})
8045 Consider @var{dir} as being an externally provided Ada library.
8046 Instructs @code{gnatmake} to skip compilation units whose @file{.ali}
8047 files have been located in directory @var{dir}. This allows you to have
8048 missing bodies for the units in @var{dir} and to ignore out of date bodies
8049 for the same units. You still need to specify
8050 the location of the specs for these units by using the switches
8051 @code{^-aI^/SOURCE_SEARCH=^@var{dir}}
8052 or @code{^-I^/SEARCH=^@var{dir}}.
8053 Note: this switch is provided for compatibility with previous versions
8054 of @code{gnatmake}. The easier method of causing standard libraries
8055 to be excluded from consideration is to write-protect the corresponding
8056 ALI files.
8058 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
8059 @cindex @code{^-aO^/OBJECT_SEARCH^} (@code{gnatmake})
8060 When searching for library and object files, look in directory
8061 @var{dir}. The order in which library files are searched is described in
8062 @ref{Search Paths for gnatbind}.
8064 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
8065 @cindex Search paths, for @code{gnatmake}
8066 @cindex @code{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@code{gnatmake})
8067 Equivalent to @code{^-aL^/SKIP_MISSING=^@var{dir}
8068 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8070 @item ^-I^/SEARCH=^@var{dir}
8071 @cindex @code{^-I^/SEARCH^} (@code{gnatmake})
8072 Equivalent to @code{^-aO^/OBJECT_SEARCH=^@var{dir}
8073 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
8075 @item ^-I-^/NOCURRENT_DIRECTORY^
8076 @cindex @code{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatmake})
8077 @cindex Source files, suppressing search
8078 Do not look for source files in the directory containing the source
8079 file named in the command line.
8080 Do not look for ALI or object files in the directory
8081 where @code{gnatmake} was invoked.
8083 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
8084 @cindex @code{^-L^/LIBRARY_SEARCH^} (@code{gnatmake})
8085 @cindex Linker libraries
8086 Add directory @var{dir} to the list of directories in which the linker
8087 @ifset wnt
8088 Furthermore, under Windows, the sources pointed to by the libraries path
8089 set in the registry are not searched for.
8090 @end ifset
8091 will search for libraries. This is equivalent to
8092 @code{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
8094 @item -nostdinc
8095 @cindex @code{-nostdinc} (@code{gnatmake})
8096 Do not look for source files in the system default directory.
8098 @item -nostdlib
8099 @cindex @code{-nostdlib} (@code{gnatmake})
8100 Do not look for library files in the system default directory.
8102 @item --RTS=@var{rts-path}
8103 @cindex @code{--RTS} (@code{gnatmake})
8104 Specifies the default location of the runtime library. We look for the runtime
8105 in the following directories, and stop as soon as a valid runtime is found
8106 ("adainclude" or "ada_source_path", and "adalib" or "ada_object_path" present):
8108 @itemize @bullet
8109 @item <current directory>/$rts_path
8111 @item <default-search-dir>/$rts_path
8113 @item <default-search-dir>/rts-$rts_path
8114 @end itemize
8116 @noindent
8117 The selected path is handled like a normal RTS path.
8119 @end table
8121 @node Mode Switches for gnatmake
8122 @section Mode Switches for @code{gnatmake}
8124 @noindent
8125 The mode switches (referred to as @code{mode_switches}) allow the
8126 inclusion of switches that are to be passed to the compiler itself, the
8127 binder or the linker. The effect of a mode switch is to cause all
8128 subsequent switches up to the end of the switch list, or up to the next
8129 mode switch, to be interpreted as switches to be passed on to the
8130 designated component of GNAT.
8132 @table @code
8133 @item -cargs @var{switches}
8134 @cindex @code{-cargs} (@code{gnatmake})
8135 Compiler switches. Here @var{switches} is a list of switches
8136 that are valid switches for @code{gcc}. They will be passed on to
8137 all compile steps performed by @code{gnatmake}.
8139 @item -bargs @var{switches}
8140 @cindex @code{-bargs} (@code{gnatmake})
8141 Binder switches. Here @var{switches} is a list of switches
8142 that are valid switches for @code{gcc}. They will be passed on to
8143 all bind steps performed by @code{gnatmake}.
8145 @item -largs @var{switches}
8146 @cindex @code{-largs} (@code{gnatmake})
8147 Linker switches. Here @var{switches} is a list of switches
8148 that are valid switches for @code{gcc}. They will be passed on to
8149 all link steps performed by @code{gnatmake}.
8150 @end table
8152 @node Notes on the Command Line
8153 @section Notes on the Command Line
8155 @noindent
8156 This section contains some additional useful notes on the operation
8157 of the @code{gnatmake} command.
8159 @itemize @bullet
8160 @item
8161 @cindex Recompilation, by @code{gnatmake}
8162 If @code{gnatmake} finds no ALI files, it recompiles the main program
8163 and all other units required by the main program.
8164 This means that @code{gnatmake}
8165 can be used for the initial compile, as well as during subsequent steps of
8166 the development cycle.
8168 @item
8169 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
8170 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8171 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
8172 warning.
8174 @item
8175 In @code{gnatmake} the switch @code{^-I^/SEARCH^}
8176 is used to specify both source and
8177 library file paths. Use @code{^-aI^/SOURCE_SEARCH^}
8178 instead if you just want to specify
8179 source paths only and @code{^-aO^/OBJECT_SEARCH^}
8180 if you want to specify library paths
8181 only.
8183 @item
8184 @code{gnatmake} examines both an ALI file and its corresponding object file
8185 for consistency. If an ALI is more recent than its corresponding object,
8186 or if the object file is missing, the corresponding source will be recompiled.
8187 Note that @code{gnatmake} expects an ALI and the corresponding object file
8188 to be in the same directory.
8190 @item
8191 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8192 This may conveniently be used to exclude standard libraries from
8193 consideration and in particular it means that the use of the
8194 @code{^-f^/FORCE_COMPILE^} switch will not recompile these files
8195 unless @code{^-a^/ALL_FILES^} is also specified.
8197 @item
8198 @code{gnatmake} has been designed to make the use of Ada libraries
8199 particularly convenient. Assume you have an Ada library organized
8200 as follows: @var{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
8201 of your Ada compilation units,
8202 whereas @var{^include-dir^[INCLUDE_DIR]^} contains the
8203 specs of these units, but no bodies. Then to compile a unit
8204 stored in @code{main.adb}, which uses this Ada library you would just type
8206 @smallexample
8207 @ifclear vms
8208 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
8209 @end ifclear
8210 @ifset vms
8211 $ gnatmake /SOURCE_SEARCH=@var{[INCLUDE_DIR]}
8212            /SKIP_MISSING=@var{[OBJ_DIR]} main
8213 @end ifset
8214 @end smallexample
8216 @item
8217 Using @code{gnatmake} along with the
8218 @code{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
8219 switch provides a mechanism for avoiding unnecessary rcompilations. Using
8220 this switch,
8221 you can update the comments/format of your
8222 source files without having to recompile everything. Note, however, that
8223 adding or deleting lines in a source files may render its debugging
8224 info obsolete. If the file in question is a spec, the impact is rather
8225 limited, as that debugging info will only be useful during the
8226 elaboration phase of your program. For bodies the impact can be more
8227 significant. In all events, your debugger will warn you if a source file
8228 is more recent than the corresponding object, and alert you to the fact
8229 that the debugging information may be out of date.
8230 @end itemize
8232 @node How gnatmake Works
8233 @section How @code{gnatmake} Works
8235 @noindent
8236 Generally @code{gnatmake} automatically performs all necessary
8237 recompilations and you don't need to worry about how it works. However,
8238 it may be useful to have some basic understanding of the @code{gnatmake}
8239 approach and in particular to understand how it uses the results of
8240 previous compilations without incorrectly depending on them.
8242 First a definition: an object file is considered @dfn{up to date} if the
8243 corresponding ALI file exists and its time stamp predates that of the
8244 object file and if all the source files listed in the
8245 dependency section of this ALI file have time stamps matching those in
8246 the ALI file. This means that neither the source file itself nor any
8247 files that it depends on have been modified, and hence there is no need
8248 to recompile this file.
8250 @code{gnatmake} works by first checking if the specified main unit is up
8251 to date. If so, no compilations are required for the main unit. If not,
8252 @code{gnatmake} compiles the main program to build a new ALI file that
8253 reflects the latest sources. Then the ALI file of the main unit is
8254 examined to find all the source files on which the main program depends,
8255 and @code{gnatmake} recursively applies the above procedure on all these files.
8257 This process ensures that @code{gnatmake} only trusts the dependencies
8258 in an existing ALI file if they are known to be correct. Otherwise it
8259 always recompiles to determine a new, guaranteed accurate set of
8260 dependencies. As a result the program is compiled "upside down" from what may
8261 be more familiar as the required order of compilation in some other Ada
8262 systems. In particular, clients are compiled before the units on which
8263 they depend. The ability of GNAT to compile in any order is critical in
8264 allowing an order of compilation to be chosen that guarantees that
8265 @code{gnatmake} will recompute a correct set of new dependencies if
8266 necessary.
8268 When invoking @code{gnatmake} with several @var{file_names}, if a unit is
8269 imported by several of the executables, it will be recompiled at most once.
8271 @node Examples of gnatmake Usage
8272 @section Examples of @code{gnatmake} Usage
8274 @table @code
8275 @item gnatmake hello.adb
8276 Compile all files necessary to bind and link the main program
8277 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
8278 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
8280 @item gnatmake main1 main2 main3
8281 Compile all files necessary to bind and link the main programs
8282 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
8283 (containing unit @code{Main2}) and @file{main3.adb}
8284 (containing unit @code{Main3}) and bind and link the resulting object files
8285 to generate three executable files @file{^main1^MAIN1.EXE^},
8286 @file{^main2^MAIN2.EXE^}
8287 and @file{^main3^MAIN3.EXE^}.
8289 @ifclear vms
8290 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
8291 @end ifclear
8293 @ifset vms
8294 @item gnatmake Main_Unit /QUIET /COMPILER_QUALIFIERS /OPTIMIZE=ALL /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
8295 @end ifset
8296 Compile all files necessary to bind and link the main program unit
8297 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
8298 be done with optimization level 2 and the order of elaboration will be
8299 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8300 displaying commands it is executing.
8301 @end table
8303 @node Renaming Files Using gnatchop
8304 @chapter Renaming Files Using @code{gnatchop}
8305 @findex gnatchop
8307 @noindent
8308 This chapter discusses how to handle files with multiple units by using
8309 the @code{gnatchop} utility. This utility is also useful in renaming
8310 files to meet the standard GNAT default file naming conventions.
8312 @menu
8313 * Handling Files with Multiple Units::
8314 * Operating gnatchop in Compilation Mode::
8315 * Command Line for gnatchop::
8316 * Switches for gnatchop::
8317 * Examples of gnatchop Usage::
8318 @end menu
8320 @node Handling Files with Multiple Units
8321 @section Handling Files with Multiple Units
8323 @noindent
8324 The basic compilation model of GNAT requires that a file submitted to the
8325 compiler have only one unit and there be a strict correspondence
8326 between the file name and the unit name.
8328 The @code{gnatchop} utility allows both of these rules to be relaxed,
8329 allowing GNAT to process files which contain multiple compilation units
8330 and files with arbitrary file names. @code{gnatchop}
8331 reads the specified file and generates one or more output files,
8332 containing one unit per file. The unit and the file name correspond,
8333 as required by GNAT.
8335 If you want to permanently restructure a set of "foreign" files so that
8336 they match the GNAT rules, and do the remaining development using the
8337 GNAT structure, you can simply use @code{gnatchop} once, generate the
8338 new set of files and work with them from that point on.
8340 Alternatively, if you want to keep your files in the "foreign" format,
8341 perhaps to maintain compatibility with some other Ada compilation
8342 system, you can set up a procedure where you use @code{gnatchop} each
8343 time you compile, regarding the source files that it writes as temporary
8344 files that you throw away.
8346 @node Operating gnatchop in Compilation Mode
8347 @section Operating gnatchop in Compilation Mode
8349 @noindent
8350 The basic function of @code{gnatchop} is to take a file with multiple units
8351 and split it into separate files. The boundary between files is reasonably
8352 clear, except for the issue of comments and pragmas. In default mode, the
8353 rule is that any pragmas between units belong to the previous unit, except
8354 that configuration pragmas always belong to the following unit. Any comments
8355 belong to the following unit. These rules
8356 almost always result in the right choice of
8357 the split point without needing to mark it explicitly and most users will
8358 find this default to be what they want. In this default mode it is incorrect to
8359 submit a file containing only configuration pragmas, or one that ends in
8360 configuration pragmas, to @code{gnatchop}.
8362 However, using a special option to activate "compilation mode",
8363 @code{gnatchop}
8364 can perform another function, which is to provide exactly the semantics
8365 required by the RM for handling of configuration pragmas in a compilation.
8366 In the absence of configuration pragmas (at the main file level), this
8367 option has no effect, but it causes such configuration pragmas to be handled
8368 in a quite different manner.
8370 First, in compilation mode, if @code{gnatchop} is given a file that consists of
8371 only configuration pragmas, then this file is appended to the
8372 @file{gnat.adc} file in the current directory. This behavior provides
8373 the required behavior described in the RM for the actions to be taken
8374 on submitting such a file to the compiler, namely that these pragmas
8375 should apply to all subsequent compilations in the same compilation
8376 environment. Using GNAT, the current directory, possibly containing a
8377 @file{gnat.adc} file is the representation
8378 of a compilation environment. For more information on the
8379 @file{gnat.adc} file, see the section on handling of configuration
8380 pragmas @pxref{Handling of Configuration Pragmas}.
8382 Second, in compilation mode, if @code{gnatchop}
8383 is given a file that starts with
8384 configuration pragmas, and contains one or more units, then these
8385 configuration pragmas are prepended to each of the chopped files. This
8386 behavior provides the required behavior described in the RM for the
8387 actions to be taken on compiling such a file, namely that the pragmas
8388 apply to all units in the compilation, but not to subsequently compiled
8389 units.
8391 Finally, if configuration pragmas appear between units, they are appended
8392 to the previous unit. This results in the previous unit being illegal,
8393 since the compiler does not accept configuration pragmas that follow
8394 a unit. This provides the required RM behavior that forbids configuration
8395 pragmas other than those preceding the first compilation unit of a
8396 compilation.
8398 For most purposes, @code{gnatchop} will be used in default mode. The
8399 compilation mode described above is used only if you need exactly
8400 accurate behavior with respect to compilations, and you have files
8401 that contain multiple units and configuration pragmas. In this
8402 circumstance the use of @code{gnatchop} with the compilation mode
8403 switch provides the required behavior, and is for example the mode
8404 in which GNAT processes the ACVC tests.
8406 @node Command Line for gnatchop
8407 @section Command Line for @code{gnatchop}
8409 @noindent
8410 The @code{gnatchop} command has the form:
8412 @smallexample
8413 $ gnatchop switches @var{file name} [@var{file name} @var{file name} ...]
8414       [@var{directory}]
8415 @end smallexample
8417 @noindent
8418 The only required argument is the file name of the file to be chopped.
8419 There are no restrictions on the form of this file name. The file itself
8420 contains one or more Ada units, in normal GNAT format, concatenated
8421 together. As shown, more than one file may be presented to be chopped.
8423 When run in default mode, @code{gnatchop} generates one output file in
8424 the current directory for each unit in each of the files.
8426 @var{directory}, if specified, gives the name of the directory to which
8427 the output files will be written. If it is not specified, all files are
8428 written to the current directory.
8430 For example, given a
8431 file called @file{hellofiles} containing
8433 @smallexample
8434 @group
8435 @cartouche
8436 @b{procedure} hello;
8438 @b{with} Text_IO; @b{use} Text_IO;
8439 @b{procedure} hello @b{is}
8440 @b{begin}
8441    Put_Line ("Hello");
8442 @b{end} hello;
8443 @end cartouche
8444 @end group
8445 @end smallexample
8447 @noindent
8448 the command
8450 @smallexample
8451 $ gnatchop ^hellofiles^HELLOFILES.^
8452 @end smallexample
8454 @noindent
8455 generates two files in the current directory, one called
8456 @file{hello.ads} containing the single line that is the procedure spec,
8457 and the other called @file{hello.adb} containing the remaining text. The
8458 original file is not affected. The generated files can be compiled in
8459 the normal manner.
8461 @node Switches for gnatchop
8462 @section Switches for @code{gnatchop}
8464 @noindent
8465 @code{gnatchop} recognizes the following switches:
8467 @table @code
8469 @item ^-c^/COMPILATION^
8470 @cindex @code{^-c^/COMPILATION^} (@code{gnatchop})
8471 Causes @code{gnatchop} to operate in compilation mode, in which
8472 configuration pragmas are handled according to strict RM rules. See
8473 previous section for a full description of this mode.
8475 @ifclear vms
8476 @item -gnatxxx
8477 This passes the given @option{-gnatxxx} switch to @code{gnat} which is
8478 used to parse the given file. Not all @code{xxx} options make sense,
8479 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
8480 process a source file that uses Latin-2 coding for identifiers.
8481 @end ifclear
8483 @item ^-h^/HELP^
8484 Causes @code{gnatchop} to generate a brief help summary to the standard
8485 output file showing usage information.
8487 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
8488 @cindex @code{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
8489 Limit generated file names to the specified number @code{mm}
8490 of characters.
8491 This is useful if the
8492 resulting set of files is required to be interoperable with systems
8493 which limit the length of file names.
8494 @ifset vms
8495 If no value is given, or
8496 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
8497 a default of 39, suitable for OpenVMS Alpha
8498 Systems, is assumed
8499 @end ifset
8500 @ifclear vms
8501 No space is allowed between the @code{-k} and the numeric value. The numeric
8502 value may be omitted in which case a default of @code{-k8},
8503 suitable for use
8504 with DOS-like file systems, is used. If no @code{-k} switch
8505 is present then
8506 there is no limit on the length of file names.
8507 @end ifclear
8509 @item ^-p^/PRESERVE^
8510 @cindex @code{^-p^/PRESERVE^} (@code{gnatchop})
8511 Causes the file ^modification^creation^ time stamp of the input file to be
8512 preserved and used for the time stamp of the output file(s). This may be
8513 useful for preserving coherency of time stamps in an enviroment where
8514 @code{gnatchop} is used as part of a standard build process.
8516 @item ^-q^/QUIET^
8517 @cindex @code{^-q^/QUIET^} (@code{gnatchop})
8518 Causes output of informational messages indicating the set of generated
8519 files to be suppressed. Warnings and error messages are unaffected.
8521 @item ^-r^/REFERENCE^
8522 @cindex @code{^-r^/REFERENCE^} (@code{gnatchop})
8523 @findex Source_Reference
8524 Generate @code{Source_Reference} pragmas. Use this switch if the output
8525 files are regarded as temporary and development is to be done in terms
8526 of the original unchopped file. This switch causes
8527 @code{Source_Reference} pragmas to be inserted into each of the
8528 generated files to refers back to the original file name and line number.
8529 The result is that all error messages refer back to the original
8530 unchopped file.
8531 In addition, the debugging information placed into the object file (when
8532 the @code{^-g^/DEBUG^} switch of @code{gcc} or @code{gnatmake} is specified) also
8533 refers back to this original file so that tools like profilers and
8534 debuggers will give information in terms of the original unchopped file.
8536 If the original file to be chopped itself contains
8537 a @code{Source_Reference}
8538 pragma referencing a third file, then gnatchop respects
8539 this pragma, and the generated @code{Source_Reference} pragmas
8540 in the chopped file refer to the original file, with appropriate
8541 line numbers. This is particularly useful when @code{gnatchop}
8542 is used in conjunction with @code{gnatprep} to compile files that
8543 contain preprocessing statements and multiple units.
8545 @item ^-v^/VERBOSE^
8546 @cindex @code{^-v^/VERBOSE^} (@code{gnatchop})
8547 Causes @code{gnatchop} to operate in verbose mode. The version
8548 number and copyright notice are output, as well as exact copies of
8549 the gnat1 commands spawned to obtain the chop control information.
8551 @item ^-w^/OVERWRITE^
8552 @cindex @code{^-w^/OVERWRITE^} (@code{gnatchop})
8553 Overwrite existing file names. Normally @code{gnatchop} regards it as a
8554 fatal error if there is already a file with the same name as a
8555 file it would otherwise output, in other words if the files to be
8556 chopped contain duplicated units. This switch bypasses this
8557 check, and causes all but the last instance of such duplicated
8558 units to be skipped.
8560 @ifclear vms
8561 @item --GCC=xxxx
8562 @cindex @code{--GCC=} (@code{gnatchop})
8563 Specify the path of the GNAT parser to be used. When this switch is used,
8564 no attempt is made to add the prefix to the GNAT parser executable.
8565 @end ifclear
8566 @end table
8568 @node Examples of gnatchop Usage
8569 @section Examples of @code{gnatchop} Usage
8571 @table @code
8572 @ifset vms
8573 @item gnatchop /OVERWRITE HELLO_S.ADA [ICHBIAH.FILES]
8574 @end ifset
8575 @ifclear vms
8576 @item gnatchop -w hello_s.ada ichbiah/files
8577 @end ifclear
8579 Chops the source file @file{hello_s.ada}. The output files will be
8580 placed in the directory @file{^ichbiah/files^[ICHBIAH.FILES]^},
8581 overwriting any
8582 files with matching names in that directory (no files in the current
8583 directory are modified).
8585 @item gnatchop ^archive^ARCHIVE.^
8586 Chops the source file @file{^archive^ARCHIVE.^}
8587 into the current directory. One
8588 useful application of @code{gnatchop} is in sending sets of sources
8589 around, for example in email messages. The required sources are simply
8590 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
8591 command), and then
8592 @code{gnatchop} is used at the other end to reconstitute the original
8593 file names.
8595 @item gnatchop file1 file2 file3 direc
8596 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
8597 the resulting files in the directory @file{direc}. Note that if any units
8598 occur more than once anywhere within this set of files, an error message
8599 is generated, and no files are written. To override this check, use the
8600 @code{^-w^/OVERWRITE^} switch,
8601 in which case the last occurrence in the last file will
8602 be the one that is output, and earlier duplicate occurrences for a given
8603 unit will be skipped.
8604 @end table
8606 @node Configuration Pragmas
8607 @chapter Configuration Pragmas
8608 @cindex Configuration pragmas
8609 @cindex Pragmas, configuration
8611 @noindent
8612 In Ada 95, configuration pragmas include those pragmas described as
8613 such in the Ada 95 Reference Manual, as well as
8614 implementation-dependent pragmas that are configuration pragmas. See the
8615 individual descriptions of pragmas in the GNAT Reference Manual for
8616 details on these additional GNAT-specific configuration pragmas. Most
8617 notably, the pragma @code{Source_File_Name}, which allows
8618 specifying non-default names for source files, is a configuration
8619 pragma. The following is a complete list of configuration pragmas
8620 recognized by @code{GNAT}:
8622 @smallexample
8623    Ada_83
8624    Ada_95
8625    C_Pass_By_Copy
8626    Component_Alignment
8627    Discard_Names
8628    Elaboration_Checks
8629    Eliminate
8630    Extend_System
8631    Extensions_Allowed
8632    External_Name_Casing
8633    Float_Representation
8634    Initialize_Scalars
8635    License
8636    Locking_Policy
8637    Long_Float
8638    No_Run_Time
8639    Normalize_Scalars
8640    Polling
8641    Propagate_Exceptions
8642    Queuing_Policy
8643    Ravenscar
8644    Restricted_Run_Time
8645    Restrictions
8646    Reviewable
8647    Source_File_Name
8648    Style_Checks
8649    Suppress
8650    Task_Dispatching_Policy
8651    Unsuppress
8652    Use_VADS_Size
8653    Warnings
8654    Validity_Checks
8655 @end smallexample
8657 @menu
8658 * Handling of Configuration Pragmas::
8659 * The Configuration Pragmas Files::
8660 @end menu
8662 @node Handling of Configuration Pragmas
8663 @section Handling of Configuration Pragmas
8665 Configuration pragmas may either appear at the start of a compilation
8666 unit, in which case they apply only to that unit, or they may apply to
8667 all compilations performed in a given compilation environment.
8669 GNAT also provides the @code{gnatchop} utility to provide an automatic
8670 way to handle configuration pragmas following the semantics for
8671 compilations (that is, files with multiple units), described in the RM.
8672 See section @pxref{Operating gnatchop in Compilation Mode} for details.
8673 However, for most purposes, it will be more convenient to edit the
8674 @file{gnat.adc} file that contains configuration pragmas directly,
8675 as described in the following section.
8677 @node The Configuration Pragmas Files
8678 @section The Configuration Pragmas Files
8679 @cindex @file{gnat.adc}
8681 @noindent
8682 In GNAT a compilation environment is defined by the current
8683 directory at the time that a compile command is given. This current
8684 directory is searched for a file whose name is @file{gnat.adc}. If
8685 this file is present, it is expected to contain one or more
8686 configuration pragmas that will be applied to the current compilation.
8687 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
8688 considered.
8690 Configuration pragmas may be entered into the @file{gnat.adc} file
8691 either by running @code{gnatchop} on a source file that consists only of
8692 configuration pragmas, or more conveniently  by
8693 direct editing of the @file{gnat.adc} file, which is a standard format
8694 source file.
8696 In addition to @file{gnat.adc}, one additional file containing configuration
8697 pragmas may be applied to the current compilation using the switch
8698 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
8699 contains only configuration pragmas. These configuration pragmas are
8700 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
8701 is present and switch @option{-gnatA} is not used).
8703 It is allowed to specify several switches @option{-gnatec}, however only
8704 the last one on the command line will be taken into account.
8706 @ifset vms
8707 Of special interest to GNAT OpenVMS Alpha is the following configuration pragma:
8709 @smallexample
8710 @cartouche
8711 @b{pragma} Extend_System (Aux_DEC);
8712 @end cartouche
8713 @end smallexample
8715 @noindent
8716 In the presence of this pragma, GNAT adds to the definition of the
8717 predefined package SYSTEM all the additional types and subprograms that are
8718 defined in DEC Ada. See @pxref{Compatibility with DEC Ada} for details.
8719 @end ifset
8721 @node Handling Arbitrary File Naming Conventions Using gnatname
8722 @chapter Handling Arbitrary File Naming Conventions Using @code{gnatname}
8723 @cindex Arbitrary File Naming Conventions
8725 @menu
8726 * Arbitrary File Naming Conventions::
8727 * Running gnatname::
8728 * Switches for gnatname::
8729 * Examples of gnatname Usage::
8730 @end menu
8732 @node Arbitrary File Naming Conventions
8733 @section Arbitrary File Naming Conventions
8735 @noindent
8736 The GNAT compiler must be able to know the source file name of a compilation unit.
8737 When using the standard GNAT default file naming conventions (@code{.ads} for specs,
8738 @code{.adb} for bodies), the GNAT compiler does not need additional information.
8740 @noindent
8741 When the source file names do not follow the standard GNAT default file naming
8742 conventions, the GNAT compiler must be given additional information through
8743 a configuration pragmas file (see @ref{Configuration Pragmas}) or a project file.
8744 When the non standard file naming conventions are well-defined, a small number of
8745 pragmas @code{Source_File_Name} specifying a naming pattern
8746 (see @ref{Alternative File Naming Schemes}) may be sufficient. However,
8747 if the file naming conventions are irregular or arbitrary, a number
8748 of pragma @code{Source_File_Name} for individual compilation units must be defined.
8749 To help maintain the correspondence between compilation unit names and
8750 source file names within the compiler,
8751 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
8752 set of files.
8754 @node Running gnatname
8755 @section Running @code{gnatname}
8757 @noindent
8758 The usual form of the @code{gnatname} command is
8760 @smallexample
8761 $ gnatname [@var{switches}] @var{naming_pattern} [@var{naming_patterns}]
8762 @end smallexample
8764 @noindent
8765 All of the arguments are optional. If invoked without any argument,
8766 @code{gnatname} will display its usage.
8768 @noindent
8769 When used with at least one naming pattern, @code{gnatname} will attempt to
8770 find all the compilation units in files that follow at least one of the
8771 naming patterns. To find these compilation units,
8772 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
8773 regular files.
8775 @noindent
8776 One or several Naming Patterns may be given as arguments to @code{gnatname}.
8777 Each Naming Pattern is enclosed between double quotes.
8778 A Naming Pattern is a regular expression similar to the wildcard patterns
8779 used in file names by the Unix shells or the DOS prompt.
8781 @noindent
8782 Examples of Naming Patterns are
8784 @smallexample
8785    "*.[12].ada"
8786    "*.ad[sb]*"
8787    "body_*"    "spec_*"
8788 @end smallexample
8790 @noindent
8791 For a more complete description of the syntax of Naming Patterns, see the second kind
8792 of regular expressions described in @file{g-regexp.ads} (the "Glob" regular
8793 expressions).
8795 @noindent
8796 When invoked with no switches, @code{gnatname} will create a configuration
8797 pragmas file @file{gnat.adc} in the current working directory, with pragmas
8798 @code{Source_File_Name} for each file that contains a valid Ada unit.
8800 @node Switches for gnatname
8801 @section Switches for @code{gnatname}
8803 @noindent
8804 Switches for @code{gnatname} must precede any specified Naming Pattern.
8806 @noindent
8807 You may specify any of the following switches to @code{gnatname}:
8809 @table @code
8811 @item -c@file{file}
8812 @cindex @code{-c} (@code{gnatname})
8813 Create a configuration pragmas file @file{file} (instead of the default
8814 @file{gnat.adc}). There may be zero, one or more space between @code{-c} and
8815 @file{file}. @file{file} may include directory information. @file{file} must be
8816 writeable. There may be only one switch @code{-c}. When a switch @code{-c} is
8817 specified, no switch @code{-P} may be specified (see below).
8819 @item -d@file{dir}
8820 @cindex @code{-d} (@code{gnatname})
8821 Look for source files in directory @file{dir}. There may be zero, one or more spaces
8822 between @code{-d} and @file{dir}. When a switch @code{-d} is specified,
8823 the current working directory will not be searched for source files, unless it
8824 is explictly
8825 specified with a @code{-d} or @code{-D} switch. Several switches @code{-d} may be
8826 specified. If @file{dir} is a relative path, it is relative to the directory of
8827 the configuration pragmas file specified with switch @code{-c}, or to the directory
8828 of the project file specified with switch @code{-P} or, if neither switch @code{-c}
8829 nor switch @code{-P} are specified, it is relative to the current working
8830 directory. The directory
8831 specified with switch @code{-c} must exist and be readable.
8833 @item -D@file{file}
8834 @cindex @code{-D} (@code{gnatname})
8835 Look for source files in all directories listed in text file @file{file}. There may be
8836 zero, one or more spaces between @code{-d} and @file{dir}. @file{file}
8837 must be an existing, readable text file. Each non empty line in @file{file} must be
8838 a directory. Specifying switch @code{-D} is equivalent to specifying as many switches
8839 @code{-d} as there are non empty lines in @file{file}.
8841 @item -h
8842 @cindex @code{-h} (@code{gnatname})
8843 Output usage (help) information. The output is written to @file{stdout}.
8845 @item -P@file{proj}
8846 @cindex @code{-P} (@code{gnatname})
8847 Create or update project file @file{proj}. There may be zero, one or more space
8848 between @code{-P} and @file{proj}. @file{proj} may include directory information.
8849 @file{proj} must be writeable. There may be only one switch @code{-P}.
8850 When a switch @code{-P} is specified, no switch @code{-c} may be specified.
8852 @item -v
8853 @cindex @code{-v} (@code{gnatname})
8854 Verbose mode. Output detailed explanation of behavior to @file{stdout}. This includes
8855 name of the file written, the name of the directories to search and, for each file
8856 in those directories whose name matches at least one of the Naming Patterns, an
8857 indication of whether the file contains a unit, and if so the name of the unit.
8859 @item -v -v
8860 Very Verbose mode. In addition to the output produced in verbose mode, for each file
8861 in the searched directories whose name matches none of the Naming Patterns, an
8862 indication is given that there is no match.
8864 @item -x@file{pattern}
8865 Excluded patterns. Using this switch, it is possible to exclude some files
8866 that would match the name patterns. For example,
8867 @code{"gnatname -x "*_nt.ada" "*.ada"} will look for Ada units in all files
8868 with the @file{.ada} extension, except those whose names end with
8869 @file{_nt.ada}.
8871 @end table
8873 @node Examples of gnatname Usage
8874 @section Examples of @code{gnatname} Usage
8876 @smallexample
8877 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
8878 @end smallexample
8880 In this example, the directory @file{/home/me} must already exist and be
8881 writeable. In addition, the directory @file{/home/me/sources} (specified by
8882 @code{-d sources}) must exist and be readable. Note the optional spaces after
8883 @code{-c} and @code{-d}.
8885 @smallexample
8886 $ gnatname -P/home/me/proj -x "*_nt_body.ada" -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
8887 @end smallexample
8889 Note that several switches @code{-d} may be used, even in conjunction with one
8890 or several switches @code{-D}. Several Naming Patterns and one excluded pattern
8891 are used in this example.
8894 @c *****************************************
8895 @c * G N A T  P r o j e c t  M a n a g e r *
8896 @c *****************************************
8897 @node GNAT Project Manager
8898 @chapter GNAT Project Manager
8900 @menu
8901 * Introduction::
8902 * Examples of Project Files::
8903 * Project File Syntax::
8904 * Objects and Sources in Project Files::
8905 * Importing Projects::
8906 * Project Extension::
8907 * External References in Project Files::
8908 * Packages in Project Files::
8909 * Variables from Imported Projects::
8910 * Naming Schemes::
8911 * Library Projects::
8912 * Switches Related to Project Files::
8913 * Tools Supporting Project Files::
8914 * An Extended Example::
8915 * Project File Complete Syntax::
8916 @end menu
8919 @c ****************
8920 @c * Introduction *
8921 @c ****************
8923 @node Introduction
8924 @section Introduction
8926 @noindent
8927 This chapter describes GNAT's @emph{Project Manager}, a facility that
8928 lets you configure various properties for a collection of source files.  In
8929 particular, you can specify:
8930 @itemize @bullet
8931 @item
8932 The directory or set of directories containing the source files, and/or the
8933 names of the specific source files themselves
8934 @item
8935 The directory in which the compiler's output
8936 (@file{ALI} files, object files, tree files) will be placed
8937 @item
8938 The directory in which the executable programs will be placed
8939 @item
8940 Switch settings for any of the project-enabled tools (@command{gnatmake},
8941 compiler, binder, linker, @code{gnatls}, @code{gnatxref}, @code{gnatfind});
8942 you can apply these settings either globally or to individual units
8943 @item
8944 The source files containing the main subprogram(s) to be built
8945 @item
8946 The source programming language(s) (currently Ada and/or C)
8947 @item
8948 Source file naming conventions; you can specify these either globally or for
8949 individual units
8950 @end itemize
8952 @menu
8953 * Project Files::
8954 @end menu
8956 @node Project Files
8957 @subsection Project Files
8959 @noindent
8960 A @dfn{project} is a specific set of values for these properties.  You can
8961 define a project's settings in a @dfn{project file}, a text file with an
8962 Ada-like syntax; a property value is either a string or a list of strings.
8963 Properties that are not explicitly set receive default values.  A project
8964 file may interrogate the values of @dfn{external variables} (user-defined
8965 command-line switches or environment variables), and it may specify property
8966 settings conditionally, based on the value of such variables.
8968 In simple cases, a project's source files depend only on other source files
8969 in the same project, or on the predefined libraries.  ("Dependence" is in
8970 the technical sense; for example, one Ada unit "with"ing another.)  However,
8971 the Project Manager also allows much more sophisticated arrangements,
8972 with the source files in one project depending on source files in other
8973 projects:
8974 @itemize @bullet
8975 @item
8976 One project can @emph{import} other projects containing needed source files.
8977 @item
8978 You can organize GNAT projects in a hierarchy: a @emph{child} project
8979 can extend a @emph{parent} project, inheriting the parent's source files and
8980 optionally overriding any of them with alternative versions
8981 @end itemize
8983 @noindent
8984 More generally, the Project Manager lets you structure large development
8985 efforts into hierarchical subsystems, with build decisions deferred to the
8986 subsystem level and thus different compilation environments (switch settings)
8987 used for different subsystems.
8989 The Project Manager is invoked through the @option{-P@emph{projectfile}}
8990 switch to @command{gnatmake} or to the @command{gnat} front driver.
8991 If you want to define (on the command line) an external variable that is
8992 queried by the project file, additionally use the
8993 @option{-X@emph{vbl}=@emph{value}} switch.
8994 The Project Manager parses and interprets the project file, and drives the
8995 invoked tool based on the project settings.
8997 The Project Manager supports a wide range of development strategies,
8998 for systems of all sizes.  Some typical practices that are easily handled:
8999 @itemize @bullet
9000 @item
9001 Using a common set of source files, but generating object files in different
9002 directories via different switch settings
9003 @item
9004 Using a mostly-shared set of source files, but with different versions of
9005 some unit or units
9006 @end itemize
9008 @noindent
9009 The destination of an executable can be controlled inside a project file
9010 using the @option{-o} switch. In the absence of such a switch either inside
9011 the project file or on the command line, any executable files generated by
9012 @command{gnatmake} will be placed in the directory @code{Exec_Dir} specified
9013 in the project file. If no @code{Exec_Dir} is specified, they will be placed
9014 in the object directory of the project.
9016 You can use project files to achieve some of the effects of a source
9017 versioning system (for example, defining separate projects for
9018 the different sets of sources that comprise different releases) but the
9019 Project Manager is independent of any source configuration management tools
9020 that might be used by the developers.
9022 The next section introduces the main features of GNAT's project facility
9023 through a sequence of examples; subsequent sections will present the syntax
9024 and semantics in more detail.
9027 @c *****************************
9028 @c * Examples of Project Files *
9029 @c *****************************
9031 @node Examples of Project Files
9032 @section Examples of Project Files
9033 @noindent
9034 This section illustrates some of the typical uses of project files and
9035 explains their basic structure and behavior.
9037 @menu
9038 * Common Sources with Different Switches and Different Output Directories::
9039 * Using External Variables::
9040 * Importing Other Projects::
9041 * Extending a Project::
9042 @end menu
9044 @node Common Sources with Different Switches and Different Output Directories
9045 @subsection Common Sources with Different Switches and Different Output Directories
9047 @menu
9048 * Source Files::
9049 * Specifying the Object Directory::
9050 * Specifying the Exec Directory::
9051 * Project File Packages::
9052 * Specifying Switch Settings::
9053 * Main Subprograms::
9054 * Source File Naming Conventions::
9055 * Source Language(s)::
9056 @end menu
9058 @noindent
9059 Assume that the Ada source files @file{pack.ads}, @file{pack.adb}, and
9060 @file{proc.adb} are in the @file{/common} directory.  The file
9061 @file{proc.adb} contains an Ada main subprogram @code{Proc} that "with"s
9062 package @code{Pack}.  We want to compile these source files under two sets
9063 of switches:
9064 @itemize @bullet
9065 @item
9066 When debugging, we want to pass the @option{-g} switch to @command{gnatmake},
9067 and the @option{-gnata}, @option{-gnato}, and @option{-gnatE} switches to the
9068 compiler; the compiler's output is to appear in @file{/common/debug}
9069 @item
9070 When preparing a release version, we want to pass the @option{-O2} switch to
9071 the compiler; the compiler's output is to appear in @file{/common/release}
9072 @end itemize
9074 @noindent
9075 The GNAT project files shown below, respectively @file{debug.gpr} and
9076 @file{release.gpr} in the @file{/common} directory, achieve these effects.
9078 Diagrammatically:
9079 @smallexample
9080 @group
9081 /common
9082   debug.gpr
9083   release.gpr
9084   pack.ads
9085   pack.adb
9086   proc.adb
9087 @end group
9088 @group
9089 /common/debug @{-g, -gnata, -gnato, -gnatE@}
9090   proc.ali, proc.o
9091   pack.ali, pack.o
9092 @end group
9093 @group
9094 /common/release @{-O2@}
9095   proc.ali, proc.o
9096   pack.ali, pack.o
9097 @end group
9098 @end smallexample
9099 Here are the project files:
9100 @smallexample
9101 @group
9102 project Debug is
9103   for Object_Dir use "debug";
9104   for Main use ("proc");
9106   package Builder is
9107     for Default_Switches ("Ada") use ("-g");
9108   end Builder;
9109 @end group
9111 @group
9112   package Compiler is
9113     for Default_Switches ("Ada")
9114        use ("-fstack-check", "-gnata", "-gnato", "-gnatE");
9115   end Compiler;
9116 end Debug;
9117 @end group
9118 @end smallexample
9120 @smallexample
9121 @group
9122 project Release is
9123   for Object_Dir use "release";
9124   for Exec_Dir use ".";
9125   for Main use ("proc");
9127   package Compiler is
9128     for Default_Switches ("Ada") use ("-O2");
9129   end Compiler;
9130 end Release;
9131 @end group
9132 @end smallexample
9134 @noindent
9135 The name of the project defined by @file{debug.gpr} is @code{"Debug"} (case
9136 insensitive), and analogously the project defined by @file{release.gpr} is
9137 @code{"Release"}.  For consistency the file should have the same name as the
9138 project, and the project file's extension should be @code{"gpr"}. These
9139 conventions are not required, but a warning is issued if they are not followed.
9141 If the current directory is @file{/temp}, then the command
9142 @smallexample
9143 gnatmake -P/common/debug.gpr
9144 @end smallexample
9146 @noindent
9147 generates object and ALI files in @file{/common/debug}, and the @code{proc}
9148 executable also in @file{/common/debug}, using the switch settings defined in
9149 the project file.
9151 Likewise, the command
9152 @smallexample
9153 gnatmake -P/common/release.gpr
9154 @end smallexample
9156 @noindent
9157 generates object and ALI files in @file{/common/release}, and the @code{proc}
9158 executable in @file{/common}, using the switch settings from the project file.
9160 @node Source Files
9161 @unnumberedsubsubsec Source Files
9163 @noindent
9164 If a project file does not explicitly specify a set of source directories or
9165 a set of source files, then by default the project's source files are the
9166 Ada source files in the project file directory.  Thus @file{pack.ads},
9167 @file{pack.adb}, and @file{proc.adb} are the source files for both projects.
9169 @node Specifying the Object Directory
9170 @unnumberedsubsubsec Specifying the Object Directory
9172 @noindent
9173 Several project properties are modeled by Ada-style @emph{attributes};
9174 you define the property by supplying the equivalent of an Ada attribute
9175 definition clause in the project file.
9176 A project's object directory is such a property; the corresponding
9177 attribute is @code{Object_Dir}, and its value is a string expression.  A
9178 directory may be specified either as absolute or as relative; in the latter
9179 case, it is relative to the project file directory.  Thus the compiler's
9180 output is directed to @file{/common/debug} (for the @code{Debug} project)
9181 and to @file{/common/release} (for the @code{Release} project).  If
9182 @code{Object_Dir} is not specified, then the default is the project file
9183 directory.
9185 @node Specifying the Exec Directory
9186 @unnumberedsubsubsec Specifying the Exec Directory
9188 @noindent
9189 A project's exec directory is another property; the corresponding
9190 attribute is @code{Exec_Dir}, and its value is also a string expression,
9191 either specified as relative or absolute. If @code{Exec_Dir} is not specified,
9192 then the default is the object directory (which may also be the project file
9193 directory if attribute @code{Object_Dir} is not specified). Thus the executable
9194 is placed in @file{/common/debug} for the @code{Debug} project (attribute
9195 @code{Exec_Dir} not specified) and in @file{/common} for the @code{Release}
9196 project.
9198 @node Project File Packages
9199 @unnumberedsubsubsec Project File Packages
9201 @noindent
9202 A GNAT tool integrated with the Project Manager is modeled by a
9203 corresponding package in the project file.
9204 The @code{Debug} project defines the packages @code{Builder}
9205 (for @command{gnatmake}) and @code{Compiler};
9206 the @code{Release} project defines only the @code{Compiler} package.
9208 The Ada package syntax is not to be taken literally.  Although packages in
9209 project files bear a surface resemblance to packages in Ada source code, the
9210 notation is simply a way to convey a grouping of properties for a named
9211 entity.  Indeed, the package names permitted in project files are restricted
9212 to a predefined set, corresponding to the project-aware tools, and the contents
9213 of packages are limited to a small set of constructs.
9214 The packages in the example above contain attribute definitions.
9217 @node Specifying Switch Settings
9218 @unnumberedsubsubsec Specifying Switch Settings
9220 @noindent
9221 Switch settings for a project-aware tool can be specified through attributes
9222 in the package corresponding to the tool.
9223 The example above illustrates one of the relevant attributes,
9224 @code{Default_Switches}, defined in the packages in both project files.
9225 Unlike simple attributes like @code{Source_Dirs}, @code{Default_Switches} is
9226 known as an @emph{associative array}.  When you define this attribute, you must
9227 supply an "index" (a literal string), and the effect of the attribute
9228 definition is to set the value of the "array" at the specified "index".
9229 For the @code{Default_Switches} attribute, the index is a programming
9230 language (in our case, Ada) , and the value specified (after @code{use})
9231 must be a list of string expressions.
9233 The attributes permitted in project files are restricted to a predefined set.
9234 Some may appear at project level, others in packages.
9235 For any attribute that is an associate array, the index must always be a
9236 literal string, but the restrictions on this string (e.g., a file name or a
9237 language name) depend on the individual attribute.
9238 Also depending on the attribute, its specified value will need to be either a
9239 string or a string list.
9241 In the @code{Debug} project, we set the switches for two tools,
9242 @command{gnatmake} and the compiler, and thus we include corresponding
9243 packages, with each package defining the @code{Default_Switches} attribute
9244 with index @code{"Ada"}.
9245 Note that the package corresponding to
9246 @command{gnatmake} is named @code{Builder}.  The @code{Release} project is
9247 similar, but with just the @code{Compiler} package.
9249 In project @code{Debug} above the switches starting with @option{-gnat} that
9250 are specified in package @code{Compiler} could have been placed in package
9251 @code{Builder}, since @command{gnatmake} transmits all such switches to the
9252 compiler.
9254 @node Main Subprograms
9255 @unnumberedsubsubsec Main Subprograms
9257 @noindent
9258 One of the properties of a project is its list of main subprograms (actually
9259 a list of names of source files containing main subprograms, with the file
9260 extension optional.  This property is captured in the @code{Main} attribute,
9261 whose value is a list of strings.  If a project defines the @code{Main}
9262 attribute, then you do not need to identify the main subprogram(s) when
9263 invoking @command{gnatmake} (see @ref{gnatmake and Project Files}).
9265 @node Source File Naming Conventions
9266 @unnumberedsubsubsec Source File Naming Conventions
9268 @noindent
9269 Since the project files do not specify any source file naming conventions,
9270 the GNAT defaults are used.  The mechanism for defining source file naming
9271 conventions -- a package named @code{Naming} -- will be described below
9272 (@pxref{Naming Schemes}).
9274 @node Source Language(s)
9275 @unnumberedsubsubsec Source Language(s)
9277 @noindent
9278 Since the project files do not specify a @code{Languages} attribute, by
9279 default the GNAT tools assume that the language of the project file is Ada.
9280 More generally, a project can comprise source files
9281 in Ada, C, and/or other languages.
9283 @node Using External Variables
9284 @subsection Using External Variables
9286 @noindent
9287 Instead of supplying different project files for debug and release, we can
9288 define a single project file that queries an external variable (set either
9289 on the command line or via an environment variable) in order to
9290 conditionally define the appropriate settings.  Again, assume that the
9291 source files @file{pack.ads}, @file{pack.adb}, and @file{proc.adb} are
9292 located in directory @file{/common}.  The following project file,
9293 @file{build.gpr}, queries the external variable named @code{STYLE} and
9294 defines an object directory and switch settings based on whether the value
9295 is @code{"deb"} (debug) or @code{"rel"} (release), where the default is
9296 @code{"deb"}.
9298 @smallexample
9299 @group
9300 project Build is
9301   for Main use ("proc");
9303   type Style_Type is ("deb", "rel");
9304   Style : Style_Type := external ("STYLE", "deb");
9306   case Style is
9307     when "deb" =>
9308       for Object_Dir use "debug";
9310     when "rel" =>
9311       for Object_Dir use "release";
9312       for Exec_Dir use ".";
9313   end case;
9314 @end group
9316 @group
9317   package Builder is
9319     case Style is
9320       when "deb" =>
9321         for Default_Switches ("Ada") use ("-g");
9322     end case;
9324   end Builder;
9325 @end group
9327 @group
9328   package Compiler is
9330     case Style is
9331       when "deb" =>
9332         for Default_Switches ("Ada") use ("-gnata", "-gnato", "-gnatE");
9334       when "rel" =>
9335         for Default_Switches ("Ada") use ("-O2");
9336     end case;
9338   end Compiler;
9340 end Build;
9341 @end group
9342 @end smallexample
9344 @noindent
9345 @code{Style_Type} is an example of a @emph{string type}, which is the project
9346 file analog of an Ada enumeration type but containing string literals rather
9347 than identifiers.  @code{Style} is declared as a variable of this type.
9349 The form @code{external("STYLE", "deb")} is known as an
9350 @emph{external reference}; its first argument is the name of an
9351 @emph{external variable}, and the second argument is a default value to be
9352 used if the external variable doesn't exist.  You can define an external
9353 variable on the command line via the @option{-X} switch, or you can use an
9354 environment variable as an external variable.
9356 Each @code{case} construct is expanded by the Project Manager based on the
9357 value of @code{Style}. Thus the command
9358 @smallexample
9359 gnatmake -P/common/build.gpr -XSTYLE=deb
9360 @end smallexample
9362 @noindent
9363 is equivalent to the @command{gnatmake} invocation using the project file
9364 @file{debug.gpr} in the earlier example.  So is the command
9365 @smallexample
9366 gnatmake -P/common/build.gpr
9367 @end smallexample
9369 @noindent
9370 since @code{"deb"} is the default for @code{STYLE}.
9372 Analogously,
9373 @smallexample
9374 gnatmake -P/common/build.gpr -XSTYLE=rel
9375 @end smallexample
9377 @noindent
9378 is equivalent to the @command{gnatmake} invocation using the project file
9379 @file{release.gpr} in the earlier example.
9382 @node Importing Other Projects
9383 @subsection Importing Other Projects
9385 @noindent
9386 A compilation unit in a source file in one project may depend on compilation
9387 units in source files in other projects.  To obtain this behavior, the
9388 dependent project must @emph{import} the projects containing the needed source
9389 files.  This effect is embodied in syntax similar to an Ada @code{with} clause,
9390 but the "with"ed entities are strings denoting project files.
9392 As an example, suppose that the two projects @code{GUI_Proj} and
9393 @code{Comm_Proj} are defined in the project files @file{gui_proj.gpr} and
9394 @file{comm_proj.gpr} in directories @file{/gui} and @file{/comm},
9395 respectively.  Assume that the source files for @code{GUI_Proj} are
9396 @file{gui.ads} and @file{gui.adb}, and that the source files for
9397 @code{Comm_Proj} are @file{comm.ads} and @file{comm.adb}, with each set of
9398 files located in its respective project file directory.  Diagrammatically:
9400 @smallexample
9401 @group
9402 /gui
9403   gui_proj.gpr
9404   gui.ads
9405   gui.adb
9406 @end group
9408 @group
9409 /comm
9410   comm_proj.gpr
9411   comm.ads
9412   comm.adb
9413 @end group
9414 @end smallexample
9416 @noindent
9417 We want to develop an application in directory @file{/app} that "with"s the
9418 packages @code{GUI} and @code{Comm}, using the properties of the
9419 corresponding project files (e.g. the switch settings and object directory).
9420 Skeletal code for a main procedure might be something like the following:
9422 @smallexample
9423 @group
9424 with GUI, Comm;
9425 procedure App_Main is
9426    ...
9427 begin
9428    ...
9429 end App_Main;
9430 @end group
9431 @end smallexample
9433 @noindent
9434 Here is a project file, @file{app_proj.gpr}, that achieves the desired
9435 effect:
9437 @smallexample
9438 @group
9439 with "/gui/gui_proj", "/comm/comm_proj";
9440 project App_Proj is
9441    for Main use ("app_main");
9442 end App_Proj;
9443 @end group
9444 @end smallexample
9446 @noindent
9447 Building an executable is achieved through the command:
9448 @smallexample
9449 gnatmake -P/app/app_proj
9450 @end smallexample
9451 @noindent
9452 which will generate the @code{app_main} executable in the directory where
9453 @file{app_proj.gpr} resides.
9455 If an imported project file uses the standard extension (@code{gpr}) then
9456 (as illustrated above) the @code{with} clause can omit the extension.
9458 Our example specified an absolute path for each imported project file.
9459 Alternatively, you can omit the directory if either
9460 @itemize @bullet
9461 @item
9462 The imported project file is in the same directory as the importing project
9463 file, or
9464 @item
9465 You have defined an environment variable @code{ADA_PROJECT_PATH} that
9466 includes the directory containing the needed project file.
9467 @end itemize
9469 @noindent
9470 Thus, if we define @code{ADA_PROJECT_PATH} to include @file{/gui} and
9471 @file{/comm}, then our project file @file{app_proj.gpr} could be written as
9472 follows:
9474 @smallexample
9475 @group
9476 with "gui_proj", "comm_proj";
9477 project App_Proj is
9478    for Main use ("app_main");
9479 end App_Proj;
9480 @end group
9481 @end smallexample
9483 @noindent
9484 Importing other projects raises the possibility of ambiguities.  For
9485 example, the same unit might be present in different imported projects, or
9486 it might be present in both the importing project and an imported project.
9487 Both of these conditions are errors.  Note that in the current version of
9488 the Project Manager, it is illegal to have an ambiguous unit even if the
9489 unit is never referenced by the importing project.  This restriction may be
9490 relaxed in a future release.
9492 @node Extending a Project
9493 @subsection Extending a Project
9495 @noindent
9496 A common situation in large software systems is to have multiple
9497 implementations for a common interface; in Ada terms, multiple versions of a
9498 package body for the same specification.  For example, one implementation
9499 might be safe for use in tasking programs, while another might only be used
9500 in sequential applications.  This can be modeled in GNAT using the concept
9501 of @emph{project extension}.  If one project (the "child") @emph{extends}
9502 another project (the "parent") then by default all source files of the
9503 parent project are inherited by the child, but the child project can
9504 override any of the parent's source files with new versions, and can also
9505 add new files.  This facility is the project analog of extension in
9506 Object-Oriented Programming.  Project hierarchies are permitted (a child
9507 project may be the parent of yet another project), and a project that
9508 inherits one project can also import other projects.
9510 As an example, suppose that directory @file{/seq} contains the project file
9511 @file{seq_proj.gpr} and the source files @file{pack.ads}, @file{pack.adb},
9512 and @file{proc.adb}:
9514 @smallexample
9515 @group
9516 /seq
9517   pack.ads
9518   pack.adb
9519   proc.adb
9520   seq_proj.gpr
9521 @end group
9522 @end smallexample
9524 @noindent
9525 Note that the project file can simply be empty (that is, no attribute or
9526 package is defined):
9528 @smallexample
9529 @group
9530 project Seq_Proj is
9531 end Seq_Proj;
9532 @end group
9533 @end smallexample
9535 @noindent
9536 implying that its source files are all the Ada source files in the project
9537 directory.
9539 Suppose we want to supply an alternate version of @file{pack.adb}, in
9540 directory @file{/tasking}, but use the existing versions of @file{pack.ads}
9541 and @file{proc.adb}.  We can define a project @code{Tasking_Proj} that
9542 inherits @code{Seq_Proj}:
9544 @smallexample
9545 @group
9546 /tasking
9547   pack.adb
9548   tasking_proj.gpr
9549 @end group
9551 @group
9552 project Tasking_Proj extends "/seq/seq_proj" is
9553 end Tasking_Proj;
9554 @end group
9555 @end smallexample
9557 @noindent
9558 The version of @file{pack.adb} used in a build depends on which project file
9559 is specified.
9561 Note that we could have designed this using project import rather than
9562 project inheritance; a @code{base} project would contain the sources for
9563 @file{pack.ads} and @file{proc.adb}, a sequential project would import
9564 @code{base} and add @file{pack.adb}, and likewise a tasking project would
9565 import @code{base} and add a different version of @file{pack.adb}.  The
9566 choice depends on whether other sources in the original project need to be
9567 overridden.  If they do, then project extension is necessary, otherwise,
9568 importing is sufficient.
9571 @c ***********************
9572 @c * Project File Syntax *
9573 @c ***********************
9575 @node Project File Syntax
9576 @section Project File Syntax
9578 @menu
9579 * Basic Syntax::
9580 * Packages::
9581 * Expressions::
9582 * String Types::
9583 * Variables::
9584 * Attributes::
9585 * Associative Array Attributes::
9586 * case Constructions::
9587 @end menu
9589 @noindent
9590 This section describes the structure of project files.
9592 A project may be an @emph{independent project}, entirely defined by a single
9593 project file. Any Ada source file in an independent project depends only
9594 on the predefined library and other Ada source files in the same project.
9596 @noindent
9597 A project may also @dfn{depend on} other projects, in either or both of the following ways:
9598 @itemize @bullet
9599 @item It may import any number of projects
9600 @item It may extend at most one other project
9601 @end itemize
9603 @noindent
9604 The dependence relation is a directed acyclic graph (the subgraph reflecting
9605 the "extends" relation is a tree).
9607 A project's @dfn{immediate sources} are the source files directly defined by
9608 that project, either implicitly by residing in the project file's directory,
9609 or explicitly through any of the source-related attributes described below.
9610 More generally, a project @var{proj}'s @dfn{sources} are the immediate sources
9611 of @var{proj} together with the immediate sources (unless overridden) of any
9612 project on which @var{proj} depends (either directly or indirectly).
9614 @node Basic Syntax
9615 @subsection Basic Syntax
9617 @noindent
9618 As seen in the earlier examples, project files have an Ada-like syntax.
9619 The minimal project file is:
9620 @smallexample
9621 @group
9622 project Empty is
9624 end Empty;
9625 @end group
9626 @end smallexample
9628 @noindent
9629 The identifier @code{Empty} is the name of the project.
9630 This project name must be present after the reserved
9631 word @code{end} at the end of the project file, followed by a semi-colon.
9633 Any name in a project file, such as the project name or a variable name,
9634 has the same syntax as an Ada identifier.
9636 The reserved words of project files are the Ada reserved words plus
9637 @code{extends}, @code{external}, and @code{project}.  Note that the only Ada
9638 reserved words currently used in project file syntax are:
9640 @itemize @bullet
9641 @item
9642 @code{case}
9643 @item
9644 @code{end}
9645 @item
9646 @code{for}
9647 @item
9648 @code{is}
9649 @item
9650 @code{others}
9651 @item
9652 @code{package}
9653 @item
9654 @code{renames}
9655 @item
9656 @code{type}
9657 @item
9658 @code{use}
9659 @item
9660 @code{when}
9661 @item
9662 @code{with}
9663 @end itemize
9665 @noindent
9666 Comments in project files have the same syntax as in Ada, two consecutives
9667 hyphens through the end of the line.
9669 @node Packages
9670 @subsection Packages
9672 @noindent
9673 A project file may contain @emph{packages}. The name of a package must be one
9674 of the identifiers (case insensitive) from a predefined list, and a package
9675 with a given name may only appear once in a project file. The predefined list
9676 includes the following packages:
9678 @itemize @bullet
9679 @item
9680 @code{Naming}
9681 @item
9682 @code{Builder}
9683 @item
9684 @code{Compiler}
9685 @item
9686 @code{Binder}
9687 @item
9688 @code{Linker}
9689 @item
9690 @code{Finder}
9691 @item
9692 @code{Cross_Reference}
9693 @item
9694 @code{gnatls}
9695 @end itemize
9697 @noindent
9698 (The complete list of the package names and their attributes can be found
9699 in file @file{prj-attr.adb}).
9701 @noindent
9702 In its simplest form, a package may be empty:
9704 @smallexample
9705 @group
9706 project Simple is
9707   package Builder is
9708   end Builder;
9709 end Simple;
9710 @end group
9711 @end smallexample
9713 @noindent
9714 A package may contain @emph{attribute declarations},
9715 @emph{variable declarations} and @emph{case constructions}, as will be
9716 described below.
9718 When there is ambiguity between a project name and a package name,
9719 the name always designates the project. To avoid possible confusion, it is
9720 always a good idea to avoid naming a project with one of the
9721 names allowed for packages or any name that starts with @code{gnat}.
9724 @node Expressions
9725 @subsection Expressions
9727 @noindent
9728 An @emph{expression} is either a @emph{string expression} or a
9729 @emph{string list expression}.
9731 A @emph{string expression} is either a @emph{simple string expression} or a
9732 @emph{compound string expression}.
9734 A @emph{simple string expression} is one of the following:
9735 @itemize @bullet
9736 @item A literal string; e.g.@code{"comm/my_proj.gpr"}
9737 @item A string-valued variable reference (see @ref{Variables})
9738 @item A string-valued attribute reference (see @ref{Attributes})
9739 @item An external reference (see @ref{External References in Project Files})
9740 @end itemize
9742 @noindent
9743 A @emph{compound string expression} is a concatenation of string expressions,
9744 using @code{"&"}
9745 @smallexample
9746        Path & "/" & File_Name & ".ads"
9747 @end smallexample
9749 @noindent
9750 A @emph{string list expression} is either a
9751 @emph{simple string list expression} or a
9752 @emph{compound string list expression}.
9754 A @emph{simple string list expression} is one of the following:
9755 @itemize @bullet
9756 @item A parenthesized list of zero or more string expressions, separated by commas
9757 @smallexample
9758    File_Names := (File_Name, "gnat.adc", File_Name & ".orig");
9759    Empty_List := ();
9760 @end smallexample
9761 @item A string list-valued variable reference
9762 @item A string list-valued attribute reference
9763 @end itemize
9765 @noindent
9766 A @emph{compound string list expression} is the concatenation (using
9767 @code{"&"}) of a simple string list expression and an expression.  Note that
9768 each term in a compound string list expression, except the first, may be
9769 either a string expression or a string list expression.
9771 @smallexample
9772 @group
9773    File_Name_List := () & File_Name; --  One string in this list
9774    Extended_File_Name_List := File_Name_List & (File_Name & ".orig");
9775    --  Two strings
9776    Big_List := File_Name_List & Extended_File_Name_List;
9777    --  Concatenation of two string lists: three strings
9778    Illegal_List := "gnat.adc" & Extended_File_Name_List;
9779    --  Illegal: must start with a string list
9780 @end group
9781 @end smallexample
9784 @node String Types
9785 @subsection String Types
9787 @noindent
9788 The value of a variable may be restricted to a list of string literals.
9789 The restricted list of string literals is given in a
9790 @emph{string type declaration}.
9792 Here is an example of a string type declaration:
9794 @smallexample
9795    type OS is ("NT, "nt", "Unix", "Linux", "other OS");
9796 @end smallexample
9798 @noindent
9799 Variables of a string type are called @emph{typed variables}; all other
9800 variables are called @emph{untyped variables}. Typed variables are
9801 particularly useful in @code{case} constructions
9802 (see @ref{case Constructions}).
9804 A string type declaration starts with the reserved word @code{type}, followed
9805 by the name of the string type (case-insensitive), followed by the reserved
9806 word @code{is}, followed by a parenthesized list of one or more string literals
9807 separated by commas, followed by a semicolon.
9809 The string literals in the list are case sensitive and must all be different.
9810 They may include any graphic characters allowed in Ada, including spaces.
9812 A string type may only be declared at the project level, not inside a package.
9814 A string type may be referenced by its name if it has been declared in the same
9815 project file, or by its project name, followed by a dot,
9816 followed by the string type name.
9819 @node Variables
9820 @subsection Variables
9822 @noindent
9823 A variable may be declared at the project file level, or in a package.
9824 Here are some examples of variable declarations:
9826 @smallexample
9827 @group
9828    This_OS : OS := external ("OS"); --  a typed variable declaration
9829    That_OS := "Linux";              --  an untyped variable declaration
9830 @end group
9831 @end smallexample
9833 @noindent
9834 A @emph{typed variable declaration} includes the variable name, followed by a colon,
9835 followed by the name of a string type, followed by @code{:=}, followed by
9836 a simple string expression.
9838 An @emph{untyped variable declaration} includes the variable name,
9839 followed by @code{:=}, followed by an expression.  Note that, despite the
9840 terminology, this form of "declaration" resembles more an assignment
9841 than a declaration in Ada.  It is a declaration in several senses:
9842 @itemize @bullet
9843 @item
9844 The variable name does not need to be defined previously
9845 @item
9846 The declaration establishes the @emph{kind} (string versus string list) of the
9847 variable, and later declarations of the same variable need to be consistent
9848 with this
9849 @end itemize
9851 @noindent
9852 A string variable declaration (typed or untyped) declares a variable
9853 whose value is a string. This variable may be used as a string expression.
9854 @smallexample
9855    File_Name       := "readme.txt";
9856    Saved_File_Name := File_Name & ".saved";
9857 @end smallexample
9859 @noindent
9860 A string list variable declaration declares a variable whose value is a list
9861 of strings. The list may contain any number (zero or more) of strings.
9863 @smallexample
9864    Empty_List := ();
9865    List_With_One_Element := ("-gnaty");
9866    List_With_Two_Elements := List_With_One_Element & "-gnatg";
9867    Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada"
9868                  "pack2.ada", "util_.ada", "util.ada");
9869 @end smallexample
9871 @noindent
9872 The same typed variable may not be declared more than once at project level, and it may not be declared more than once in any package; it is in effect a constant or a readonly variable.
9874 The same untyped variable may be declared several times.
9875 In this case, the new value replaces the old one,
9876 and any subsequent reference to the variable uses the new value.
9877 However, as noted above, if a variable has been declared as a string, all subsequent
9878 declarations must give it a string value. Similarly, if a variable has
9879 been declared as a string list, all subsequent declarations
9880 must give it a string list value.
9882 A @emph{variable reference} may take several forms:
9884 @itemize @bullet
9885 @item The simple variable name, for a variable in the current package (if any) or in the current project
9886 @item A context name, followed by a dot, followed by the variable name.
9887 @end itemize
9889 @noindent
9890 A @emph{context} may be one of the following:
9892 @itemize @bullet
9893 @item The name of an existing package in the current project
9894 @item The name of an imported project of the current project
9895 @item The name of an ancestor project (i.e., a project extended by the current project, either directly or indirectly)
9896 @item An imported/parent project name, followed by a dot, followed by a package name
9897 @end itemize
9899 @noindent
9900 A variable reference may be used in an expression.
9903 @node Attributes
9904 @subsection Attributes
9906 @noindent
9907 A project (and its packages) may have @emph{attributes} that define the project's properties.
9908 Some attributes have values that are strings;
9909 others have values that are string lists.
9911 There are two categories of attributes: @emph{simple attributes} and @emph{associative arrays}
9912 (see @ref{Associative Array Attributes}).
9914 The names of the attributes are restricted; there is a list of project
9915 attributes, and a list of package attributes for each package.
9916 The names are not case sensitive.
9918 The project attributes are as follows (all are simple attributes):
9920 @multitable @columnfractions .4 .3
9921 @item @emph{Attribute Name}
9922 @tab @emph{Value}
9923 @item @code{Source_Files}
9924 @tab string list
9925 @item @code{Source_Dirs}
9926 @tab string list
9927 @item @code{Source_List_File}
9928 @tab string
9929 @item @code{Object_Dir}
9930 @tab string
9931 @item @code{Exec_Dir}
9932 @tab string
9933 @item @code{Main}
9934 @tab string list
9935 @item @code{Languages}
9936 @tab string list
9937 @item @code{Library_Dir}
9938 @tab string
9939 @item @code{Library_Name}
9940 @tab string
9941 @item @code{Library_Kind}
9942 @tab string
9943 @item @code{Library_Elaboration}
9944 @tab string
9945 @item @code{Library_Version}
9946 @tab string
9947 @end multitable
9949 @noindent
9950 The attributes for package @code{Naming} are as follows
9951 (see @ref{Naming Schemes}):
9953 @multitable @columnfractions .4 .2 .2 .2
9954 @item Attribute Name @tab Category @tab Index @tab Value
9955 @item @code{Specification_Suffix}
9956 @tab associative array
9957 @tab language name
9958 @tab string
9959 @item @code{Implementation_Suffix}
9960 @tab associative array
9961 @tab language name
9962 @tab string
9963 @item @code{Separate_Suffix}
9964 @tab simple attribute
9965 @tab n/a
9966 @tab string
9967 @item @code{Casing}
9968 @tab simple attribute
9969 @tab n/a
9970 @tab string
9971 @item @code{Dot_Replacement}
9972 @tab simple attribute
9973 @tab n/a
9974 @tab string
9975 @item @code{Specification}
9976 @tab associative array
9977 @tab Ada unit name
9978 @tab string
9979 @item @code{Implementation}
9980 @tab associative array
9981 @tab Ada unit name
9982 @tab string
9983 @item @code{Specification_Exceptions}
9984 @tab associative array
9985 @tab language name
9986 @tab string list
9987 @item @code{Implementation_Exceptions}
9988 @tab associative array
9989 @tab language name
9990 @tab string list
9991 @end multitable
9993 @noindent
9994 The attributes for package @code{Builder}, @code{Compiler}, @code{Binder},
9995 @code{Linker}, @code{Cross_Reference}, and @code{Finder}
9996 are as follows (see @ref{Switches and Project Files}).
9998 @multitable @columnfractions .4 .2 .2 .2
9999 @item Attribute Name @tab Category @tab Index @tab Value
10000 @item @code{Default_Switches}
10001 @tab associative array
10002 @tab language name
10003 @tab string list
10004 @item @code{Switches}
10005 @tab associative array
10006 @tab file name
10007 @tab string list
10008 @end multitable
10010 @noindent
10011 In addition, package @code{Builder} has a single string attribute
10012 @code{Local_Configuration_Pragmas} and package @code{Builder} has a single
10013 string attribute @code{Global_Configuration_Pragmas}.
10015 @noindent
10016 The attribute for package @code{Glide} are not documented: they are for
10017 internal use only.
10019 @noindent
10020 Each simple attribute has a default value: the empty string (for string-valued
10021 attributes) and the empty list (for string list-valued attributes).
10023 Similar to variable declarations, an attribute declaration defines a new value
10024 for an attribute.
10026 Examples of simple attribute declarations:
10028 @smallexample
10029    for Object_Dir use "objects";
10030    for Source_Dirs use ("units", "test/drivers");
10031 @end smallexample
10033 @noindent
10034 A @dfn{simple attribute declaration} starts with the reserved word @code{for},
10035 followed by the name of the attribute, followed by the reserved word
10036 @code{use}, followed by an expression (whose kind depends on the attribute),
10037 followed by a semicolon.
10039 Attributes may be referenced in expressions.
10040 The general form for such a reference is @code{<entity>'<attribute>}:
10041 the entity for which the attribute is defined,
10042 followed by an apostrophe, followed by the name of the attribute.
10043 For associative array attributes, a litteral string between parentheses
10044 need to be supplied as index.
10046 Examples are:
10048 @smallexample
10049   project'Object_Dir
10050   Naming'Dot_Replacement
10051   Imported_Project'Source_Dirs
10052   Imported_Project.Naming'Casing
10053   Builder'Default_Switches("Ada")
10054 @end smallexample
10056 @noindent
10057 The entity may be:
10058 @itemize @bullet
10059 @item @code{project} for an attribute of the current project
10060 @item The name of an existing package of the current project
10061 @item The name of an imported project
10062 @item The name of a parent project (extended by the current project)
10063 @item An imported/parent project name, followed by a dot,
10064       followed by a package name
10065 @end itemize
10067 @noindent
10068 Example:
10069 @smallexample
10070 @group
10071    project Prj is
10072      for Source_Dirs use project'Source_Dirs & "units";
10073      for Source_Dirs use project'Source_Dirs & "test/drivers"
10074    end Prj;
10075 @end group
10076 @end smallexample
10078 @noindent
10079 In the first attribute declaration, initially the attribute @code{Source_Dirs}
10080 has the default value: an empty string list. After this declaration,
10081 @code{Source_Dirs} is a string list of one element: "units".
10082 After the second attribute declaration @code{Source_Dirs} is a string list of
10083 two elements: "units" and "test/drivers".
10085 Note: this example is for illustration only. In practice,
10086 the project file would contain only one attribute declaration:
10088 @smallexample
10089    for Source_Dirs use ("units", "test/drivers");
10090 @end smallexample
10093 @node Associative Array Attributes
10094 @subsection Associative Array Attributes
10096 @noindent
10097 Some attributes are defined as @emph{associative arrays}. An associative
10098 array may be regarded as a function that takes a string as a parameter
10099 and delivers a string or string list value as its result.
10101 Here are some examples of associative array attribute declarations:
10103 @smallexample
10104    for Implementation ("main") use "Main.ada";
10105    for Switches ("main.ada") use ("-v", "-gnatv");
10106    for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
10107 @end smallexample
10109 @noindent
10110 Like untyped variables and simple attributes, associative array attributes may be declared several times. Each declaration supplies a new value for the
10111 attribute, replacing the previous setting.
10114 @node case Constructions
10115 @subsection @code{case} Constructions
10117 @noindent
10118 A @code{case} construction is used in a project file to effect conditional
10119 behavior.
10120 Here is a typical example:
10122 @smallexample
10123 @group
10124 project MyProj is
10125    type OS_Type is ("Linux", "Unix", "NT", "VMS");
10127    OS : OS_Type := external ("OS", "Linux");
10128 @end group
10130 @group
10131    package Compiler is
10132      case OS is
10133        when "Linux" | "Unix" =>
10134          for Default_Switches ("Ada") use ("-gnath");
10135        when "NT" =>
10136          for Default_Switches ("Ada") use ("-gnatP");
10137        when others =>
10138      end case;
10139    end Compiler;
10140 end MyProj;
10141 @end group
10142 @end smallexample
10144 @noindent
10145 The syntax of a @code{case} construction is based on the Ada case statement
10146 (although there is no @code{null} construction for empty alternatives).
10148 Following the reserved word @code{case} there is the case variable (a typed
10149 string variable), the reserved word @code{is}, and then a sequence of one or
10150 more alternatives.
10151 Each alternative comprises the reserved word @code{when}, either a list of
10152 literal strings separated by the @code{"|"} character or the reserved word
10153 @code{others},  and the @code{"=>"} token.
10154 Each literal string must belong to the string type that is the type of the
10155 case variable.
10156 An @code{others} alternative, if present, must occur last.
10157 The @code{end case;} sequence terminates the case construction.
10159 After each @code{=>}, there are zero or more constructions.  The only
10160 constructions allowed in a case construction are other case constructions and
10161 attribute declarations. String type declarations, variable declarations and
10162 package declarations are not allowed.
10164 The value of the case variable is often given by an external reference
10165 (see @ref{External References in Project Files}).
10168 @c ****************************************
10169 @c * Objects and Sources in Project Files *
10170 @c ****************************************
10172 @node Objects and Sources in Project Files
10173 @section Objects and Sources in Project Files
10175 @menu
10176 * Object Directory::
10177 * Exec Directory::
10178 * Source Directories::
10179 * Source File Names::
10180 @end menu
10182 @noindent
10183 Each project has exactly one object directory and one or more source
10184 directories. The source directories must contain at least one source file,
10185 unless  the project file explicitly specifies that no source files are present
10186 (see @ref{Source File Names}).
10189 @node Object Directory
10190 @subsection Object Directory
10192 @noindent
10193 The object directory for a project is the directory containing the compiler's
10194 output (such as @file{ALI} files and object files) for the project's immediate
10195 sources. Note that for inherited sources (when extending a parent project) the
10196 parent project's object directory is used.
10198 The object directory is given by the value of the attribute @code{Object_Dir}
10199 in the project file.
10201 @smallexample
10202    for Object_Dir use "objects";
10203 @end smallexample
10205 @noindent
10206 The attribute @var{Object_Dir} has a string value, the path name of the object
10207 directory. The path name may be absolute or relative to the directory of the
10208 project file. This directory must already exist, and be readable and writable.
10210 By default, when the attribute @code{Object_Dir} is not given an explicit value
10211 or when its value is the empty string, the object directory is the same as the
10212 directory containing the project file.
10215 @node Exec Directory
10216 @subsection Exec Directory
10218 @noindent
10219 The exec directory for a project is the directory containing the executables
10220 for the project's main subprograms.
10222 The exec directory is given by the value of the attribute @code{Exec_Dir}
10223 in the project file.
10225 @smallexample
10226    for Exec_Dir use "executables";
10227 @end smallexample
10229 @noindent
10230 The attribute @var{Exec_Dir} has a string value, the path name of the exec
10231 directory. The path name may be absolute or relative to the directory of the
10232 project file. This directory must already exist, and be writable.
10234 By default, when the attribute @code{Exec_Dir} is not given an explicit value
10235 or when its value is the empty string, the exec directory is the same as the
10236 object directory of the project file.
10239 @node Source Directories
10240 @subsection Source Directories
10242 @noindent
10243 The source directories of a project are specified by the project file
10244 attribute @code{Source_Dirs}.
10246 This attribute's value is a string list. If the attribute is not given an
10247 explicit value, then there is only one source directory, the one where the
10248 project file resides.
10250 A @code{Source_Dirs} attribute that is explicitly defined to be the empty list,
10251 as in
10253 @smallexample
10254     for Source_Dirs use ();
10255 @end smallexample
10257 @noindent
10258 indicates that the project contains no source files.
10260 Otherwise, each string in the string list designates one or more
10261 source directories.
10263 @smallexample
10264    for Source_Dirs use ("sources", "test/drivers");
10265 @end smallexample
10267 @noindent
10268 If a string in the list ends with @code{"/**"},  then the directory whose path
10269 name precedes the two asterisks, as well as all its subdirectories
10270 (recursively), are source directories.
10272 @smallexample
10273    for Source_Dirs use ("/system/sources/**");
10274 @end smallexample
10276 @noindent
10277 Here the directory @code{/system/sources} and all of its subdirectories
10278 (recursively) are source directories.
10280 To specify that the source directories are the directory of the project file
10281 and all of its subdirectories, you can declare @code{Source_Dirs} as follows:
10282 @smallexample
10283    for Source_Dirs use ("./**");
10284 @end smallexample
10286 @noindent
10287 Each of the source directories must exist and be readable.
10290 @node Source File Names
10291 @subsection Source File Names
10293 @noindent
10294 In a project that contains source files, their names may be specified by the
10295 attributes @code{Source_Files} (a string list) or @code{Source_List_File}
10296 (a string). Source file names never include any directory information.
10298 If the attribute @code{Source_Files} is given an explicit value, then each
10299 element of the list is a source file name.
10301 @smallexample
10302    for Source_Files use ("main.adb");
10303    for Source_Files use ("main.adb", "pack1.ads", "pack2.adb");
10304 @end smallexample
10306 @noindent
10307 If the attribute @code{Source_Files} is not given an explicit value,
10308 but the attribute @code{Source_List_File} is given a string value,
10309 then the source file names are contained in the text file whose path name
10310 (absolute or relative to the directory of the project file) is the
10311 value of the attribute @code{Source_List_File}.
10313 Each line in the file that is not empty or is not a comment
10314 contains a source file name. A comment line starts with two hyphens.
10316 @smallexample
10317    for Source_List_File use "source_list.txt";
10318 @end smallexample
10320 @noindent
10321 By default, if neither the attribute @code{Source_Files} nor the attribute
10322 @code{Source_List_File} is given an explicit value, then each file in the
10323 source directories that conforms to the project's naming scheme
10324 (see @ref{Naming Schemes}) is an immediate source of the project.
10326 A warning is issued if both attributes @code{Source_Files} and
10327 @code{Source_List_File} are given explicit values. In this case, the attribute
10328 @code{Source_Files} prevails.
10330 Each source file name must be the name of one and only one existing source file
10331 in one of the source directories.
10333 A @code{Source_Files} attribute defined with an empty list as its value
10334 indicates that there are no source files in the project.
10336 Except for projects that are clearly specified as containing no Ada source
10337 files (@code{Source_Dirs} or @code{Source_Files} specified as an empty list,
10338 or @code{Languages} specified without @code{"Ada"} in the list)
10339 @smallexample
10340    for Source_Dirs use ();
10341    for Source_Files use ();
10342    for Languages use ("C", "C++");
10343 @end smallexample
10345 @noindent
10346 a project must contain at least one immediate source.
10348 Projects with no source files are useful as template packages
10349 (see @ref{Packages in Project Files}) for other projects; in particular to
10350 define a package @code{Naming} (see @ref{Naming Schemes}).
10353 @c ****************************
10354 @c * Importing Projects *
10355 @c ****************************
10357 @node  Importing Projects
10358 @section Importing Projects
10360 @noindent
10361 An immediate source of a project P may depend on source files that
10362 are neither immediate sources of P nor in the predefined library.
10363 To get this effect, P must @emph{import} the projects that contain the needed
10364 source files.
10366 @smallexample
10367 @group
10368   with "project1", "utilities.gpr";
10369   with "/namings/apex.gpr";
10370   project Main is
10371     ...
10372 @end group
10373 @end smallexample
10375 @noindent
10376 As can be seen in this example, the syntax for importing projects is similar
10377 to the syntax for importing compilation units in Ada. However, project files
10378 use literal strings instead of names, and the @code{with} clause identifies
10379 project files rather than packages.
10381 Each literal string is the file name or path name (absolute or relative) of a
10382 project file. If a string is simply a file name, with no path, then its
10383 location is determined by the @emph{project path}:
10385 @itemize @bullet
10386 @item
10387 If the environment variable @env{ADA_PROJECT_PATH} exists, then the project
10388 path includes all the directories in this environment variable, plus the
10389 directory of the project file.
10391 @item
10392 If the environment variable @env{ADA_PROJECT_PATH} does not exist,
10393 then the project path contains only one directory, namely the one where
10394 the project file is located.
10395 @end itemize
10397 @noindent
10398 If a relative pathname is used as in
10400 @smallexample
10401   with "tests/proj";
10402 @end smallexample
10404 @noindent
10405 then the path is relative to the directory where the importing project file is
10406 located. Any symbolic link will be fully resolved in the directory
10407 of the importing project file before the imported project file is looked up.
10409 When the @code{with}'ed project file name does not have an extension,
10410 the default is @file{.gpr}. If a file with this extension is not found, then
10411 the file name as specified in the @code{with} clause (no extension) will be
10412 used. In the above example, if a file @code{project1.gpr} is found, then it
10413 will be used; otherwise, if a file @code{project1} exists then it will be used;
10414 if neither file exists, this is an error.
10416 A warning is issued if the name of the project file does not match the
10417 name of the project; this check is case insensitive.
10419 Any source file that is an immediate source of the imported project can be
10420 used by the immediate sources of the importing project, and recursively. Thus
10421 if @code{A} imports @code{B}, and @code{B} imports @code{C}, the immediate
10422 sources of @code{A} may depend on the immediate sources of @code{C}, even if
10423 @code{A} does not import @code{C} explicitly. However, this is not recommended,
10424 because if and when @code{B} ceases to import @code{C}, some sources in
10425 @code{A} will no longer compile.
10427 A side effect of this capability is that cyclic dependences are not permitted:
10428 if @code{A} imports @code{B} (directly or indirectly) then @code{B} is not
10429 allowed to import @code{A}.
10432 @c *********************
10433 @c * Project Extension *
10434 @c *********************
10436 @node Project Extension
10437 @section Project Extension
10439 @noindent
10440 During development of a large system, it is sometimes necessary to use
10441 modified versions of some of the source files without changing the original
10442 sources. This can be achieved through a facility known as
10443 @emph{project extension}.
10445 @smallexample
10446    project Modified_Utilities extends "/baseline/utilities.gpr" is ...
10447 @end smallexample
10449 @noindent
10450 The project file for the project being extended (the @emph{parent}) is
10451 identified by the literal string that follows the reserved word @code{extends},
10452 which itself follows the name of the extending project (the @emph{child}).
10454 By default, a child project inherits all the sources of its parent.
10455 However, inherited sources can be overridden: a unit with the same name as one
10456 in the parent will hide the original unit.
10457 Inherited sources are considered to be sources (but not immediate sources)
10458 of the child project; see @ref{Project File Syntax}.
10460 An inherited source file retains any switches specified in the parent project.
10462 For example if the project @code{Utilities} contains the specification and the
10463 body of an Ada package @code{Util_IO}, then the project
10464 @code{Modified_Utilities} can contain a new body for package @code{Util_IO}.
10465 The original body of @code{Util_IO} will not be considered in program builds.
10466 However, the package specification will still be found in the project
10467 @code{Utilities}.
10469 A child project can have only one parent but it may import any number of other
10470 projects.
10472 A project is not allowed to import directly or indirectly at the same time a
10473 child project and any of its ancestors.
10476 @c ****************************************
10477 @c * External References in Project Files *
10478 @c ****************************************
10480 @node  External References in Project Files
10481 @section External References in Project Files
10483 @noindent
10484 A project file may contain references to external variables; such references
10485 are called @emph{external references}.
10487 An external variable is either defined as part of the environment (an
10488 environment variable in Unix, for example) or else specified on the command
10489 line via the @option{-X@emph{vbl}=@emph{value}} switch. If both, then the
10490 command line value is used.
10492 An external reference is denoted by the built-in function
10493 @code{external}, which returns a string value.  This function has two forms:
10494 @itemize @bullet
10495 @item @code{external (external_variable_name)}
10496 @item @code{external (external_variable_name, default_value)}
10497 @end itemize
10499 @noindent
10500 Each parameter must be a string literal.  For example:
10502 @smallexample
10503    external ("USER")
10504    external ("OS", "Linux")
10505 @end smallexample
10507 @noindent
10508 In the form with one parameter, the function returns the value of
10509 the external variable given as parameter. If this name is not present in the
10510 environment, then the returned value is an empty string.
10512 In the form with two string parameters, the second parameter is
10513 the value returned when the variable given as the first parameter is not
10514 present in the environment. In the example above, if @code{"OS"} is not
10515 the name of an environment variable and is not passed on the command line,
10516 then the returned value will be @code{"Linux"}.
10518 An external reference may be part of a string expression or of a string
10519 list expression, to define variables or attributes.
10521 @smallexample
10522 @group
10523    type Mode_Type is ("Debug", "Release");
10524    Mode : Mode_Type := external ("MODE");
10525    case Mode is
10526      when "Debug" =>
10527         ...
10528 @end group
10529 @end smallexample
10532 @c *****************************
10533 @c * Packages in Project Files *
10534 @c *****************************
10536 @node  Packages in Project Files
10537 @section Packages in Project Files
10539 @noindent
10540 The @emph{package} is the project file feature that defines the settings for
10541 project-aware tools.
10542 For each such tool you can declare a corresponding package; the names for these
10543 packages are preset (see @ref{Packages}) but are not case sensitive.
10544 A package may contain variable declarations, attribute declarations, and case
10545 constructions.
10547 @smallexample
10548 @group
10549    project Proj is
10550       package Builder is  -- used by gnatmake
10551          for Default_Switches ("Ada") use ("-v", "-g");
10552       end Builder;
10553    end Proj;
10554 @end group
10555 @end smallexample
10557 @noindent
10558 A package declaration starts with the reserved word @code{package},
10559 followed by the package name (case insensitive), followed by the reserved word
10560 @code{is}. It ends with the reserved word @code{end}, followed by the package
10561 name, finally followed by a semi-colon.
10563 Most of the packages have an attribute @code{Default_Switches}.
10564 This attribute is an associative array, and its value is a string list.
10565 The index of the associative array is the name of a programming language (case
10566 insensitive). This attribute indicates the switch or switches to be used
10567 with the corresponding tool.
10569 Some packages also have another attribute, @code{Switches}, an associative
10570 array whose value is a string list. The index is the name of a source file.
10571 This attribute indicates the switch or switches to be used by the corresponding
10572 tool when dealing with this specific file.
10574 Further information on these switch-related attributes is found in
10575 @ref{Switches and Project Files}.
10577 A package may be declared as a @emph{renaming} of another package; e.g., from
10578 the project file for an imported project.
10580 @smallexample
10581 @group
10582   with "/global/apex.gpr";
10583   project Example is
10584     package Naming renames Apex.Naming;
10585     ...
10586   end Example;
10587 @end group
10588 @end smallexample
10590 @noindent
10591 Packages that are renamed in other project files often come from project files
10592 that have no sources: they are just used as templates. Any modification in the
10593 template will be reflected automatically in all the project files that rename
10594 a package from the template.
10596 In addition to the tool-oriented packages, you can also declare a package
10597 named @code{Naming} to establish specialized source file naming conventions
10598 (see @ref{Naming Schemes}).
10601 @c ************************************
10602 @c * Variables from Imported Projects *
10603 @c ************************************
10605 @node Variables from Imported Projects
10606 @section Variables from Imported Projects
10608 @noindent
10609 An attribute or variable defined in an imported or parent project can
10610 be used in expressions in the importing / extending project.
10611 Such an attribute or variable is prefixed with the name of the project
10612 and (if relevant) the name of package where it is defined.
10614 @smallexample
10615 @group
10616   with "imported";
10617   project Main extends "base" is
10618      Var1 := Imported.Var;
10619      Var2 := Base.Var & ".new";
10620 @end group
10622 @group
10623      package Builder is
10624         for Default_Switches ("Ada") use Imported.Builder.Ada_Switches &
10625                          "-gnatg" & "-v";
10626      end Builder;
10627 @end group
10629 @group
10630      package Compiler is
10631         for Default_Switches ("Ada") use Base.Compiler.Ada_Switches;
10632      end Compiler;
10633   end Main;
10634 @end group
10635 @end smallexample
10637 @noindent
10638 In this example:
10640 @itemize @bullet
10641 @item
10642 @code{Var1} is a copy of the variable @code{Var} defined in the project file
10643 @file{"imported.gpr"}
10644 @item
10645 the value of @code{Var2} is a copy of the value of variable @code{Var}
10646 defined in the project file @file{base.gpr}, concatenated with @code{".new"}
10647 @item
10648 attribute @code{Default_Switches ("Ada")} in package @code{Builder}
10649 is a string list that includes in its value a copy of variable
10650 @code{Ada_Switches} defined in the @code{Builder} package in project file
10651 @file{imported.gpr} plus two new elements: @option{"-gnatg"} and @option{"-v"};
10652 @item
10653 attribute @code{Default_Switches ("Ada")} in package @code{Compiler}
10654 is a copy of the variable @code{Ada_Switches} defined in the @code{Compiler}
10655 package in project file @file{base.gpr}, the project being extended.
10656 @end itemize
10659 @c ******************
10660 @c * Naming Schemes *
10661 @c ******************
10663 @node  Naming Schemes
10664 @section Naming Schemes
10666 @noindent
10667 Sometimes an Ada software system is ported from a foreign compilation
10668 environment to GNAT, with file names that do not use the default GNAT
10669 conventions. Instead of changing all the file names (which for a variety of
10670 reasons might not be possible), you can define the relevant file naming scheme
10671 in the @code{Naming} package in your project file.  For example, the following
10672 package models the Apex file naming rules:
10674 @smallexample
10675 @group
10676   package Naming is
10677     for Casing                        use "lowercase";
10678     for Dot_Replacement               use ".";
10679     for Specification_Suffix ("Ada")  use ".1.ada";
10680     for Implementation_Suffix ("Ada") use ".2.ada";
10681   end Naming;
10682 @end group
10683 @end smallexample
10685 @noindent
10686 You can define the following attributes in package @code{Naming}:
10688 @table @code
10690 @item @var{Casing}
10691 This must be a string with one of the three values @code{"lowercase"},
10692 @code{"uppercase"} or @code{"mixedcase"}; these strings are case insensitive.
10694 @noindent
10695 If @var{Casing} is not specified, then the default is @code{"lowercase"}.
10697 @item @var{Dot_Replacement}
10698 This must be a string whose value satisfies the following conditions:
10700 @itemize @bullet
10701 @item It must not be empty
10702 @item It cannot start or end with an alphanumeric character
10703 @item It cannot be a single underscore
10704 @item It cannot start with an underscore followed by an alphanumeric
10705 @item It cannot contain a dot @code{'.'} except if it the entire string is @code{"."}
10706 @end itemize
10708 @noindent
10709 If @code{Dot_Replacement} is not specified, then the default is @code{"-"}.
10711 @item @var{Specification_Suffix}
10712 This is an associative array (indexed by the programming language name, case
10713 insensitive) whose value is a string that must satisfy the following
10714 conditions:
10716 @itemize @bullet
10717 @item It must not be empty
10718 @item It cannot start with an alphanumeric character
10719 @item It cannot start with an underscore followed by an alphanumeric character
10720 @end itemize
10721 @noindent
10722 If @code{Specification_Suffix ("Ada")} is not specified, then the default is
10723 @code{".ads"}.
10725 @item @var{Implementation_Suffix}
10726 This is an associative array (indexed by the programming language name, case
10727 insensitive) whose value is a string that must satisfy the following
10728 conditions:
10730 @itemize @bullet
10731 @item It must not be empty
10732 @item It cannot start with an alphanumeric character
10733 @item It cannot start with an underscore followed by an alphanumeric character
10734 @item It cannot be a suffix of @code{Specification_Suffix}
10735 @end itemize
10736 @noindent
10737 If @code{Implementation_Suffix ("Ada")} is not specified, then the default is
10738 @code{".adb"}.
10740 @item @var{Separate_Suffix}
10741 This must be a string whose value satisfies the same conditions as
10742 @code{Implementation_Suffix}.
10744 @noindent
10745 If @code{Separate_Suffix ("Ada")} is not specified, then it defaults to same
10746 value as @code{Implementation_Suffix ("Ada")}.
10748 @item @var{Specification}
10749 @noindent
10750 You can use the @code{Specification} attribute, an associative array, to define
10751 the source file name for an individual Ada compilation unit's spec. The array
10752 index must be a string literal that identifies the Ada unit (case insensitive).
10753 The value of this attribute must be a string that identifies the file that
10754 contains this unit's spec (case sensitive or insensitive depending on the
10755 operating system).
10757 @smallexample
10758    for Specification ("MyPack.MyChild") use "mypack.mychild.spec";
10759 @end smallexample
10761 @item @var{Implementation}
10763 You can use the @code{Implementation} attribute, an associative array, to
10764 define the source file name for an individual Ada compilation unit's body
10765 (possibly a subunit).  The array index must be a string literal that identifies
10766 the Ada unit (case insensitive).  The value of this attribute must be a string
10767 that identifies the file that contains this unit's body or subunit (case
10768 sensitive or insensitive depending on the operating system).
10770 @smallexample
10771    for Implementation ("MyPack.MyChild") use "mypack.mychild.body";
10772 @end smallexample
10773 @end table
10776 @c ********************
10777 @c * Library Projects *
10778 @c ********************
10780 @node Library Projects
10781 @section Library Projects
10783 @noindent
10784 @emph{Library projects} are projects whose object code is placed in a library.
10785 (Note that this facility is not yet supported on all platforms)
10787 To create a library project, you need to define in its project file
10788 two project-level attributes: @code{Library_Name} and @code{Library_Dir}.
10789 Additionally, you may define the library-related attributes
10790 @code{Library_Kind}, @code{Library_Version} and @code{Library_Elaboration}.
10792 The @code{Library_Name} attribute has a string value that must start with a
10793 letter and include only letters and digits.
10795 The @code{Library_Dir} attribute has a string value that designates the path
10796 (absolute or relative) of the directory where the library will reside.
10797 It must designate an existing directory, and this directory needs to be
10798 different from the project's object directory. It also needs to be writable.
10800 If both @code{Library_Name} and @code{Library_Dir} are specified and
10801 are legal, then the project file defines a library project.  The optional
10802 library-related attributes are checked only for such project files.
10804 The @code{Library_Kind} attribute has a string value that must be one of the
10805 following (case insensitive): @code{"static"}, @code{"dynamic"} or
10806 @code{"relocatable"}. If this attribute is not specified, the library is a
10807 static library. Otherwise, the library may be dynamic or relocatable.
10808 Depending on the operating system, there may or may not be a distinction
10809 between dynamic and relocatable libraries. For example, on Unix there is no
10810 such distinction.
10812 The @code{Library_Version} attribute has a string value whose interpretation
10813 is platform dependent. On Unix, it is used only for dynamic/relocatable
10814 libraries as the internal name of the library (the @code{"soname"}). If the
10815 library file name (built from the @code{Library_Name}) is different from the
10816 @code{Library_Version}, then the library file will be a symbolic link to the
10817 actual file whose name will be @code{Library_Version}.
10819 Example (on Unix):
10821 @smallexample
10822 @group
10823 project Plib is
10825    Version := "1";
10827    for Library_Dir use "lib_dir";
10828    for Library_Name use "dummy";
10829    for Library_Kind use "relocatable";
10830    for Library_Version use "libdummy.so." & Version;
10832 end Plib;
10833 @end group
10834 @end smallexample
10836 @noindent
10837 Directory @file{lib_dir} will contain the internal library file whose name
10838 will be @file{libdummy.so.1}, and @file{libdummy.so} will be a symbolic link to
10839 @file{libdummy.so.1}.
10841 When @command{gnatmake} detects that a project file (not the main project file)
10842 is a library project file, it will check all immediate sources of the project
10843 and rebuild the library if any of the sources have been recompiled.
10844 All @file{ALI} files will also be copied from the object directory to the
10845 library directory. To build executables, @command{gnatmake} will use the
10846 library rather than the individual object files.
10849 @c *************************************
10850 @c * Switches Related to Project Files *
10851 @c *************************************
10852 @node Switches Related to Project Files
10853 @section Switches Related to Project Files
10855 @noindent
10856 The following switches are used by GNAT tools that support project files:
10858 @table @code
10860 @item @option{-P@var{project}}
10861 Indicates the name of a project file. This project file will be parsed with
10862 the verbosity indicated by @option{-vP@emph{x}}, if any, and using the external
10863 references indicated by @option{-X} switches, if any.
10865 @noindent
10866 There must be only one @option{-P} switch on the command line.
10868 @noindent
10869 Since the Project Manager parses the project file only after all the switches
10870 on the command line are checked, the order of the switches @option{-P},
10871 @option{-Vp@emph{x}} or @option{-X} is not significant.
10873 @item @option{-X@var{name=value}}
10874 Indicates that external variable @var{name} has the value @var{value}.
10875 The Project Manager will use this value for occurrences of
10876 @code{external(name)} when parsing the project file.
10878 @noindent
10879 If @var{name} or @var{value} includes a space, then @var{name=value} should be
10880 put between quotes.
10881 @smallexample
10882   -XOS=NT
10883   -X"user=John Doe"
10884 @end smallexample
10886 @noindent
10887 Several @option{-X} switches can be used simultaneously.
10888 If several @option{-X} switches specify the same @var{name}, only the last one
10889 is used.
10891 @noindent
10892 An external variable specified with a @option{-X} switch takes precedence
10893 over the value of the same name in the environment.
10895 @item @option{-vP@emph{x}}
10896 Indicates the verbosity of the parsing of GNAT project files.
10897 @option{-vP0} means Default (no output for syntactically correct project
10898 files);
10899 @option{-vP1} means Medium;
10900 @option{-vP2} means High.
10901 @noindent
10902 The default is Default.
10903 @noindent
10904 If several @option{-vP@emph{x}} switches are present, only the last one is
10905 used.
10907 @end table
10910 @c **********************************
10911 @c * Tools Supporting Project Files *
10912 @c **********************************
10914 @node  Tools Supporting Project Files
10915 @section Tools Supporting Project Files
10917 @menu
10918 * gnatmake and Project Files::
10919 * The GNAT Driver and Project Files::
10920 @ifclear vms
10921 * Glide and Project Files::
10922 @end ifclear
10923 @end menu
10925 @node gnatmake and Project Files
10926 @subsection gnatmake and Project Files
10928 @noindent
10929 This section covers two topics related to @command{gnatmake} and project files:
10930 defining switches for @command{gnatmake} and for the tools that it invokes;
10931 and the use of the @code{Main} attribute.
10933 @menu
10934 * Switches and Project Files::
10935 * Project Files and Main Subprograms::
10936 @end menu
10938 @node Switches and Project Files
10939 @subsubsection Switches and Project Files
10941 @noindent
10942 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
10943 @code{Linker}, you can specify a @code{Default_Switches} attribute, a
10944 @code{Switches} attribute, or both; as their names imply, these switch-related
10945 attributes affect which switches are used for which files when
10946 @command{gnatmake} is invoked.  As will be explained below, these
10947 package-contributed switches precede the switches passed on the
10948 @command{gnatmake} command line.
10950 The @code{Default_Switches} attribute is an associative array indexed by
10951 language name (case insensitive) and returning a string list.  For example:
10953 @smallexample
10954 @group
10955 package Compiler is
10956   for Default_Switches ("Ada") use ("-gnaty", "-v");
10957 end Compiler;
10958 @end group
10959 @end smallexample
10961 @noindent
10962 The @code{Switches} attribute is also an associative array, indexed by a file
10963 name (which may or may not be case sensitive, depending on the operating
10964 system) and returning a string list.  For example:
10966 @smallexample
10967 @group
10968 package Builder is
10969    for Switches ("main1.adb") use ("-O2");
10970    for Switches ("main2.adb") use ("-g");
10971 end Builder;
10972 @end group
10973 @end smallexample
10975 @noindent
10976 For the @code{Builder} package, the file names should designate source files
10977 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
10978 file names should designate @file{ALI} or source files for main subprograms.
10979 In each case just the file name (without explicit extension) is acceptable.
10981 For each tool used in a program build (@command{gnatmake}, the compiler, the
10982 binder, and the linker), its corresponding package @dfn{contributes} a set of
10983 switches for each file on which the tool is invoked, based on the
10984 switch-related attributes defined in the package. In particular, the switches
10985 that each of these packages contributes for a given file @var{f} comprise:
10987 @itemize @bullet
10988 @item
10989 the value of attribute @code{Switches (@var{f})}, if it is specified in the
10990 package for the given file,
10991 @item
10992 otherwise, the value of @code{Default_Switches ("Ada")}, if it is specified in
10993 the package.
10994 @end itemize
10996 @noindent
10997 If neither of these attributes is defined in the package, then the package does
10998 not contribute any switches for the given file.
11000 When @command{gnatmake} is invoked on a file, the switches comprise two sets,
11001 in the following order: those contributed for the file by the @code{Builder}
11002 package; and the switches passed on the command line.
11004 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
11005 the switches passed to the tool comprise three sets, in the following order:
11007 @enumerate
11008 @item
11009 the applicable switches contributed for the file by the @code{Builder} package
11010 in the project file supplied on the command line;
11012 @item
11013 those contributed for the file by the package (in the relevant project file --
11014 see below) corresponding to the tool; and
11016 @item
11017 the applicable switches passed on the command line.
11018 @end enumerate
11020 @noindent
11021 The term @emph{applicable switches} reflects the fact that @command{gnatmake}
11022 switches may or may not be passed to individual tools, depending on the
11023 individual switch.
11025 @command{gnatmake} may invoke the compiler on source files from different
11026 projects. The Project Manager will use the appropriate project file to
11027 determine the @code{Compiler} package for each source file being compiled.
11028 Likewise for the @code{Binder} and @code{Linker} packages.
11030 As an example, consider the following package in a project file:
11032 @smallexample
11033 @group
11034 project Proj1 is
11035    package Compiler is
11036       for Default_Switches ("Ada") use ("-g");
11037       for Switches ("a.adb") use ("-O1");
11038       for Switches ("b.adb") use ("-O2", "-gnaty");
11039    end Compiler;
11040 end Proj1;
11041 @end group
11042 @end smallexample
11044 @noindent
11045 If @command{gnatmake} is invoked with this project file, and it needs to
11046 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
11047 @file{a.adb} will be compiled with the switch @option{-O1}, @file{b.adb}
11048 with switches @option{-O2} and @option{-gnaty}, and @file{c.adb} with
11049 @option{-g}.
11051 Another example illustrates the ordering of the switches contributed by
11052 different packages:
11054 @smallexample
11055 @group
11056 project Proj2 is
11057    package Builder is
11058       for Switches ("main.adb") use ("-g", "-O1", "-f");
11059    end Builder;
11060 @end group
11062 @group
11063    package Compiler is
11064       for Switches ("main.adb") use ("-O2");
11065    end Compiler;
11066 end Proj2;
11067 @end group
11068 @end smallexample
11070 @noindent
11071 If you issue the command:
11073 @smallexample
11074     gnatmake -PProj2 -O0 main
11075 @end smallexample
11077 @noindent
11078 then the compiler will be invoked on @file{main.adb} with the following sequence of switches
11080 @smallexample
11081    -g -O1 -O2 -O0
11082 @end smallexample
11084 with the last @option{-O} switch having precedence over the earlier ones;
11085 several other switches (such as @option{-c}) are added implicitly.
11087 The switches @option{-g} and @option{-O1} are contributed by package
11088 @code{Builder},  @option{-O2} is contributed by the package @code{Compiler}
11089 and @option{-O0} comes from the command line.
11091 The @option{-g} switch will also be passed in the invocation of
11092 @command{gnatlink.}
11094 A final example illustrates switch contributions from packages in different
11095 project files:
11097 @smallexample
11098 @group
11099 project Proj3 is
11100    for Source_Files use ("pack.ads", "pack.adb");
11101    package Compiler is
11102       for Default_Switches ("Ada") use ("-gnata");
11103    end Compiler;
11104 end Proj3;
11105 @end group
11107 @group
11108 with "Proj3";
11109 project Proj4 is
11110    for Source_Files use ("foo_main.adb", "bar_main.adb");
11111    package Builder is
11112       for Switches ("foo_main.adb") use ("-s", "-g");
11113    end Builder;
11114 end Proj4;
11115 @end group
11117 @group
11118 -- Ada source file:
11119 with Pack;
11120 procedure Foo_Main is
11121    ...
11122 end Foo_Main;
11123 @end group
11124 @end smallexample
11126 If the command is
11127 @smallexample
11128 gnatmake -PProj4 foo_main.adb -cargs -gnato
11129 @end smallexample
11131 @noindent
11132 then the switches passed to the compiler for @file{foo_main.adb} are
11133 @option{-g} (contributed by the package @code{Proj4.Builder}) and
11134 @option{-gnato} (passed on the command line).
11135 When the imported package @code{Pack} is compiled, the switches used are
11136 @option{-g} from @code{Proj4.Builder}, @option{-gnata} (contributed from
11137 package @code{Proj3.Compiler}, and @option{-gnato} from the command line.
11140 @node Project Files and Main Subprograms
11141 @subsubsection Project Files and Main Subprograms
11143 @noindent
11144 When using a project file, you can invoke @command{gnatmake}
11145 with several main subprograms, by specifying their source files on the command
11146 line.  Each of these needs to be an immediate source file of the project.
11148 @smallexample
11149     gnatmake -Pprj main1 main2 main3
11150 @end smallexample
11152 @noindent
11153 When using a project file, you can also invoke @command{gnatmake} without
11154 explicitly specifying any main, and the effect depends on whether you have
11155 defined the @code{Main} attribute.  This attribute has a string list value,
11156 where each element in the list is the name of a source file (the file
11157 extension is optional) containing a main subprogram.
11159 If the @code{Main} attribute is defined in a project file as a non-empty
11160 string list and the switch @option{-u} is not used on the command line, then
11161 invoking @command{gnatmake} with this project file but without any main on the
11162 command line is equivalent to invoking @command{gnatmake} with all the file
11163 names in the @code{Main} attribute on the command line.
11165 Example:
11166 @smallexample
11167 @group
11168    project Prj is
11169       for Main use ("main1", "main2", "main3");
11170    end Prj;
11171 @end group
11172 @end smallexample
11174 @noindent
11175 With this project file, @code{"gnatmake -Pprj"} is equivalent to
11176 @code{"gnatmake -Pprj main1 main2 main3"}.
11178 When the project attribute @code{Main} is not specified, or is specified
11179 as an empty string list, or when the switch @option{-u} is used on the command
11180 line, then invoking @command{gnatmake} with no main on the command line will
11181 result in all immediate sources of the project file being checked, and
11182 potentially recompiled. Depending on the presence of the switch @option{-u},
11183 sources from other project files on which the immediate sources of the main
11184 project file depend are also checked and potentially recompiled. In other
11185 words, the @option{-u} switch is applied to all of the immediate sources of themain project file.
11188 @node The GNAT Driver and Project Files
11189 @subsection The GNAT Driver and Project Files
11191 @noindent
11192 A number of GNAT tools, other than @command{gnatmake} are project-aware:
11193 @command{gnatbind}, @command{gnatfind}, @command{gnatlink}, @command{gnatls}
11194 and @command{gnatxref}. However, none of these tools can be invoked directly
11195 with a project file switch (@code{-P}). They need to be invoke through the
11196 @command{gnat} driver.
11198 The @command{gnat} driver is a front-end that accepts a number of commands and
11199 call the corresponding tool. It has been designed initially for VMS to convert
11200 VMS style qualifiers to Unix style switches, but it is now available to all
11201 the GNAT supported platforms.
11203 On non VMS platforms, the @command{gnat} driver accepts the following commands
11204 (case insensitive):
11206 @itemize @bullet
11207 @item
11208 BIND to invoke @command{gnatbind}
11209 @item
11210 CHOP to invoke @command{gnatchop}
11211 @item
11212 COMP or COMPILE to invoke the compiler
11213 @item
11214 ELIM to invoke @command{gnatelim}
11215 @item
11216 FIND to invoke @command{gnatfind}
11217 @item
11218 KR or KRUNCH to invoke @command{gnatkr}
11219 @item
11220 LINK to invoke @command{gnatlink}
11221 @item
11222 LS or LIST to invoke @command{gnatls}
11223 @item
11224 MAKE to invoke @command{gnatmake}
11225 @item
11226 NAME to invoke @command{gnatname}
11227 @item
11228 PREP or PREPROCESS to invoke @command{gnatprep}
11229 @item
11230 PSTA or STANDARD to invoke @command{gnatpsta}
11231 @item
11232 STUB to invoke @command{gnatstub}
11233 @item
11234 XREF to invoke @command{gnatxref}
11235 @end itemize
11237 @noindent
11238 Note that the compiler is invoked using the command @command{gnatmake -f -u}.
11240 @noindent
11241 Following the command, you may put switches and arguments for the invoked
11242 tool.
11244 @smallexample
11245   gnat bind -C main.ali
11246   gnat ls -a main
11247   gnat chop foo.txt
11248 @end smallexample
11250 @noindent
11251 In addition, for command BIND, FIND, LS or LIST, LINK and XREF, the project
11252 file related switches (@code{-P}, @code{-X} and @code{-vPx}) may be used in
11253 addition to the switches of the invoking tool.
11255 @noindent
11256 For each of these command, there is possibly a package in the main project that
11257 corresponds to the invoked tool.
11259 @itemize @bullet
11260 @item
11261 package @code{Binder} for command BIND (invoking @code{gnatbind})
11263 @item
11264 package @code{Finder} for command FIND (invoking @code{gnatfind})
11266 @item
11267 package @code{Gnatls} for command LS or LIST (invoking @code{gnatls})
11269 @item
11270 package @code{Linker} for command LINK (invoking @code{gnatlink})
11272 @item
11273 package @code{Cross_Reference} for command XREF (invoking @code{gnatlink})
11275 @end itemize
11277 @noindent
11278 Package @code{Gnatls} has a unique attribute @code{Switches}, a simple variable
11279 with a string list value. It contains switches for the invocation of
11280 @code{gnatls}.
11282 @smallexample
11283 @group
11284 project Proj1 is
11285    package gnatls is
11286       for Switches use ("-a", "-v");
11287    end gnatls;
11288 end Proj1;
11289 @end group
11290 @end smallexample
11292 @noindent
11293 All other packages contains a switch @code{Default_Switches}, an associative
11294 array, indexed by the programming language (case insensitive) and having a
11295 string list value. @code{Default_Switches ("Ada")} contains the switches for
11296 the invocation of the tool corresponding to the package.
11298 @smallexample
11299 @group
11300 project Proj is
11302    for Source_Dirs use ("./**");
11304    package gnatls is
11305       for Switches use ("-a", "-v");
11306    end gnatls;
11307 @end group
11308 @group
11310    package Binder is
11311       for Default_Switches ("Ada") use ("-C", "-e");
11312    end Binder;
11313 @end group
11314 @group
11316    package Linker is
11317       for Default_Switches ("Ada") use ("-C");
11318    end Linker;
11319 @end group
11320 @group
11322    package Finder is
11323       for Default_Switches ("Ada") use ("-a", "-f");
11324    end Finder;
11325 @end group
11326 @group
11328    package Cross_Reference is
11329       for Default_Switches ("Ada") use ("-a", "-f", "-d", "-u");
11330    end Cross_Reference;
11331 end Proj;
11332 @end group
11333 @end smallexample
11335 @noindent
11336 With the above project file, commands such as
11338 @smallexample
11339    gnat ls -Pproj main
11340    gnat xref -Pproj main
11341    gnat bind -Pproj main.ali
11342 @end smallexample
11344 @noindent
11345 will set up the environment properly and invoke the tool with the switches
11346 found in the package corresponding to the tool.
11349 @ifclear vms
11350 @node Glide and Project Files
11351 @subsection Glide and Project Files
11353 @noindent
11354 Glide will automatically recognize the @file{.gpr} extension for
11355 project files, and will
11356 convert them to its own internal format automatically. However, it
11357 doesn't provide a syntax-oriented editor for modifying these
11358 files.
11359 The project file will be loaded as text when you select the menu item
11360 @code{Ada} @result{} @code{Project} @result{} @code{Edit}.
11361 You can edit this text and save the @file{gpr} file;
11362 when you next select this project file in Glide it
11363 will be automatically reloaded.
11365 @ifset vxworks
11366 Glide uses the @code{gnatlist} attribute in the @code{Ide} package, whose value
11367 is something like @code{powerpc-wrs-vxworks-gnatls}, to compute the
11368 cross-prefix.  From this information the correct location for the
11369 GNAT runtime, and thus also the correct cross-references, can be
11370 determined.
11371 @end ifset
11372 @end ifclear
11375 @node An Extended Example
11376 @section An Extended Example
11378 @noindent
11379 Suppose that we have two programs, @var{prog1} and @var{prog2}, with the sources
11380 in the respective directories. We would like to build them with a single
11381 @command{gnatmake} command, and we would like to place their object files into
11382 @file{.build} subdirectories of the source directories. Furthermore, we would
11383 like to have to have two separate subdirectories in @file{.build}  --
11384 @file{release} and @file{debug} -- which will contain the object files compiled with
11385 different set of compilation flags.
11387 In other words, we have the following structure:
11389 @smallexample
11390 @group
11391    main
11392      |- prog1
11393      |    |- .build
11394      |         | debug
11395      |         | release
11396      |- prog2
11397           |- .build
11398                | debug
11399                | release
11400 @end group
11401 @end smallexample
11403 @noindent
11404 Here are the project files that we need to create in a directory @file{main}
11405 to maintain this structure:
11407 @enumerate
11409 @item We create a @code{Common} project with a package @code{Compiler} that
11410 specifies the compilation switches:
11412 @smallexample
11413 File "common.gpr":
11414 @group
11415 @b{project} Common @b{is}
11417    @b{for} Source_Dirs @b{use} (); -- No source files
11418 @end group
11420 @group
11421    @b{type} Build_Type @b{is} ("release", "debug");
11422    Build : Build_Type := External ("BUILD", "debug");
11423 @end group
11424 @group
11425    @b{package} Compiler @b{is}
11426       @b{case} Build @b{is}
11427          @b{when} "release" =>
11428            @b{for} Default_Switches ("Ada") @b{use} ("-O2");
11429          @b{when} "debug"   =>
11430            @b{for} Default_Switches ("Ada") @b{use} ("-g");
11431       @b{end case};
11432    @b{end} Compiler;
11434 @b{end} Common;
11435 @end group
11436 @end smallexample
11438 @item We create separate projects for the two programs:
11440 @smallexample
11441 @group
11442 File "prog1.gpr":
11444 @b{with} "common";
11445 @b{project} Prog1 @b{is}
11447     @b{for} Source_Dirs @b{use} ("prog1");
11448     @b{for} Object_Dir  @b{use} "prog1/.build/" & Common.Build;
11450     @b{package} Compiler @b{renames} Common.Compiler;
11452 @b{end} Prog1;
11453 @end group
11454 @end smallexample
11456 @smallexample
11457 @group
11458 File "prog2.gpr":
11460 @b{with} "common";
11461 @b{project} Prog2 @b{is}
11463     @b{for} Source_Dirs @b{use} ("prog2");
11464     @b{for} Object_Dir  @b{use} "prog2/.build/" & Common.Build;
11466     @b{package} Compiler @b{renames} Common.Compiler;
11468 @end group
11469 @b{end} Prog2;
11470 @end smallexample
11472 @item We create a wrapping project @var{Main}:
11474 @smallexample
11475 @group
11476 File "main.gpr":
11478 @b{with} "common";
11479 @b{with} "prog1";
11480 @b{with} "prog2";
11481 @b{project} Main @b{is}
11483    @b{package} Compiler @b{renames} Common.Compiler;
11485 @b{end} Main;
11486 @end group
11487 @end smallexample
11489 @item Finally we need to create a dummy procedure that @code{with}s (either
11490 explicitly or implicitly) all the sources of our two programs.
11492 @end enumerate
11494 @noindent
11495 Now we can build the programs using the command
11497 @smallexample
11498    gnatmake -Pmain dummy
11499 @end smallexample
11501 @noindent
11502 for the Debug mode, or
11504 @smallexample
11505    gnatmake -Pmain -XBUILD=release
11506 @end smallexample
11508 @noindent
11509 for the Release mode.
11512 @c ********************************
11513 @c * Project File Complete Syntax *
11514 @c ********************************
11516 @node Project File Complete Syntax
11517 @section Project File Complete Syntax
11519 @smallexample
11520 project ::=
11521   context_clause project_declaration
11523 context_clause ::=
11524   @{with_clause@}
11526 with_clause ::=
11527   @b{with} literal_string @{ , literal_string @} ;
11529 project_declaration ::=
11530   @b{project} <project_>simple_name [ @b{extends} literal_string ] @b{is}
11531     @{declarative_item@}
11532   @b{end} <project_>simple_name;
11534 declarative_item ::=
11535   package_declaration |
11536   typed_string_declaration |
11537   other_declarative_item
11539 package_declaration ::=
11540   @b{package} <package_>simple_name package_completion
11542 package_completion ::=
11543   package_body | package_renaming
11545 package body ::=
11546   @b{is}
11547     @{other_declarative_item@}
11548   @b{end} <package_>simple_name ;
11550 package_renaming ::==
11551   @b{renames} <project_>simple_name.<package_>simple_name ;
11553 typed_string_declaration ::=
11554   @b{type} <typed_string_>_simple_name @b{is}
11555    ( literal_string @{, literal_string@} );
11557 other_declarative_item ::=
11558   attribute_declaration |
11559   typed_variable_declaration |
11560   variable_declaration |
11561   case_construction
11563 attribute_declaration ::=
11564   @b{for} attribute @b{use} expression ;
11566 attribute ::=
11567   <simple_attribute_>simple_name |
11568   <associative_array_attribute_>simple_name ( literal_string )
11570 typed_variable_declaration ::=
11571   <typed_variable_>simple_name : <typed_string_>name :=  string_expression ;
11573 variable_declaration ::=
11574   <variable_>simple_name := expression;
11576 expression ::=
11577   term @{& term@}
11579 term ::=
11580   literal_string |
11581   string_list |
11582   <variable_>name |
11583   external_value |
11584   attribute_reference
11586 literal_string ::=
11587   (same as Ada)
11589 string_list ::=
11590   ( <string_>expression @{ , <string_>expression @} )
11592 external_value ::=
11593   @b{external} ( literal_string [, literal_string] )
11595 attribute_reference ::=
11596   attribute_parent ' <simple_attribute_>simple_name [ ( literal_string ) ]
11598 attribute_parent ::=
11599   @b{project} |
11600   <project_or_package>simple_name |
11601   <project_>simple_name . <package_>simple_name
11603 case_construction ::=
11604   @b{case} <typed_variable_>name @b{is}
11605     @{case_item@}
11606   @b{end case} ;
11608 case_item ::=
11609   @b{when} discrete_choice_list => @{case_construction | attribute_declaration@}
11611 discrete_choice_list ::=
11612   literal_string @{| literal_string@}
11614 name ::=
11615   simple_name @{. simple_name@}
11617 simple_name ::=
11618   identifier (same as Ada)
11620 @end smallexample
11623 @node Elaboration Order Handling in GNAT
11624 @chapter Elaboration Order Handling in GNAT
11625 @cindex Order of elaboration
11626 @cindex Elaboration control
11628 @menu
11629 * Elaboration Code in Ada 95::
11630 * Checking the Elaboration Order in Ada 95::
11631 * Controlling the Elaboration Order in Ada 95::
11632 * Controlling Elaboration in GNAT - Internal Calls::
11633 * Controlling Elaboration in GNAT - External Calls::
11634 * Default Behavior in GNAT - Ensuring Safety::
11635 * Elaboration Issues for Library Tasks::
11636 * Mixing Elaboration Models::
11637 * What to Do If the Default Elaboration Behavior Fails::
11638 * Elaboration for Access-to-Subprogram Values::
11639 * Summary of Procedures for Elaboration Control::
11640 * Other Elaboration Order Considerations::
11641 @end menu
11643 @noindent
11644 This chapter describes the handling of elaboration code in Ada 95 and
11645 in GNAT, and discusses how the order of elaboration of program units can
11646 be controlled in GNAT, either automatically or with explicit programming
11647 features.
11649 @node Elaboration Code in Ada 95
11650 @section Elaboration Code in Ada 95
11652 @noindent
11653 Ada 95 provides rather general mechanisms for executing code at elaboration
11654 time, that is to say before the main program starts executing. Such code arises
11655 in three contexts:
11657 @table @asis
11658 @item Initializers for variables.
11659 Variables declared at the library level, in package specs or bodies, can
11660 require initialization that is performed at elaboration time, as in:
11661 @smallexample
11662 @cartouche
11663 Sqrt_Half : Float := Sqrt (0.5);
11664 @end cartouche
11665 @end smallexample
11667 @item Package initialization code
11668 Code in a @code{BEGIN-END} section at the outer level of a package body is
11669 executed as part of the package body elaboration code.
11671 @item Library level task allocators
11672 Tasks that are declared using task allocators at the library level
11673 start executing immediately and hence can execute at elaboration time.
11674 @end table
11676 @noindent
11677 Subprogram calls are possible in any of these contexts, which means that
11678 any arbitrary part of the program may be executed as part of the elaboration
11679 code. It is even possible to write a program which does all its work at
11680 elaboration time, with a null main program, although stylistically this
11681 would usually be considered an inappropriate way to structure
11682 a program.
11684 An important concern arises in the context of elaboration code:
11685 we have to be sure that it is executed in an appropriate order. What we
11686 have is a series of elaboration code sections, potentially one section
11687 for each unit in the program. It is important that these execute
11688 in the correct order. Correctness here means that, taking the above
11689 example of the declaration of @code{Sqrt_Half},
11690 if some other piece of
11691 elaboration code references @code{Sqrt_Half},
11692 then it must run after the
11693 section of elaboration code that contains the declaration of
11694 @code{Sqrt_Half}.
11696 There would never be any order of elaboration problem if we made a rule
11697 that whenever you @code{with} a unit, you must elaborate both the spec and body
11698 of that unit before elaborating the unit doing the @code{with}'ing:
11700 @smallexample
11701 @group
11702 @cartouche
11703 @b{with} Unit_1;
11704 @b{package} Unit_2 @b{is} ...
11705 @end cartouche
11706 @end group
11707 @end smallexample
11709 @noindent
11710 would require that both the body and spec of @code{Unit_1} be elaborated
11711 before the spec of @code{Unit_2}. However, a rule like that would be far too
11712 restrictive. In particular, it would make it impossible to have routines
11713 in separate packages that were mutually recursive.
11715 You might think that a clever enough compiler could look at the actual
11716 elaboration code and determine an appropriate correct order of elaboration,
11717 but in the general case, this is not possible. Consider the following
11718 example.
11720 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
11721 that references
11722 the variable @code{Sqrt_1}, which is declared in the elaboration code
11723 of the body of @code{Unit_1}:
11725 @smallexample
11726 @cartouche
11727 Sqrt_1 : Float := Sqrt (0.1);
11728 @end cartouche
11729 @end smallexample
11731 @noindent
11732 The elaboration code of the body of @code{Unit_1} also contains:
11734 @smallexample
11735 @group
11736 @cartouche
11737 @b{if} expression_1 = 1 @b{then}
11738    Q := Unit_2.Func_2;
11739 @b{end if};
11740 @end cartouche
11741 @end group
11742 @end smallexample
11744 @noindent
11745 @code{Unit_2} is exactly parallel,
11746 it has a procedure @code{Func_2} that references
11747 the variable @code{Sqrt_2}, which is declared in the elaboration code of
11748 the body @code{Unit_2}:
11750 @smallexample
11751 @cartouche
11752 Sqrt_2 : Float := Sqrt (0.1);
11753 @end cartouche
11754 @end smallexample
11756 @noindent
11757 The elaboration code of the body of @code{Unit_2} also contains:
11759 @smallexample
11760 @group
11761 @cartouche
11762 @b{if} expression_2 = 2 @b{then}
11763    Q := Unit_1.Func_1;
11764 @b{end if};
11765 @end cartouche
11766 @end group
11767 @end smallexample
11769 @noindent
11770 Now the question is, which of the following orders of elaboration is
11771 acceptable:
11773 @smallexample
11774 @group
11775 Spec of Unit_1
11776 Spec of Unit_2
11777 Body of Unit_1
11778 Body of Unit_2
11779 @end group
11780 @end smallexample
11782 @noindent
11785 @smallexample
11786 @group
11787 Spec of Unit_2
11788 Spec of Unit_1
11789 Body of Unit_2
11790 Body of Unit_1
11791 @end group
11792 @end smallexample
11794 @noindent
11795 If you carefully analyze the flow here, you will see that you cannot tell
11796 at compile time the answer to this question.
11797 If @code{expression_1} is not equal to 1,
11798 and @code{expression_2} is not equal to 2,
11799 then either order is acceptable, because neither of the function calls is
11800 executed. If both tests evaluate to true, then neither order is acceptable
11801 and in fact there is no correct order.
11803 If one of the two expressions is true, and the other is false, then one
11804 of the above orders is correct, and the other is incorrect. For example,
11805 if @code{expression_1} = 1 and @code{expression_2} /= 2,
11806 then the call to @code{Func_2}
11807 will occur, but not the call to @code{Func_1.}
11808 This means that it is essential
11809 to elaborate the body of @code{Unit_1} before
11810 the body of @code{Unit_2}, so the first
11811 order of elaboration is correct and the second is wrong.
11813 By making @code{expression_1} and @code{expression_2}
11814 depend on input data, or perhaps
11815 the time of day, we can make it impossible for the compiler or binder
11816 to figure out which of these expressions will be true, and hence it
11817 is impossible to guarantee a safe order of elaboration at run time.
11819 @node Checking the Elaboration Order in Ada 95
11820 @section Checking the Elaboration Order in Ada 95
11822 @noindent
11823 In some languages that involve the same kind of elaboration problems,
11824 e.g. Java and C++, the programmer is expected to worry about these
11825 ordering problems himself, and it is common to
11826 write a program in which an incorrect elaboration order  gives
11827 surprising results, because it references variables before they
11828 are initialized.
11829 Ada 95 is designed to be a safe language, and a programmer-beware approach is
11830 clearly not sufficient. Consequently, the language provides three lines
11831 of defense:
11833 @table @asis
11834 @item Standard rules
11835 Some standard rules restrict the possible choice of elaboration
11836 order. In particular, if you @code{with} a unit, then its spec is always
11837 elaborated before the unit doing the @code{with}. Similarly, a parent
11838 spec is always elaborated before the child spec, and finally
11839 a spec is always elaborated before its corresponding body.
11841 @item Dynamic elaboration checks
11842 @cindex Elaboration checks
11843 @cindex Checks, elaboration
11844 Dynamic checks are made at run time, so that if some entity is accessed
11845 before it is elaborated (typically  by means of a subprogram call)
11846 then the exception (@code{Program_Error}) is raised.
11848 @item Elaboration control
11849 Facilities are provided for the programmer to specify the desired order
11850 of elaboration.
11851 @end table
11853 Let's look at these facilities in more detail. First, the rules for
11854 dynamic checking. One possible rule would be simply to say that the
11855 exception is raised if you access a variable which has not yet been
11856 elaborated. The trouble with this approach is that it could require
11857 expensive checks on every variable reference. Instead Ada 95 has two
11858 rules which are a little more restrictive, but easier to check, and
11859 easier to state:
11861 @table @asis
11862 @item Restrictions on calls
11863 A subprogram can only be called at elaboration time if its body
11864 has been elaborated. The rules for elaboration given above guarantee
11865 that the spec of the subprogram has been elaborated before the
11866 call, but not the body. If this rule is violated, then the
11867 exception @code{Program_Error} is raised.
11869 @item Restrictions on instantiations
11870 A generic unit can only be instantiated if the body of the generic
11871 unit has been elaborated. Again, the rules for elaboration given above
11872 guarantee that the spec of the generic unit has been elaborated
11873 before the instantiation, but not the body. If this rule is
11874 violated, then the exception @code{Program_Error} is raised.
11875 @end table
11877 @noindent
11878 The idea is that if the body has been elaborated, then any variables
11879 it references must have been elaborated; by checking for the body being
11880 elaborated we guarantee that none of its references causes any
11881 trouble. As we noted above, this is a little too restrictive, because a
11882 subprogram that has no non-local references in its body may in fact be safe
11883 to call. However, it really would be unsafe to rely on this, because
11884 it would mean that the caller was aware of details of the implementation
11885 in the body. This goes against the basic tenets of Ada.
11887 A plausible implementation can be described as follows.
11888 A Boolean variable is associated with each subprogram
11889 and each generic unit. This variable is initialized to False, and is set to
11890 True at the point body is elaborated. Every call or instantiation checks the
11891 variable, and raises @code{Program_Error} if the variable is False.
11893 Note that one might think that it would be good enough to have one Boolean
11894 variable for each package, but that would not deal with cases of trying
11895 to call a body in the same package as the call
11896 that has not been elaborated yet.
11897 Of course a compiler may be able to do enough analysis to optimize away
11898 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
11899 does such optimizations, but still the easiest conceptual model is to
11900 think of there being one variable per subprogram.
11902 @node Controlling the Elaboration Order in Ada 95
11903 @section Controlling the Elaboration Order in Ada 95
11905 @noindent
11906 In the previous section we discussed the rules in Ada 95 which ensure
11907 that @code{Program_Error} is raised if an incorrect elaboration order is
11908 chosen. This prevents erroneous executions, but we need mechanisms to
11909 specify a correct execution and avoid the exception altogether.
11910 To achieve this, Ada 95 provides a number of features for controlling
11911 the order of elaboration. We discuss these features in this section.
11913 First, there are several ways of indicating to the compiler that a given
11914 unit has no elaboration problems:
11916 @table @asis
11917 @item packages that do not require a body
11918 In Ada 95, a library package that does not require a body does not permit
11919 a body. This means that if we have a such a package, as in:
11921 @smallexample
11922 @group
11923 @cartouche
11924 @b{package} Definitions @b{is}
11925    @b{generic}
11926       @b{type} m @b{is new} integer;
11927    @b{package} Subp @b{is}
11928       @b{type} a @b{is array} (1 .. 10) @b{of} m;
11929       @b{type} b @b{is array} (1 .. 20) @b{of} m;
11930    @b{end} Subp;
11931 @b{end} Definitions;
11932 @end cartouche
11933 @end group
11934 @end smallexample
11936 @noindent
11937 A package that @code{with}'s @code{Definitions} may safely instantiate
11938 @code{Definitions.Subp} because the compiler can determine that there
11939 definitely is no package body to worry about in this case
11941 @item pragma Pure
11942 @cindex pragma Pure
11943 @findex Pure
11944 Places sufficient restrictions on a unit to guarantee that
11945 no call to any subprogram in the unit can result in an
11946 elaboration problem. This means that the compiler does not need
11947 to worry about the point of elaboration of such units, and in
11948 particular, does not need to check any calls to any subprograms
11949 in this unit.
11951 @item pragma Preelaborate
11952 @findex Preelaborate
11953 @cindex pragma Preelaborate
11954 This pragma places slightly less stringent restrictions on a unit than
11955 does pragma Pure,
11956 but these restrictions are still sufficient to ensure that there
11957 are no elaboration problems with any calls to the unit.
11959 @item pragma Elaborate_Body
11960 @findex Elaborate_Body
11961 @cindex pragma Elaborate_Body
11962 This pragma requires that the body of a unit be elaborated immediately
11963 after its spec. Suppose a unit @code{A} has such a pragma,
11964 and unit @code{B} does
11965 a @code{with} of unit @code{A}. Recall that the standard rules require
11966 the spec of unit @code{A}
11967 to be elaborated before the @code{with}'ing unit; given the pragma in
11968 @code{A}, we also know that the body of @code{A}
11969 will be elaborated before @code{B}, so
11970 that calls to @code{A} are safe and do not need a check.
11971 @end table
11973 @noindent
11974 Note that,
11975 unlike pragma @code{Pure} and pragma @code{Preelaborate},
11976 the use of
11977 @code{Elaborate_Body} does not guarantee that the program is
11978 free of elaboration problems, because it may not be possible
11979 to satisfy the requested elaboration order.
11980 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
11981 If a programmer
11982 marks @code{Unit_1} as @code{Elaborate_Body},
11983 and not @code{Unit_2,} then the order of
11984 elaboration will be:
11986 @smallexample
11987 @group
11988 Spec of Unit_2
11989 Spec of Unit_1
11990 Body of Unit_1
11991 Body of Unit_2
11992 @end group
11993 @end smallexample
11995 @noindent
11996 Now that means that the call to @code{Func_1} in @code{Unit_2}
11997 need not be checked,
11998 it must be safe. But the call to @code{Func_2} in
11999 @code{Unit_1} may still fail if
12000 @code{Expression_1} is equal to 1,
12001 and the programmer must still take
12002 responsibility for this not being the case.
12004 If all units carry a pragma @code{Elaborate_Body}, then all problems are
12005 eliminated, except for calls entirely within a body, which are
12006 in any case fully under programmer control. However, using the pragma
12007 everywhere is not always possible.
12008 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
12009 we marked both of them as having pragma @code{Elaborate_Body}, then
12010 clearly there would be no possible elaboration order.
12012 The above pragmas allow a server to guarantee safe use by clients, and
12013 clearly this is the preferable approach. Consequently a good rule in
12014 Ada 95 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
12015 and if this is not possible,
12016 mark them as @code{Elaborate_Body} if possible.
12017 As we have seen, there are situations where neither of these
12018 three pragmas can be used.
12019 So we also provide methods for clients to control the
12020 order of elaboration of the servers on which they depend:
12022 @table @asis
12023 @item pragma Elaborate (unit)
12024 @findex Elaborate
12025 @cindex pragma Elaborate
12026 This pragma is placed in the context clause, after a @code{with} clause,
12027 and it requires that the body of the named unit be elaborated before
12028 the unit in which the pragma occurs. The idea is to use this pragma
12029 if the current unit calls at elaboration time, directly or indirectly,
12030 some subprogram in the named unit.
12032 @item pragma Elaborate_All (unit)
12033 @findex Elaborate_All
12034 @cindex pragma Elaborate_All
12035 This is a stronger version of the Elaborate pragma. Consider the
12036 following example:
12038 @smallexample
12039 Unit A @code{with}'s unit B and calls B.Func in elab code
12040 Unit B @code{with}'s unit C, and B.Func calls C.Func
12041 @end smallexample
12043 @noindent
12044 Now if we put a pragma @code{Elaborate (B)}
12045 in unit @code{A}, this ensures that the
12046 body of @code{B} is elaborated before the call, but not the
12047 body of @code{C}, so
12048 the call to @code{C.Func} could still cause @code{Program_Error} to
12049 be raised.
12051 The effect of a pragma @code{Elaborate_All} is stronger, it requires
12052 not only that the body of the named unit be elaborated before the
12053 unit doing the @code{with}, but also the bodies of all units that the
12054 named unit uses, following @code{with} links transitively. For example,
12055 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
12056 then it requires
12057 not only that the body of @code{B} be elaborated before @code{A},
12058 but also the
12059 body of @code{C}, because @code{B} @code{with}'s @code{C}.
12060 @end table
12062 @noindent
12063 We are now in a position to give a usage rule in Ada 95 for avoiding
12064 elaboration problems, at least if dynamic dispatching and access to
12065 subprogram values are not used. We will handle these cases separately
12066 later.
12068 The rule is simple. If a unit has elaboration code that can directly or
12069 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
12070 a generic unit in a @code{with}'ed unit,
12071 then if the @code{with}'ed unit does not have
12072 pragma @code{Pure} or @code{Preelaborate}, then the client should have
12073 a pragma @code{Elaborate_All}
12074 for the @code{with}'ed unit. By following this rule a client is
12075 assured that calls can be made without risk of an exception.
12076 If this rule is not followed, then a program may be in one of four
12077 states:
12079 @table @asis
12080 @item No order exists
12081 No order of elaboration exists which follows the rules, taking into
12082 account any @code{Elaborate}, @code{Elaborate_All},
12083 or @code{Elaborate_Body} pragmas. In
12084 this case, an Ada 95 compiler must diagnose the situation at bind
12085 time, and refuse to build an executable program.
12087 @item One or more orders exist, all incorrect
12088 One or more acceptable elaboration orders exists, and all of them
12089 generate an elaboration order problem. In this case, the binder
12090 can build an executable program, but @code{Program_Error} will be raised
12091 when the program is run.
12093 @item Several orders exist, some right, some incorrect
12094 One or more acceptable elaboration orders exists, and some of them
12095 work, and some do not. The programmer has not controlled
12096 the order of elaboration, so the binder may or may not pick one of
12097 the correct orders, and the program may or may not raise an
12098 exception when it is run. This is the worst case, because it means
12099 that the program may fail when moved to another compiler, or even
12100 another version of the same compiler.
12102 @item One or more orders exists, all correct
12103 One ore more acceptable elaboration orders exist, and all of them
12104 work. In this case the program runs successfully. This state of
12105 affairs can be guaranteed by following the rule we gave above, but
12106 may be true even if the rule is not followed.
12107 @end table
12109 @noindent
12110 Note that one additional advantage of following our Elaborate_All rule
12111 is that the program continues to stay in the ideal (all orders OK) state
12112 even if maintenance
12113 changes some bodies of some subprograms. Conversely, if a program that does
12114 not follow this rule happens to be safe at some point, this state of affairs
12115 may deteriorate silently as a result of maintenance changes.
12117 You may have noticed that the above discussion did not mention
12118 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
12119 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
12120 code in the body makes calls to some other unit, so it is still necessary
12121 to use @code{Elaborate_All} on such units.
12123 @node Controlling Elaboration in GNAT - Internal Calls
12124 @section Controlling Elaboration in GNAT - Internal Calls
12126 @noindent
12127 In the case of internal calls, i.e. calls within a single package, the
12128 programmer has full control over the order of elaboration, and it is up
12129 to the programmer to elaborate declarations in an appropriate order. For
12130 example writing:
12132 @smallexample
12133 @group
12134 @cartouche
12135 @b{function} One @b{return} Float;
12137 Q : Float := One;
12139 @b{function} One @b{return} Float @b{is}
12140 @b{begin}
12141      return 1.0;
12142 @b{end} One;
12143 @end cartouche
12144 @end group
12145 @end smallexample
12147 @noindent
12148 will obviously raise @code{Program_Error} at run time, because function
12149 One will be called before its body is elaborated. In this case GNAT will
12150 generate a warning that the call will raise @code{Program_Error}:
12152 @smallexample
12153 @group
12154 @cartouche
12155  1. procedure y is
12156  2.    function One return Float;
12157  3.
12158  4.    Q : Float := One;
12159                     |
12160     >>> warning: cannot call "One" before body is elaborated
12161     >>> warning: Program_Error will be raised at run time
12163  5.
12164  6.    function One return Float is
12165  7.    begin
12166  8.         return 1.0;
12167  9.    end One;
12169 11. begin
12170 12.    null;
12171 13. end;
12172 @end cartouche
12173 @end group
12174 @end smallexample
12176 @noindent
12177 Note that in this particular case, it is likely that the call is safe, because
12178 the function @code{One} does not access any global variables.
12179 Nevertheless in Ada 95, we do not want the validity of the check to depend on
12180 the contents of the body (think about the separate compilation case), so this
12181 is still wrong, as we discussed in the previous sections.
12183 The error is easily corrected by rearranging the declarations so that the
12184 body of One appears before the declaration containing the call
12185 (note that in Ada 95,
12186 declarations can appear in any order, so there is no restriction that
12187 would prevent this reordering, and if we write:
12189 @smallexample
12190 @group
12191 @cartouche
12192 @b{function} One @b{return} Float;
12194 @b{function} One @b{return} Float @b{is}
12195 @b{begin}
12196      return 1.0;
12197 @b{end} One;
12199 Q : Float := One;
12200 @end cartouche
12201 @end group
12202 @end smallexample
12204 @noindent
12205 then all is well, no warning is generated, and no
12206 @code{Program_Error} exception
12207 will be raised.
12208 Things are more complicated when a chain of subprograms is executed:
12210 @smallexample
12211 @group
12212 @cartouche
12213 @b{function} A @b{return} Integer;
12214 @b{function} B @b{return} Integer;
12215 @b{function} C @b{return} Integer;
12217 @b{function} B @b{return} Integer @b{is begin return} A; @b{end};
12218 @b{function} C @b{return} Integer @b{is begin return} B; @b{end};
12220 X : Integer := C;
12222 @b{function} A @b{return} Integer @b{is begin return} 1; @b{end};
12223 @end cartouche
12224 @end group
12225 @end smallexample
12227 @noindent
12228 Now the call to @code{C}
12229 at elaboration time in the declaration of @code{X} is correct, because
12230 the body of @code{C} is already elaborated,
12231 and the call to @code{B} within the body of
12232 @code{C} is correct, but the call
12233 to @code{A} within the body of @code{B} is incorrect, because the body
12234 of @code{A} has not been elaborated, so @code{Program_Error}
12235 will be raised on the call to @code{A}.
12236 In this case GNAT will generate a
12237 warning that @code{Program_Error} may be
12238 raised at the point of the call. Let's look at the warning:
12240 @smallexample
12241 @group
12242 @cartouche
12243  1. procedure x is
12244  2.    function A return Integer;
12245  3.    function B return Integer;
12246  4.    function C return Integer;
12247  5.
12248  6.    function B return Integer is begin return A; end;
12249                                                     |
12250     >>> warning: call to "A" before body is elaborated may
12251                  raise Program_Error
12252     >>> warning: "B" called at line 7
12253     >>> warning: "C" called at line 9
12255  7.    function C return Integer is begin return B; end;
12256  8.
12257  9.    X : Integer := C;
12259 11.    function A return Integer is begin return 1; end;
12261 13. begin
12262 14.    null;
12263 15. end;
12264 @end cartouche
12265 @end group
12266 @end smallexample
12268 @noindent
12269 Note that the message here says "may raise", instead of the direct case,
12270 where the message says "will be raised". That's because whether
12271 @code{A} is
12272 actually called depends in general on run-time flow of control.
12273 For example, if the body of @code{B} said
12275 @smallexample
12276 @group
12277 @cartouche
12278 @b{function} B @b{return} Integer @b{is}
12279 @b{begin}
12280    @b{if} some-condition-depending-on-input-data @b{then}
12281       @b{return} A;
12282    @b{else}
12283       @b{return} 1;
12284    @b{end if};
12285 @b{end} B;
12286 @end cartouche
12287 @end group
12288 @end smallexample
12290 @noindent
12291 then we could not know until run time whether the incorrect call to A would
12292 actually occur, so @code{Program_Error} might
12293 or might not be raised. It is possible for a compiler to
12294 do a better job of analyzing bodies, to
12295 determine whether or not @code{Program_Error}
12296 might be raised, but it certainly
12297 couldn't do a perfect job (that would require solving the halting problem
12298 and is provably impossible), and because this is a warning anyway, it does
12299 not seem worth the effort to do the analysis. Cases in which it
12300 would be relevant are rare.
12302 In practice, warnings of either of the forms given
12303 above will usually correspond to
12304 real errors, and should be examined carefully and eliminated.
12305 In the rare case where a warning is bogus, it can be suppressed by any of
12306 the following methods:
12308 @itemize @bullet
12309 @item
12310 Compile with the @option{-gnatws} switch set
12312 @item
12313 Suppress @code{Elaboration_Checks} for the called subprogram
12315 @item
12316 Use pragma @code{Warnings_Off} to turn warnings off for the call
12317 @end itemize
12319 @noindent
12320 For the internal elaboration check case,
12321 GNAT by default generates the
12322 necessary run-time checks to ensure
12323 that @code{Program_Error} is raised if any
12324 call fails an elaboration check. Of course this can only happen if a
12325 warning has been issued as described above. The use of pragma
12326 @code{Suppress (Elaboration_Checks)} may (but is not guaranteed to) suppress
12327 some of these checks, meaning that it may be possible (but is not
12328 guaranteed) for a program to be able to call a subprogram whose body
12329 is not yet elaborated, without raising a @code{Program_Error} exception.
12331 @node Controlling Elaboration in GNAT - External Calls
12332 @section Controlling Elaboration in GNAT - External Calls
12334 @noindent
12335 The previous section discussed the case in which the execution of a
12336 particular thread of elaboration code occurred entirely within a
12337 single unit. This is the easy case to handle, because a programmer
12338 has direct and total control over the order of elaboration, and
12339 furthermore, checks need only be generated in cases which are rare
12340 and which the compiler can easily detect.
12341 The situation is more complex when separate compilation is taken into account.
12342 Consider the following:
12344 @smallexample
12345 @cartouche
12346 @group
12347 @b{package} Math @b{is}
12348    @b{function} Sqrt (Arg : Float) @b{return} Float;
12349 @b{end} Math;
12351 @b{package body} Math @b{is}
12352    @b{function} Sqrt (Arg : Float) @b{return} Float @b{is}
12353    @b{begin}
12354          ...
12355    @b{end} Sqrt;
12356 @b{end} Math;
12357 @end group
12358 @group
12359 @b{with} Math;
12360 @b{package} Stuff @b{is}
12361    X : Float := Math.Sqrt (0.5);
12362 @b{end} Stuff;
12364 @b{with} Stuff;
12365 @b{procedure} Main @b{is}
12366 @b{begin}
12367    ...
12368 @b{end} Main;
12369 @end group
12370 @end cartouche
12371 @end smallexample
12373 @noindent
12374 where @code{Main} is the main program. When this program is executed, the
12375 elaboration code must first be executed, and one of the jobs of the
12376 binder is to determine the order in which the units of a program are
12377 to be elaborated. In this case we have four units: the spec and body
12378 of @code{Math},
12379 the spec of @code{Stuff} and the body of @code{Main}).
12380 In what order should the four separate sections of elaboration code
12381 be executed?
12383 There are some restrictions in the order of elaboration that the binder
12384 can choose. In particular, if unit U has a @code{with}
12385 for a package @code{X}, then you
12386 are assured that the spec of @code{X}
12387 is elaborated before U , but you are
12388 not assured that the body of @code{X}
12389 is elaborated before U.
12390 This means that in the above case, the binder is allowed to choose the
12391 order:
12393 @smallexample
12394 spec of Math
12395 spec of Stuff
12396 body of Math
12397 body of Main
12398 @end smallexample
12400 @noindent
12401 but that's not good, because now the call to @code{Math.Sqrt}
12402 that happens during
12403 the elaboration of the @code{Stuff}
12404 spec happens before the body of @code{Math.Sqrt} is
12405 elaborated, and hence causes @code{Program_Error} exception to be raised.
12406 At first glance, one might say that the binder is misbehaving, because
12407 obviously you want to elaborate the body of something you @code{with}
12408 first, but
12409 that is not a general rule that can be followed in all cases. Consider
12411 @smallexample
12412 @group
12413 @cartouche
12414 @b{package} X @b{is} ...
12416 @b{package} Y @b{is} ...
12418 @b{with} X;
12419 @b{package body} Y @b{is} ...
12421 @b{with} Y;
12422 @b{package body} X @b{is} ...
12423 @end cartouche
12424 @end group
12425 @end smallexample
12427 @noindent
12428 This is a common arrangement, and, apart from the order of elaboration
12429 problems that might arise in connection with elaboration code, this works fine.
12430 A rule that says that you must first elaborate the body of anything you
12431 @code{with} cannot work in this case:
12432 the body of @code{X} @code{with}'s @code{Y},
12433 which means you would have to
12434 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
12435 which means
12436 you have to elaborate the body of @code{X} first, but ... and we have a
12437 loop that cannot be broken.
12439 It is true that the binder can in many cases guess an order of elaboration
12440 that is unlikely to cause a @code{Program_Error}
12441 exception to be raised, and it tries to do so (in the
12442 above example of @code{Math/Stuff/Spec}, the GNAT binder will
12443 by default
12444 elaborate the body of @code{Math} right after its spec, so all will be well).
12446 However, a program that blindly relies on the binder to be helpful can
12447 get into trouble, as we discussed in the previous sections, so
12448 GNAT
12449 provides a number of facilities for assisting the programmer in
12450 developing programs that are robust with respect to elaboration order.
12452 @node Default Behavior in GNAT - Ensuring Safety
12453 @section Default Behavior in GNAT - Ensuring Safety
12455 @noindent
12456 The default behavior in GNAT ensures elaboration safety. In its
12457 default mode GNAT implements the
12458 rule we previously described as the right approach. Let's restate it:
12460 @itemize
12461 @item
12462 @emph{If a unit has elaboration code that can directly or indirectly make a
12463 call to a subprogram in a @code{with}'ed unit, or instantiate a generic unit
12464 in a @code{with}'ed unit, then if the @code{with}'ed unit
12465 does not have pragma @code{Pure} or
12466 @code{Preelaborate}, then the client should have an
12467 @code{Elaborate_All} for the @code{with}'ed unit.}
12468 @end itemize
12470 @noindent
12471 By following this rule a client
12472 is assured that calls and instantiations can be made without risk of an exception.
12474 In this mode GNAT traces all calls that are potentially made from
12475 elaboration code, and puts in any missing implicit @code{Elaborate_All}
12476 pragmas.
12477 The advantage of this approach is that no elaboration problems
12478 are possible if the binder can find an elaboration order that is
12479 consistent with these implicit @code{Elaborate_All} pragmas. The
12480 disadvantage of this approach is that no such order may exist.
12482 If the binder does not generate any diagnostics, then it means that it
12483 has found an elaboration order that is guaranteed to be safe. However,
12484 the binder may still be relying on implicitly generated
12485 @code{Elaborate_All} pragmas so portability to other compilers than
12486 GNAT is not guaranteed.
12488 If it is important to guarantee portability, then the compilations should
12489 use the
12490 @option{-gnatwl}
12491 (warn on elaboration problems) switch. This will cause warning messages
12492 to be generated indicating the missing @code{Elaborate_All} pragmas.
12493 Consider the following source program:
12495 @smallexample
12496 @group
12497 @cartouche
12498 @b{with} k;
12499 @b{package} j @b{is}
12500   m : integer := k.r;
12501 @b{end};
12502 @end cartouche
12503 @end group
12504 @end smallexample
12506 @noindent
12507 where it is clear that there
12508 should be a pragma @code{Elaborate_All}
12509 for unit @code{k}. An implicit pragma will be generated, and it is
12510 likely that the binder will be able to honor it. However,
12511 it is safer to include the pragma explicitly in the source. If this
12512 unit is compiled with the
12513 @option{-gnatwl}
12514 switch, then the compiler outputs a warning:
12516 @smallexample
12517 @group
12518 @cartouche
12519 1. with k;
12520 2. package j is
12521 3.   m : integer := k.r;
12522                      |
12523    >>> warning: call to "r" may raise Program_Error
12524    >>> warning: missing pragma Elaborate_All for "k"
12526 4. end;
12527 @end cartouche
12528 @end group
12529 @end smallexample
12531 @noindent
12532 and these warnings can be used as a guide for supplying manually
12533 the missing pragmas.
12535 This default mode is more restrictive than the Ada Reference
12536 Manual, and it is possible to construct programs which will compile
12537 using the dynamic model described there, but will run into a
12538 circularity using the safer static model we have described.
12540 Of course any Ada compiler must be able to operate in a mode
12541 consistent with the requirements of the Ada Reference Manual,
12542 and in particular must have the capability of implementing the
12543 standard dynamic model of elaboration with run-time checks.
12545 In GNAT, this standard mode can be achieved either by the use of
12546 the @option{-gnatE} switch on the compiler (@code{gcc} or @code{gnatmake})
12547 command, or by the use of the configuration pragma:
12549 @smallexample
12550 pragma Elaboration_Checks (RM);
12551 @end smallexample
12553 @noindent
12554 Either approach will cause the unit affected to be compiled using the
12555 standard dynamic run-time elaboration checks described in the Ada
12556 Reference Manual. The static model is generally preferable, since it
12557 is clearly safer to rely on compile and link time checks rather than
12558 run-time checks. However, in the case of legacy code, it may be
12559 difficult to meet the requirements of the static model. This
12560 issue is further discussed in
12561 @ref{What to Do If the Default Elaboration Behavior Fails}.
12563 Note that the static model provides a strict subset of the allowed
12564 behavior and programs of the Ada Reference Manual, so if you do
12565 adhere to the static model and no circularities exist,
12566 then you are assured that your program will
12567 work using the dynamic model.
12569 @node Elaboration Issues for Library Tasks
12570 @section Elaboration Issues for Library Tasks
12571 @cindex Library tasks, elaboration issues
12572 @cindex Elaboration of library tasks
12574 @noindent
12575 In this section we examine special elaboration issues that arise for
12576 programs that declare library level tasks.
12578 Generally the model of execution of an Ada program is that all units are
12579 elaborated, and then execution of the program starts. However, the
12580 declaration of library tasks definitely does not fit this model. The
12581 reason for this is that library tasks start as soon as they are declared
12582 (more precisely, as soon as the statement part of the enclosing package
12583 body is reached), that is to say before elaboration
12584 of the program is complete. This means that if such a task calls a
12585 subprogram, or an entry in another task, the callee may or may not be
12586 elaborated yet, and in the standard
12587 Reference Manual model of dynamic elaboration checks, you can even
12588 get timing dependent Program_Error exceptions, since there can be
12589 a race between the elaboration code and the task code.
12591 The static model of elaboration in GNAT seeks to avoid all such
12592 dynamic behavior, by being conservative, and the conservative
12593 approach in this particular case is to assume that all the code
12594 in a task body is potentially executed at elaboration time if
12595 a task is declared at the library level.
12597 This can definitely result in unexpected circularities. Consider
12598 the following example
12600 @smallexample
12601 package Decls is
12602   task Lib_Task is
12603      entry Start;
12604   end Lib_Task;
12606   type My_Int is new Integer;
12608   function Ident (M : My_Int) return My_Int;
12609 end Decls;
12611 with Utils;
12612 package body Decls is
12613   task body Lib_Task is
12614   begin
12615      accept Start;
12616      Utils.Put_Val (2);
12617   end Lib_Task;
12619   function Ident (M : My_Int) return My_Int is
12620   begin
12621      return M;
12622   end Ident;
12623 end Decls;
12625 with Decls;
12626 package Utils is
12627   procedure Put_Val (Arg : Decls.My_Int);
12628 end Utils;
12630 with Text_IO;
12631 package body Utils is
12632   procedure Put_Val (Arg : Decls.My_Int) is
12633   begin
12634      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12635   end Put_Val;
12636 end Utils;
12638 with Decls;
12639 procedure Main is
12640 begin
12641    Decls.Lib_Task.Start;
12642 end;
12643 @end smallexample
12645 @noindent
12646 If the above example is compiled in the default static elaboration
12647 mode, then a circularity occurs. The circularity comes from the call
12648 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
12649 this call occurs in elaboration code, we need an implicit pragma
12650 @code{Elaborate_All} for @code{Utils}. This means that not only must
12651 the spec and body of @code{Utils} be elaborated before the body
12652 of @code{Decls}, but also the spec and body of any unit that is
12653 @code{with'ed} by the body of @code{Utils} must also be elaborated before
12654 the body of @code{Decls}. This is the transitive implication of
12655 pragma @code{Elaborate_All} and it makes sense, because in general
12656 the body of @code{Put_Val} might have a call to something in a
12657 @code{with'ed} unit.
12659 In this case, the body of Utils (actually its spec) @code{with's}
12660 @code{Decls}. Unfortunately this means that the body of @code{Decls}
12661 must be elaborated before itself, in case there is a call from the
12662 body of @code{Utils}.
12664 Here is the exact chain of events we are worrying about:
12666 @enumerate
12667 @item
12668 In the body of @code{Decls} a call is made from within the body of a library
12669 task to a subprogram in the package @code{Utils}. Since this call may
12670 occur at elaboration time (given that the task is activated at elaboration
12671 time), we have to assume the worst, i.e. that the
12672 call does happen at elaboration time.
12674 @item
12675 This means that the body and spec of @code{Util} must be elaborated before
12676 the body of @code{Decls} so that this call does not cause an access before
12677 elaboration.
12679 @item
12680 Within the body of @code{Util}, specifically within the body of
12681 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
12682 by this package.
12684 @item
12685 One such @code{with}'ed package is package @code{Decls}, so there
12686 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
12687 In fact there is such a call in this example, but we would have to
12688 assume that there was such a call even if it were not there, since
12689 we are not supposed to write the body of @code{Decls} knowing what
12690 is in the body of @code{Utils}; certainly in the case of the
12691 static elaboration model, the compiler does not know what is in
12692 other bodies and must assume the worst.
12694 @item
12695 This means that the spec and body of @code{Decls} must also be
12696 elaborated before we elaborate the unit containing the call, but
12697 that unit is @code{Decls}! This means that the body of @code{Decls}
12698 must be elaborated before itself, and that's a circularity.
12699 @end enumerate
12701 @noindent
12702 Indeed, if you add an explicit pragma Elaborate_All for @code{Utils} in
12703 the body of @code{Decls} you will get a true Ada Reference Manual
12704 circularity that makes the program illegal.
12706 In practice, we have found that problems with the static model of
12707 elaboration in existing code often arise from library tasks, so
12708 we must address this particular situation.
12710 Note that if we compile and run the program above, using the dynamic model of
12711 elaboration (that is to say use the @option{-gnatE} switch),
12712 then it compiles, binds,
12713 links, and runs, printing the expected result of 2. Therefore in some sense
12714 the circularity here is only apparent, and we need to capture
12715 the properties of this program that  distinguish it from other library-level
12716 tasks that have real elaboration problems.
12718 We have four possible answers to this question:
12720 @itemize @bullet
12722 @item
12723 Use the dynamic model of elaboration.
12725 If we use the @option{-gnatE} switch, then as noted above, the program works.
12726 Why is this? If we examine the task body, it is apparent that the task cannot
12727 proceed past the
12728 @code{accept} statement until after elaboration has been completed, because
12729 the corresponding entry call comes from the main program, not earlier.
12730 This is why the dynamic model works here. But that's really giving
12731 up on a precise analysis, and we prefer to take this approach only if we cannot
12732 solve the
12733 problem in any other manner. So let us examine two ways to reorganize
12734 the program to avoid the potential elaboration problem.
12736 @item
12737 Split library tasks into separate packages.
12739 Write separate packages, so that library tasks are isolated from
12740 other declarations as much as possible. Let us look at a variation on
12741 the above program.
12743 @smallexample
12744 package Decls1 is
12745   task Lib_Task is
12746      entry Start;
12747   end Lib_Task;
12748 end Decls1;
12750 with Utils;
12751 package body Decls1 is
12752   task body Lib_Task is
12753   begin
12754      accept Start;
12755      Utils.Put_Val (2);
12756   end Lib_Task;
12757 end Decls1;
12759 package Decls2 is
12760   type My_Int is new Integer;
12761   function Ident (M : My_Int) return My_Int;
12762 end Decls2;
12764 with Utils;
12765 package body Decls2 is
12766   function Ident (M : My_Int) return My_Int is
12767   begin
12768      return M;
12769   end Ident;
12770 end Decls2;
12772 with Decls2;
12773 package Utils is
12774   procedure Put_Val (Arg : Decls2.My_Int);
12775 end Utils;
12777 with Text_IO;
12778 package body Utils is
12779   procedure Put_Val (Arg : Decls2.My_Int) is
12780   begin
12781      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
12782   end Put_Val;
12783 end Utils;
12785 with Decls1;
12786 procedure Main is
12787 begin
12788    Decls1.Lib_Task.Start;
12789 end;
12790 @end smallexample
12792 @noindent
12793 All we have done is to split @code{Decls} into two packages, one
12794 containing the library task, and one containing everything else. Now
12795 there is no cycle, and the program compiles, binds, links and executes
12796 using the default static model of elaboration.
12798 @item
12799 Declare separate task types.
12801 A significant part of the problem arises because of the use of the
12802 single task declaration form. This means that the elaboration of
12803 the task type, and the elaboration of the task itself (i.e. the
12804 creation of the task) happen at the same time. A good rule
12805 of style in Ada 95 is to always create explicit task types. By
12806 following the additional step of placing task objects in separate
12807 packages from the task type declaration, many elaboration problems
12808 are avoided. Here is another modified example of the example program:
12810 @smallexample
12811 package Decls is
12812   task type Lib_Task_Type is
12813      entry Start;
12814   end Lib_Task_Type;
12816   type My_Int is new Integer;
12818   function Ident (M : My_Int) return My_Int;
12819 end Decls;
12821 with Utils;
12822 package body Decls is
12823   task body Lib_Task_Type is
12824   begin
12825      accept Start;
12826      Utils.Put_Val (2);
12827   end Lib_Task_Type;
12829   function Ident (M : My_Int) return My_Int is
12830   begin
12831      return M;
12832   end Ident;
12833 end Decls;
12835 with Decls;
12836 package Utils is
12837   procedure Put_Val (Arg : Decls.My_Int);
12838 end Utils;
12840 with Text_IO;
12841 package body Utils is
12842   procedure Put_Val (Arg : Decls.My_Int) is
12843   begin
12844      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
12845   end Put_Val;
12846 end Utils;
12848 with Decls;
12849 package Declst is
12850    Lib_Task : Decls.Lib_Task_Type;
12851 end Declst;
12853 with Declst;
12854 procedure Main is
12855 begin
12856    Declst.Lib_Task.Start;
12857 end;
12858 @end smallexample
12860 @noindent
12861 What we have done here is to replace the @code{task} declaration in
12862 package @code{Decls} with a @code{task type} declaration. Then we
12863 introduce a separate package @code{Declst} to contain the actual
12864 task object. This separates the elaboration issues for
12865 the @code{task type}
12866 declaration, which causes no trouble, from the elaboration issues
12867 of the task object, which is also unproblematic, since it is now independent
12868 of the elaboration of  @code{Utils}.
12869 This separation of concerns also corresponds to
12870 a generally sound engineering principle of separating declarations
12871 from instances. This version of the program also compiles, binds, links,
12872 and executes, generating the expected output.
12874 @item
12875 Use No_Entry_Calls_In_Elaboration_Code restriction.
12876 @cindex No_Entry_Calls_In_Elaboration_Code
12878 The previous two approaches described how a program can be restructured
12879 to avoid the special problems caused by library task bodies. in practice,
12880 however, such restructuring may be difficult to apply to existing legacy code,
12881 so we must consider solutions that do not require massive rewriting.
12883 Let us consider more carefully why our original sample program works
12884 under the dynamic model of elaboration. The reason is that the code
12885 in the task body blocks immediately on the @code{accept}
12886 statement. Now of course there is nothing to prohibit elaboration
12887 code from making entry calls (for example from another library level task),
12888 so we cannot tell in isolation that
12889 the task will not execute the accept statement  during elaboration.
12891 However, in practice it is very unusual to see elaboration code
12892 make any entry calls, and the pattern of tasks starting
12893 at elaboration time and then immediately blocking on @code{accept} or
12894 @code{select} statements is very common. What this means is that
12895 the compiler is being too pessimistic when it analyzes the
12896 whole package body as though it might be executed at elaboration
12897 time.
12899 If we know that the elaboration code contains no entry calls, (a very safe
12900 assumption most of the time, that could almost be made the default
12901 behavior), then we can compile all units of the program under control
12902 of the following configuration pragma:
12904 @smallexample
12905 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
12906 @end smallexample
12908 @noindent
12909 This pragma can be placed in the @file{gnat.adc} file in the usual
12910 manner. If we take our original unmodified program and compile it
12911 in the presence of a @file{gnat.adc} containing the above pragma,
12912 then once again, we can compile, bind, link, and execute, obtaining
12913 the expected result. In the presence of this pragma, the compiler does
12914 not trace calls in a task body, that appear after the first @code{accept}
12915 or @code{select} statement, and therefore does not report a potential
12916 circularity in the original program.
12918 The compiler will check to the extent it can that the above
12919 restriction is not violated, but it is not always possible to do a
12920 complete check at compile time, so it is important to use this
12921 pragma only if the stated restriction is in fact met, that is to say
12922 no task receives an entry call before elaboration of all units is completed.
12924 @end itemize
12926 @node Mixing Elaboration Models
12927 @section Mixing Elaboration Models
12928 @noindent
12929 So far, we have assumed that the entire program is either compiled
12930 using the dynamic model or static model, ensuring consistency. It
12931 is possible to mix the two models, but rules have to be followed
12932 if this mixing is done to ensure that elaboration checks are not
12933 omitted.
12935 The basic rule is that @emph{a unit compiled with the static model cannot
12936 be @code{with'ed} by a unit compiled with the dynamic model}. The
12937 reason for this is that in the static model, a unit assumes that
12938 its clients guarantee to use (the equivalent of) pragma
12939 @code{Elaborate_All} so that no elaboration checks are required
12940 in inner subprograms, and this assumption is violated if the
12941 client is compiled with dynamic checks.
12943 The precise rule is as follows. A unit that is compiled with dynamic
12944 checks can only @code{with} a unit that meets at least one of the
12945 following criteria:
12947 @itemize @bullet
12949 @item
12950 The @code{with'ed} unit is itself compiled with dynamic elaboration
12951 checks (that is with the @option{-gnatE} switch.
12953 @item
12954 The @code{with'ed} unit is an internal GNAT implementation unit from
12955 the System, Interfaces, Ada, or GNAT hierarchies.
12957 @item
12958 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
12960 @item
12961 The @code{with'ing} unit (that is the client) has an explicit pragma
12962 @code{Elaborate_All} for the @code{with'ed} unit.
12964 @end itemize
12966 @noindent
12967 If this rule is violated, that is if a unit with dynamic elaboration
12968 checks @code{with's} a unit that does not meet one of the above four
12969 criteria, then the binder (@code{gnatbind}) will issue a warning
12970 similar to that in the following example:
12972 @smallexample
12973 warning: "x.ads" has dynamic elaboration checks and with's
12974 warning:   "y.ads" which has static elaboration checks
12975 @end smallexample
12977 @noindent
12978 These warnings indicate that the rule has been violated, and that as a result
12979 elaboration checks may be missed in the resulting executable file.
12980 This warning may be suppressed using the @code{-ws} binder switch
12981 in the usual manner.
12983 One useful application of this mixing rule is in the case of a subsystem
12984 which does not itself @code{with} units from the remainder of the
12985 application. In this case, the entire subsystem can be compiled with
12986 dynamic checks to resolve a circularity in the subsystem, while
12987 allowing the main application that uses this subsystem to be compiled
12988 using the more reliable default static model.
12990 @node What to Do If the Default Elaboration Behavior Fails
12991 @section What to Do If the Default Elaboration Behavior Fails
12993 @noindent
12994 If the binder cannot find an acceptable order, it outputs detailed
12995 diagnostics. For example:
12996 @smallexample
12997 @group
12998 @iftex
12999 @leftskip=0cm
13000 @end iftex
13001 error: elaboration circularity detected
13002 info:   "proc (body)" must be elaborated before "pack (body)"
13003 info:     reason: Elaborate_All probably needed in unit "pack (body)"
13004 info:     recompile "pack (body)" with -gnatwl
13005 info:                             for full details
13006 info:       "proc (body)"
13007 info:         is needed by its spec:
13008 info:       "proc (spec)"
13009 info:         which is withed by:
13010 info:       "pack (body)"
13011 info:  "pack (body)" must be elaborated before "proc (body)"
13012 info:     reason: pragma Elaborate in unit "proc (body)"
13013 @end group
13015 @end smallexample
13017 @noindent
13018 In this case we have a cycle that the binder cannot break. On the one
13019 hand, there is an explicit pragma Elaborate in @code{proc} for
13020 @code{pack}. This means that the body of @code{pack} must be elaborated
13021 before the body of @code{proc}. On the other hand, there is elaboration
13022 code in @code{pack} that calls a subprogram in @code{proc}. This means
13023 that for maximum safety, there should really be a pragma
13024 Elaborate_All in @code{pack} for @code{proc} which would require that
13025 the body of @code{proc} be elaborated before the body of
13026 @code{pack}. Clearly both requirements cannot be satisfied.
13027 Faced with a circularity of this kind, you have three different options.
13029 @table @asis
13030 @item Fix the program
13031 The most desirable option from the point of view of long-term maintenance
13032 is to rearrange the program so that the elaboration problems are avoided.
13033 One useful technique is to place the elaboration code into separate
13034 child packages. Another is to move some of the initialization code to
13035 explicitly called subprograms, where the program controls the order
13036 of initialization explicitly. Although this is the most desirable option,
13037 it may be impractical and involve too much modification, especially in
13038 the case of complex legacy code.
13040 @item Perform dynamic checks
13041 If the compilations are done using the
13042 @option{-gnatE}
13043 (dynamic elaboration check) switch, then GNAT behaves in
13044 a quite different manner. Dynamic checks are generated for all calls
13045 that could possibly result in raising an exception. With this switch,
13046 the compiler does not generate implicit @code{Elaborate_All} pragmas.
13047 The behavior then is exactly as specified in the Ada 95 Reference Manual.
13048 The binder will generate an executable program that may or may not
13049 raise @code{Program_Error}, and then it is the programmer's job to ensure
13050 that it does not raise an exception. Note that it is important to
13051 compile all units with the switch, it cannot be used selectively.
13053 @item Suppress checks
13054 The drawback of dynamic checks is that they generate a
13055 significant overhead at run time, both in space and time. If you
13056 are absolutely sure that your program cannot raise any elaboration
13057 exceptions, and you still want to use the dynamic elaboration model,
13058 then you can use the configuration pragma
13059 @code{Suppress (Elaboration_Checks)} to suppress all such checks. For
13060 example this pragma could be placed in the @file{gnat.adc} file.
13062 @item Suppress checks selectively
13063 When you know that certain calls in elaboration code cannot possibly
13064 lead to an elaboration error, and the binder nevertheless generates warnings
13065 on those calls and inserts Elaborate_All pragmas that lead to elaboration
13066 circularities, it is possible to remove those warnings locally and obtain
13067 a program that will bind. Clearly this can be unsafe, and it is the
13068 responsibility of the programmer to make sure that the resulting program has
13069 no elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can
13070 be used with different granularity to suppress warnings and break
13071 elaboration circularities:
13073 @itemize @bullet
13074 @item
13075 Place the pragma that names the called subprogram in the declarative part
13076 that contains the call.
13078 @item
13079 Place the pragma in the declarative part, without naming an entity. This
13080 disables warnings on all calls in the corresponding  declarative region.
13082 @item
13083 Place the pragma in the package spec that declares the called subprogram,
13084 and name the subprogram. This disables warnings on all elaboration calls to
13085 that subprogram.
13087 @item
13088 Place the pragma in the package spec that declares the called subprogram,
13089 without naming any entity. This disables warnings on all elaboration calls to
13090 all subprograms declared in this spec.
13091 @end itemize
13093 @noindent
13094 These four cases are listed in order of decreasing safety, and therefore
13095 require increasing programmer care in their application. Consider the
13096 following program:
13097 @smallexample
13099 package Pack1 is
13100   function F1 return Integer;
13101   X1 : Integer;
13102 end Pack1;
13104 package Pack2 is
13105   function F2 return Integer;
13106   function Pure (x : integer) return integer;
13107   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
13108   --  pragma Suppress (Elaboration_Check);              -- (4)
13109 end Pack2;
13111 with Pack2;
13112 package body Pack1 is
13113   function F1 return Integer is
13114   begin
13115     return 100;
13116   end F1;
13117   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
13118 begin
13119   declare
13120     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
13121     --  pragma Suppress(Elaboration_Check);             -- (2)
13122   begin
13123     X1 := Pack2.F2 + 1;                --  Elab. call (2)
13124   end;
13125 end Pack1;
13127 with Pack1;
13128 package body Pack2 is
13129   function F2 return Integer is
13130   begin
13131      return Pack1.F1;
13132   end F2;
13133   function Pure (x : integer) return integer is
13134   begin
13135      return x ** 3 - 3 * x;
13136   end;
13137 end Pack2;
13139 with Pack1, Ada.Text_IO;
13140 procedure Proc3 is
13141 begin
13142   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
13143 end Proc3;
13144 @end smallexample
13145 In the absence of any pragmas, an attempt to bind this program produces
13146 the following diagnostics:
13147 @smallexample
13148 @group
13149 @iftex
13150 @leftskip=.5cm
13151 @end iftex
13152 error: elaboration circularity detected
13153 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
13154 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
13155 info:       recompile "pack1 (body)" with -gnatwl for full details
13156 info:          "pack1 (body)"
13157 info:             must be elaborated along with its spec:
13158 info:          "pack1 (spec)"
13159 info:             which is withed by:
13160 info:          "pack2 (body)"
13161 info:             which must be elaborated along with its spec:
13162 info:          "pack2 (spec)"
13163 info:             which is withed by:
13164 info:          "pack1 (body)"
13165 @end group
13166 @end smallexample
13167 The sources of the circularity are the two calls to @code{Pack2.Pure} and
13168 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
13169 F2 is safe, even though F2 calls F1, because the call appears after the
13170 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
13171 remove the warning on the call. It is also possible to use pragma (2)
13172 because there are no other potentially unsafe calls in the block.
13174 @noindent
13175 The call to @code{Pure} is safe because this function does not depend on the
13176 state of @code{Pack2}. Therefore any call to this function is safe, and it
13177 is correct to place pragma (3) in the corresponding package spec.
13179 @noindent
13180 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
13181 warnings on all calls to functions declared therein. Note that this is not
13182 necessarily safe, and requires more detailed examination of the subprogram
13183 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
13184 be already elaborated.
13185 @end table
13187 @noindent
13188 It is hard to generalize on which of these four approaches should be
13189 taken. Obviously if it is possible to fix the program so that the default
13190 treatment works, this is preferable, but this may not always be practical.
13191 It is certainly simple enough to use
13192 @option{-gnatE}
13193 but the danger in this case is that, even if the GNAT binder
13194 finds a correct elaboration order, it may not always do so,
13195 and certainly a binder from another Ada compiler might not. A
13196 combination of testing and analysis (for which the warnings generated
13197 with the
13198 @option{-gnatwl}
13199 switch can be useful) must be used to ensure that the program is free
13200 of errors. One switch that is useful in this testing is the
13201 @code{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
13202 switch for
13203 @code{gnatbind}.
13204 Normally the binder tries to find an order that has the best chance of
13205 of avoiding elaboration problems. With this switch, the binder
13206 plays a devil's advocate role, and tries to choose the order that
13207 has the best chance of failing. If your program works even with this
13208 switch, then it has a better chance of being error free, but this is still
13209 not a guarantee.
13211 For an example of this approach in action, consider the C-tests (executable
13212 tests) from the ACVC suite. If these are compiled and run with the default
13213 treatment, then all but one of them succeed without generating any error
13214 diagnostics from the binder. However, there is one test that fails, and
13215 this is not surprising, because the whole point of this test is to ensure
13216 that the compiler can handle cases where it is impossible to determine
13217 a correct order statically, and it checks that an exception is indeed
13218 raised at run time.
13220 This one test must be compiled and run using the
13221 @option{-gnatE}
13222 switch, and then it passes. Alternatively, the entire suite can
13223 be run using this switch. It is never wrong to run with the dynamic
13224 elaboration switch if your code is correct, and we assume that the
13225 C-tests are indeed correct (it is less efficient, but efficiency is
13226 not a factor in running the ACVC tests.)
13228 @node Elaboration for Access-to-Subprogram Values
13229 @section Elaboration for Access-to-Subprogram Values
13230 @cindex Access-to-subprogram
13232 @noindent
13233 The introduction of access-to-subprogram types in Ada 95 complicates
13234 the handling of elaboration. The trouble is that it becomes
13235 impossible to tell at compile time which procedure
13236 is being called. This means that it is not possible for the binder
13237 to analyze the elaboration requirements in this case.
13239 If at the point at which the access value is created
13240 (i.e., the evaluation of @code{P'Access} for a subprogram @code{P}),
13241 the body of the subprogram is
13242 known to have been elaborated, then the access value is safe, and its use
13243 does not require a check. This may be achieved by appropriate arrangement
13244 of the order of declarations if the subprogram is in the current unit,
13245 or, if the subprogram is in another unit, by using pragma
13246 @code{Pure}, @code{Preelaborate}, or @code{Elaborate_Body}
13247 on the referenced unit.
13249 If the referenced body is not known to have been elaborated at the point
13250 the access value is created, then any use of the access value must do a
13251 dynamic check, and this dynamic check will fail and raise a
13252 @code{Program_Error} exception if the body has not been elaborated yet.
13253 GNAT will generate the necessary checks, and in addition, if the
13254 @option{-gnatwl}
13255 switch is set, will generate warnings that such checks are required.
13257 The use of dynamic dispatching for tagged types similarly generates
13258 a requirement for dynamic checks, and premature calls to any primitive
13259 operation of a tagged type before the body of the operation has been elaborated,
13260 will result in the raising of @code{Program_Error}.
13262 @node Summary of Procedures for Elaboration Control
13263 @section Summary of Procedures for Elaboration Control
13264 @cindex Elaboration control
13266 @noindent
13267 First, compile your program with the default options, using none of
13268 the special elaboration control switches. If the binder successfully
13269 binds your program, then you can be confident that, apart from issues
13270 raised by the use of access-to-subprogram types and dynamic dispatching,
13271 the program is free of elaboration errors. If it is important that the
13272 program be portable, then use the
13273 @option{-gnatwl}
13274 switch to generate warnings about missing @code{Elaborate_All}
13275 pragmas, and supply the missing pragmas.
13277 If the program fails to bind using the default static elaboration
13278 handling, then you can fix the program to eliminate the binder
13279 message, or recompile the entire program with the
13280 @option{-gnatE} switch to generate dynamic elaboration checks,
13281 and, if you are sure there really are no elaboration problems,
13282 use a global pragma @code{Suppress (Elaboration_Checks)}.
13284 @node Other Elaboration Order Considerations
13285 @section Other Elaboration Order Considerations
13286 @noindent
13287 This section has been entirely concerned with the issue of finding a valid
13288 elaboration order, as defined by the Ada Reference Manual. In a case
13289 where several elaboration orders are valid, the task is to find one
13290 of the possible valid elaboration orders (and the static model in GNAT
13291 will ensure that this is achieved).
13293 The purpose of the elaboration rules in the Ada Reference Manual is to
13294 make sure that no entity is accessed before it has been elaborated. For
13295 a subprogram, this means that the spec and body must have been elaborated
13296 before the subprogram is called. For an object, this means that the object
13297 must have been elaborated before its value is read or written. A violation
13298 of either of these two requirements is an access before elaboration order,
13299 and this section has been all about avoiding such errors.
13301 In the case where more than one order of elaboration is possible, in the
13302 sense that access before elaboration errors are avoided, then any one of
13303 the orders is "correct" in the sense that it meets the requirements of
13304 the Ada Reference Manual, and no such error occurs.
13306 However, it may be the case for a given program, that there are
13307 constraints on the order of elaboration that come not from consideration
13308 of avoiding elaboration errors, but rather from extra-lingual logic
13309 requirements. Consider this example:
13311 @smallexample
13312 with Init_Constants;
13313 package Constants is
13314    X : Integer := 0;
13315    Y : Integer := 0;
13316 end Constants;
13318 package Init_Constants is
13319    procedure Calc;
13320 end Init_Constants;
13322 with Constants;
13323 package body Init_Constants is
13324    procedure Calc is begin null; end;
13325 begin
13326    Constants.X := 3;
13327    Constants.Y := 4;
13328 end Init_Constants;
13330 with Constants;
13331 package Calc is
13332    Z : Integer := Constants.X + Constants.Y;
13333 end Calc;
13335 with Calc;
13336 with Text_IO; use Text_IO;
13337 procedure Main is
13338 begin
13339    Put_Line (Calc.Z'Img);
13340 end Main;
13341 @end smallexample
13343 @noindent
13344 In this example, there is more than one valid order of elaboration. For
13345 example both the following are correct orders:
13347 @smallexample
13348 Init_Constants spec
13349 Constants spec
13350 Calc spec
13351 Main body
13352 Init_Constants body
13354   and
13356 Init_Constants spec
13357 Init_Constants body
13358 Constants spec
13359 Calc spec
13360 Main body
13361 @end smallexample
13363 @noindent
13364 There is no language rule to prefer one or the other, both are correct
13365 from an order of elaboration point of view. But the programmatic effects
13366 of the two orders are very different. In the first, the elaboration routine
13367 of @code{Calc} initializes @code{Z} to zero, and then the main program
13368 runs with this value of zero. But in the second order, the elaboration
13369 routine of @code{Calc} runs after the body of Init_Constants has set
13370 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
13371 runs.
13373 One could perhaps by applying pretty clever non-artificial intelligence
13374 to the situation guess that it is more likely that the second order of
13375 elaboration is the one desired, but there is no formal linguistic reason
13376 to prefer one over the other. In fact in this particular case, GNAT will
13377 prefer the second order, because of the rule that bodies are elaborated
13378 as soon as possible, but it's just luck that this is what was wanted
13379 (if indeed the second order was preferred).
13381 If the program cares about the order of elaboration routines in a case like
13382 this, it is important to specify the order required. In this particular
13383 case, that could have been achieved by adding to the spec of Calc:
13385 @smallexample
13386 pragma Elaborate_All (Constants);
13387 @end smallexample
13389 @noindent
13390 which requires that the body (if any) and spec of @code{Constants},
13391 as well as the body and spec of any unit @code{with}'ed by
13392 @code{Constants} be elaborated before @code{Calc} is elaborated.
13394 Clearly no automatic method can always guess which alternative you require,
13395 and if you are working with legacy code that had constraints of this kind
13396 which were not properly specified by adding @code{Elaborate} or
13397 @code{Elaborate_All} pragmas, then indeed it is possible that two different
13398 compilers can choose different orders.
13400 The @code{gnatbind}
13401 @code{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
13402 out problems. This switch causes bodies to be elaborated as late as possible
13403 instead of as early as possible. In the example above, it would have forced
13404 the choice of the first elaboration order. If you get different results
13405 when using this switch, and particularly if one set of results is right,
13406 and one is wrong as far as you are concerned, it shows that you have some
13407 missing @code{Elaborate} pragmas. For the example above, we have the
13408 following output:
13410 @smallexample
13411 gnatmake -f -q main
13412 main
13414 gnatmake -f -q main -bargs -p
13415 main
13417 @end smallexample
13419 @noindent
13420 It is of course quite unlikely that both these results are correct, so
13421 it is up to you in a case like this to investigate the source of the
13422 difference, by looking at the two elaboration orders that are chosen,
13423 and figuring out which is correct, and then adding the necessary
13424 @code{Elaborate_All} pragmas to ensure the desired order.
13426 @node The Cross-Referencing Tools gnatxref and gnatfind
13427 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13428 @findex gnatxref
13429 @findex gnatfind
13431 @noindent
13432 The compiler generates cross-referencing information (unless
13433 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13434 This information indicates where in the source each entity is declared and
13435 referenced. Note that entities in package Standard are not included, but
13436 entities in all other predefined units are included in the output.
13438 Before using any of these two tools, you need to compile successfully your
13439 application, so that GNAT gets a chance to generate the cross-referencing
13440 information.
13442 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13443 information to provide the user with the capability to easily locate the
13444 declaration and references to an entity. These tools are quite similar,
13445 the difference being that @code{gnatfind} is intended for locating
13446 definitions and/or references to a specified entity or entities, whereas
13447 @code{gnatxref} is oriented to generating a full report of all
13448 cross-references.
13450 To use these tools, you must not compile your application using the
13451 @option{-gnatx} switch on the @file{gnatmake} command line (@inforef{The
13452 GNAT Make Program gnatmake,,gnat_ug}). Otherwise, cross-referencing
13453 information will not be generated.
13455 @menu
13456 * gnatxref Switches::
13457 * gnatfind Switches::
13458 * Project Files for gnatxref and gnatfind::
13459 * Regular Expressions in gnatfind and gnatxref::
13460 * Examples of gnatxref Usage::
13461 * Examples of gnatfind Usage::
13462 @end menu
13464 @node gnatxref Switches
13465 @section @code{gnatxref} Switches
13467 @noindent
13468 The command lines for @code{gnatxref} is:
13469 @smallexample
13470 $ gnatxref [switches] sourcefile1 [sourcefile2 ...]
13471 @end smallexample
13473 @noindent
13474 where
13476 @table @code
13477 @item sourcefile1, sourcefile2
13478 identifies the source files for which a report is to be generated. The
13479 'with'ed units will be processed too. You must provide at least one file.
13481 These file names are considered to be regular expressions, so for instance
13482 specifying 'source*.adb' is the same as giving every file in the current
13483 directory whose name starts with 'source' and whose extension is 'adb'.
13485 @end table
13487 @noindent
13488 The switches can be :
13489 @table @code
13490 @item ^-a^/ALL_FILES^
13491 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13492 the read-only files found in the library search path. Otherwise, these files
13493 will be ignored. This option can be used to protect Gnat sources or your own
13494 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13495 much faster, and their output much smaller.
13497 @item -aIDIR
13498 When looking for source files also look in directory DIR. The order in which
13499 source file search is undertaken is the same as for @file{gnatmake}.
13501 @item -aODIR
13502 When searching for library and object files, look in directory
13503 DIR. The order in which library files are searched is the same as for
13504 @file{gnatmake}.
13506 @item -nostdinc
13507 Do not look for sources in the system default directory.
13509 @item -nostdlib
13510 Do not look for library files in the system default directory.
13512 @item --RTS=@var{rts-path}
13513 @cindex @code{--RTS} (@code{gnatxref})
13514 Specifies the default location of the runtime library. Same meaning as the
13515 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13517 @item -d
13518 If this switch is set @code{gnatxref} will output the parent type
13519 reference for each matching derived types.
13521 @item ^-f^/FULL_PATHNAME^
13522 If this switch is set, the output file names will be preceded by their
13523 directory (if the file was found in the search path). If this switch is
13524 not set, the directory will not be printed.
13526 @item ^-g^/IGNORE_LOCALS^
13527 If this switch is set, information is output only for library-level
13528 entities, ignoring local entities. The use of this switch may accelerate
13529 @code{gnatfind} and @code{gnatxref}.
13531 @item -IDIR
13532 Equivalent to @samp{-aODIR -aIDIR}.
13534 @item -pFILE
13535 Specify a project file to use @xref{Project Files}.
13536 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13537 project file in the current directory.
13539 If a project file is either specified or found by the tools, then the content
13540 of the source directory and object directory lines are added as if they
13541 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13542 and @samp{^-aO^OBJECT_SEARCH^}.
13543 @item ^-u^/UNUSED^
13544 Output only unused symbols. This may be really useful if you give your
13545 main compilation unit on the command line, as @code{gnatxref} will then
13546 display every unused entity and 'with'ed package.
13548 @ifclear vms
13549 @item -v
13550 Instead of producing the default output, @code{gnatxref} will generate a
13551 @file{tags} file that can be used by vi. For examples how to use this
13552 feature, see @xref{Examples of gnatxref Usage}. The tags file is output
13553 to the standard output, thus you will have to redirect it to a file.
13554 @end ifclear
13556 @end table
13558 All these switches may be in any order on the command line, and may even
13559 appear after the file names. They need not be separated by spaces, thus
13560 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13561 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13563 @node gnatfind Switches
13564 @section @code{gnatfind} Switches
13566 @noindent
13567 The command line for @code{gnatfind} is:
13569 @smallexample
13570 $ gnatfind [switches] pattern[:sourcefile[:line[:column]]]
13571       [file1 file2 ...]
13572 @end smallexample
13574 @noindent
13575 where
13577 @table @code
13578 @item pattern
13579 An entity will be output only if it matches the regular expression found
13580 in @samp{pattern}, see @xref{Regular Expressions in gnatfind and gnatxref}.
13582 Omitting the pattern is equivalent to specifying @samp{*}, which
13583 will match any entity. Note that if you do not provide a pattern, you
13584 have to provide both a sourcefile and a line.
13586 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13587 for matching purposes. At the current time there is no support for
13588 8-bit codes other than Latin-1, or for wide characters in identifiers.
13590 @item sourcefile
13591 @code{gnatfind} will look for references, bodies or declarations
13592 of symbols referenced in @file{sourcefile}, at line @samp{line}
13593 and column @samp{column}. See @pxref{Examples of gnatfind Usage}
13594 for syntax examples.
13596 @item line
13597 is a decimal integer identifying the line number containing
13598 the reference to the entity (or entities) to be located.
13600 @item column
13601 is a decimal integer identifying the exact location on the
13602 line of the first character of the identifier for the
13603 entity reference. Columns are numbered from 1.
13605 @item file1 file2 ...
13606 The search will be restricted to these files. If none are given, then
13607 the search will be done for every library file in the search path.
13608 These file must appear only after the pattern or sourcefile.
13610 These file names are considered to be regular expressions, so for instance
13611 specifying 'source*.adb' is the same as giving every file in the current
13612 directory whose name starts with 'source' and whose extension is 'adb'.
13614 Not that if you specify at least one file in this part, @code{gnatfind} may
13615 sometimes not be able to find the body of the subprograms...
13617 @end table
13619 At least one of 'sourcefile' or 'pattern' has to be present on
13620 the command line.
13622 The following switches are available:
13623 @table @code
13625 @item ^-a^/ALL_FILES^
13626 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13627 the read-only files found in the library search path. Otherwise, these files
13628 will be ignored. This option can be used to protect Gnat sources or your own
13629 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13630 much faster, and their output much smaller.
13632 @item -aIDIR
13633 When looking for source files also look in directory DIR. The order in which
13634 source file search is undertaken is the same as for @file{gnatmake}.
13636 @item -aODIR
13637 When searching for library and object files, look in directory
13638 DIR. The order in which library files are searched is the same as for
13639 @file{gnatmake}.
13641 @item -nostdinc
13642 Do not look for sources in the system default directory.
13644 @item -nostdlib
13645 Do not look for library files in the system default directory.
13647 @item --RTS=@var{rts-path}
13648 @cindex @code{--RTS} (@code{gnatfind})
13649 Specifies the default location of the runtime library. Same meaning as the
13650 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
13652 @item -d
13653 If this switch is set, then @code{gnatfind} will output the parent type
13654 reference for each matching derived types.
13656 @item ^-e^/EXPRESSIONS^
13657 By default, @code{gnatfind} accept the simple regular expression set for
13658 @samp{pattern}. If this switch is set, then the pattern will be
13659 considered as full Unix-style regular expression.
13661 @item ^-f^/FULL_PATHNAME^
13662 If this switch is set, the output file names will be preceded by their
13663 directory (if the file was found in the search path). If this switch is
13664 not set, the directory will not be printed.
13666 @item ^-g^/IGNORE_LOCALS^
13667 If this switch is set, information is output only for library-level
13668 entities, ignoring local entities. The use of this switch may accelerate
13669 @code{gnatfind} and @code{gnatxref}.
13671 @item -IDIR
13672 Equivalent to @samp{-aODIR -aIDIR}.
13674 @item -pFILE
13675 Specify a project file (@pxref{Project Files}) to use.
13676 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13677 project file in the current directory.
13679 If a project file is either specified or found by the tools, then the content
13680 of the source directory and object directory lines are added as if they
13681 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13682 @samp{^-aO^/OBJECT_SEARCH^}.
13684 @item ^-r^/REFERENCES^
13685 By default, @code{gnatfind} will output only the information about the
13686 declaration, body or type completion of the entities. If this switch is
13687 set, the @code{gnatfind} will locate every reference to the entities in
13688 the files specified on the command line (or in every file in the search
13689 path if no file is given on the command line).
13691 @item ^-s^/PRINT_LINES^
13692 If this switch is set, then @code{gnatfind} will output the content
13693 of the Ada source file lines were the entity was found.
13695 @item -t
13696 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13697 the specified type. It act like -d option but recursively from parent
13698 type to parent type. When this switch is set it is not possible to
13699 specify more than one file.
13701 @end table
13703 All these switches may be in any order on the command line, and may even
13704 appear after the file names. They need not be separated by spaces, thus
13705 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13706 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13708 As stated previously, gnatfind will search in every directory in the
13709 search path. You can force it to look only in the current directory if
13710 you specify @code{*} at the end of the command line.
13713 @node Project Files for gnatxref and gnatfind
13714 @section Project Files for @command{gnatxref} and @command{gnatfind}
13716 @noindent
13717 Project files allow a programmer to specify how to compile its
13718 application, where to find sources,... These files are used primarily by
13719 the Glide Ada mode, but they can also be used by the two tools
13720 @code{gnatxref} and @code{gnatfind}.
13722 A project file name must end with @file{.adp}. If a single one is
13723 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13724 extract the information from it. If multiple project files are found, none of
13725 them is read, and you have to use the @samp{-p} switch to specify the one
13726 you want to use.
13728 The following lines can be included, even though most of them have default
13729 values which can be used in most cases.
13730 The lines can be entered in any order in the file.
13731 Except for @samp{src_dir} and @samp{obj_dir}, you can only have one instance of
13732 each line. If you have multiple instances, only the last one is taken into
13733 account.
13735 @table @code
13736 @item src_dir=DIR         [default: "^./^[]^"]
13737 specifies a directory where to look for source files. Multiple src_dir lines
13738 can be specified and they will be searched in the order they
13739 are specified.
13741 @item obj_dir=DIR         [default: "^./^[]^"]
13742 specifies a directory where to look for object and library files. Multiple
13743 obj_dir lines can be specified and they will be searched in the order they
13744 are specified
13746 @item comp_opt=SWITCHES   [default: ""]
13747 creates a variable which can be referred to subsequently by using
13748 the @samp{$@{comp_opt@}} notation. This is intended to store the default
13749 switches given to @file{gnatmake} and @file{gcc}.
13751 @item bind_opt=SWITCHES   [default: ""]
13752 creates a variable which can be referred to subsequently by using
13753 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13754 switches given to @file{gnatbind}.
13756 @item link_opt=SWITCHES   [default: ""]
13757 creates a variable which can be referred to subsequently by using
13758 the @samp{$@{link_opt@}} notation. This is intended to store the default
13759 switches given to @file{gnatlink}.
13761 @item main=EXECUTABLE     [default: ""]
13762 specifies the name of the executable for the application. This variable can
13763 be referred to in the following lines by using the @samp{$@{main@}} notation.
13765 @ifset vms
13766 @item comp_cmd=COMMAND    [default: "GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"]
13767 @end ifset
13768 @ifclear vms
13769 @item comp_cmd=COMMAND    [default: "gcc -c -I$@{src_dir@} -g -gnatq"]
13770 @end ifclear
13771 specifies the command used to compile a single file in the application.
13773 @ifset vms
13774 @item make_cmd=COMMAND    [default: "GNAT MAKE $@{main@} /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@} /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@} /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"]
13775 @end ifset
13776 @ifclear vms
13777 @item make_cmd=COMMAND    [default: "gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"]
13778 @end ifclear
13779 specifies the command used to recompile the whole application.
13781 @item run_cmd=COMMAND     [default: "$@{main@}"]
13782 specifies the command used to run the application.
13784 @item debug_cmd=COMMAND   [default: "gdb $@{main@}"]
13785 specifies the command used to debug the application
13787 @end table
13789 @code{gnatxref} and @code{gnatfind} only take into account the @samp{src_dir}
13790 and @samp{obj_dir} lines, and ignore the others.
13792 @node Regular Expressions in gnatfind and gnatxref
13793 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13795 @noindent
13796 As specified in the section about @code{gnatfind}, the pattern can be a
13797 regular expression. Actually, there are to set of regular expressions
13798 which are recognized by the program :
13800 @table @code
13801 @item globbing patterns
13802 These are the most usual regular expression. They are the same that you
13803 generally used in a Unix shell command line, or in a DOS session.
13805 Here is a more formal grammar :
13806 @smallexample
13807 @group
13808 @iftex
13809 @leftskip=.5cm
13810 @end iftex
13811 regexp ::= term
13812 term   ::= elmt            -- matches elmt
13813 term   ::= elmt elmt       -- concatenation (elmt then elmt)
13814 term   ::= *               -- any string of 0 or more characters
13815 term   ::= ?               -- matches any character
13816 term   ::= [char @{char@}] -- matches any character listed
13817 term   ::= [char - char]   -- matches any character in range
13818 @end group
13819 @end smallexample
13821 @item full regular expression
13822 The second set of regular expressions is much more powerful. This is the
13823 type of regular expressions recognized by utilities such a @file{grep}.
13825 The following is the form of a regular expression, expressed in Ada
13826 reference manual style BNF is as follows
13828 @smallexample
13829 @iftex
13830 @leftskip=.5cm
13831 @end iftex
13832 @group
13833 regexp ::= term @{| term@} -- alternation (term or term ...)
13835 term ::= item @{item@}     -- concatenation (item then item)
13837 item ::= elmt              -- match elmt
13838 item ::= elmt *            -- zero or more elmt's
13839 item ::= elmt +            -- one or more elmt's
13840 item ::= elmt ?            -- matches elmt or nothing
13841 @end group
13842 @group
13843 elmt ::= nschar            -- matches given character
13844 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13845 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13846 elmt ::= [char - char]     -- matches chars in given range
13847 elmt ::= \ char            -- matches given character
13848 elmt ::= .                 -- matches any single character
13849 elmt ::= ( regexp )        -- parens used for grouping
13851 char ::= any character, including special characters
13852 nschar ::= any character except ()[].*+?^^^
13853 @end group
13854 @end smallexample
13856 Following are a few examples :
13858 @table @samp
13859 @item abcde|fghi
13860 will match any of the two strings 'abcde' and 'fghi'.
13862 @item abc*d
13863 will match any string like 'abd', 'abcd', 'abccd', 'abcccd', and so on
13865 @item [a-z]+
13866 will match any string which has only lowercase characters in it (and at
13867 least one character
13869 @end table
13870 @end table
13872 @node Examples of gnatxref Usage
13873 @section Examples of @code{gnatxref} Usage
13875 @subsection General Usage
13877 @noindent
13878 For the following examples, we will consider the following units :
13880 @smallexample
13881 @group
13882 @cartouche
13883 main.ads:
13884 1: @b{with} Bar;
13885 2: @b{package} Main @b{is}
13886 3:     @b{procedure} Foo (B : @b{in} Integer);
13887 4:     C : Integer;
13888 5: @b{private}
13889 6:     D : Integer;
13890 7: @b{end} Main;
13892 main.adb:
13893 1: @b{package body} Main @b{is}
13894 2:     @b{procedure} Foo (B : @b{in} Integer) @b{is}
13895 3:     @b{begin}
13896 4:        C := B;
13897 5:        D := B;
13898 6:        Bar.Print (B);
13899 7:        Bar.Print (C);
13900 8:     @b{end} Foo;
13901 9: @b{end} Main;
13903 bar.ads:
13904 1: @b{package} Bar @b{is}
13905 2:     @b{procedure} Print (B : Integer);
13906 3: @b{end} bar;
13907 @end cartouche
13908 @end group
13909 @end smallexample
13911 @table @code
13913 @noindent
13914 The first thing to do is to recompile your application (for instance, in
13915 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13916 the cross-referencing information.
13917 You can then issue any of the following commands:
13919 @item gnatxref main.adb
13920 @code{gnatxref} generates cross-reference information for main.adb
13921 and every unit 'with'ed by main.adb.
13923 The output would be:
13924 @smallexample
13925 @iftex
13926 @leftskip=0cm
13927 @end iftex
13928 B                                                      Type: Integer
13929   Decl: bar.ads           2:22
13930 B                                                      Type: Integer
13931   Decl: main.ads          3:20
13932   Body: main.adb          2:20
13933   Ref:  main.adb          4:13     5:13     6:19
13934 Bar                                                    Type: Unit
13935   Decl: bar.ads           1:9
13936   Ref:  main.adb          6:8      7:8
13937        main.ads           1:6
13938 C                                                      Type: Integer
13939   Decl: main.ads          4:5
13940   Modi: main.adb          4:8
13941   Ref:  main.adb          7:19
13942 D                                                      Type: Integer
13943   Decl: main.ads          6:5
13944   Modi: main.adb          5:8
13945 Foo                                                    Type: Unit
13946   Decl: main.ads          3:15
13947   Body: main.adb          2:15
13948 Main                                                    Type: Unit
13949   Decl: main.ads          2:9
13950   Body: main.adb          1:14
13951 Print                                                   Type: Unit
13952   Decl: bar.ads           2:15
13953   Ref:  main.adb          6:12     7:12
13954 @end smallexample
13956 @noindent
13957 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13958 its body is in main.adb, line 1, column 14 and is not referenced any where.
13960 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13961 it referenced in main.adb, line 6 column 12 and line 7 column 12.
13963 @item gnatxref package1.adb package2.ads
13964 @code{gnatxref} will generates cross-reference information for
13965 package1.adb, package2.ads and any other package 'with'ed by any
13966 of these.
13968 @end table
13970 @ifclear vms
13971 @subsection Using gnatxref with vi
13973 @code{gnatxref} can generate a tags file output, which can be used
13974 directly from @file{vi}. Note that the standard version of @file{vi}
13975 will not work properly with overloaded symbols. Consider using another
13976 free implementation of @file{vi}, such as @file{vim}.
13978 @smallexample
13979 $ gnatxref -v gnatfind.adb > tags
13980 @end smallexample
13982 @noindent
13983 will generate the tags file for @code{gnatfind} itself (if the sources
13984 are in the search path!).
13986 From @file{vi}, you can then use the command @samp{:tag @i{entity}}
13987 (replacing @i{entity} by whatever you are looking for), and vi will
13988 display a new file with the corresponding declaration of entity.
13989 @end ifclear
13991 @node Examples of gnatfind Usage
13992 @section Examples of @code{gnatfind} Usage
13994 @table @code
13996 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13997 Find declarations for all entities xyz referenced at least once in
13998 main.adb. The references are search in every library file in the search
13999 path.
14001 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14002 switch is set)
14004 The output will look like:
14005 @smallexample
14006 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14007 ^directory/^[directory]^main.adb:24:10: xyz <= body
14008 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14009 @end smallexample
14011 @noindent
14012 that is to say, one of the entities xyz found in main.adb is declared at
14013 line 12 of main.ads (and its body is in main.adb), and another one is
14014 declared at line 45 of foo.ads
14016 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14017 This is the same command as the previous one, instead @code{gnatfind} will
14018 display the content of the Ada source file lines.
14020 The output will look like:
14022 @smallexample
14023 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14024    procedure xyz;
14025 ^directory/^[directory]^main.adb:24:10: xyz <= body
14026    procedure xyz is
14027 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14028    xyz : Integer;
14029 @end smallexample
14031 @noindent
14032 This can make it easier to find exactly the location your are looking
14033 for.
14035 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14036 Find references to all entities containing an x that are
14037 referenced on line 123 of main.ads.
14038 The references will be searched only in main.adb and foo.adb.
14040 @item gnatfind main.ads:123
14041 Find declarations and bodies for all entities that are referenced on
14042 line 123 of main.ads.
14044 This is the same as @code{gnatfind "*":main.adb:123}.
14046 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14047 Find the declaration for the entity referenced at column 45 in
14048 line 123 of file main.adb in directory mydir. Note that it
14049 is usual to omit the identifier name when the column is given,
14050 since the column position identifies a unique reference.
14052 The column has to be the beginning of the identifier, and should not
14053 point to any character in the middle of the identifier.
14055 @end table
14057 @node File Name Krunching Using gnatkr
14058 @chapter File Name Krunching Using @code{gnatkr}
14059 @findex gnatkr
14061 @noindent
14062 This chapter discusses the method used by the compiler to shorten
14063 the default file names chosen for Ada units so that they do not
14064 exceed the maximum length permitted. It also describes the
14065 @code{gnatkr} utility that can be used to determine the result of
14066 applying this shortening.
14067 @menu
14068 * About gnatkr::
14069 * Using gnatkr::
14070 * Krunching Method::
14071 * Examples of gnatkr Usage::
14072 @end menu
14074 @node About gnatkr
14075 @section About @code{gnatkr}
14077 @noindent
14078 The default file naming rule in GNAT
14079 is that the file name must be derived from
14080 the unit name. The exact default rule is as follows:
14081 @itemize @bullet
14082 @item
14083 Take the unit name and replace all dots by hyphens.
14084 @item
14085 If such a replacement occurs in the
14086 second character position of a name, and the first character is
14087 ^a, g, s, or i^A, G, S, or I^ then replace the dot by the character
14088 ^~ (tilde)^$ (dollar sign)^
14089 instead of a minus.
14090 @end itemize
14091 The reason for this exception is to avoid clashes
14092 with the standard names for children of System, Ada, Interfaces,
14093 and GNAT, which use the prefixes ^s- a- i- and g-^S- A- I- and G-^
14094 respectively.
14096 The @code{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
14097 switch of the compiler activates a "krunching"
14098 circuit that limits file names to nn characters (where nn is a decimal
14099 integer). For example, using OpenVMS,
14100 where the maximum file name length is
14101 39, the value of nn is usually set to 39, but if you want to generate
14102 a set of files that would be usable if ported to a system with some
14103 different maximum file length, then a different value can be specified.
14104 The default value of 39 for OpenVMS need not be specified.
14106 The @code{gnatkr} utility can be used to determine the krunched name for
14107 a given file, when krunched to a specified maximum length.
14109 @node Using gnatkr
14110 @section Using @code{gnatkr}
14112 @noindent
14113 The @code{gnatkr} command has the form
14115 @ifclear vms
14116 @smallexample
14117 $ gnatkr @var{name} [@var{length}]
14118 @end smallexample
14119 @end ifclear
14121 @ifset vms
14122 @smallexample
14123 $ gnatkr @var{name} /COUNT=nn
14124 @end smallexample
14125 @end ifset
14127 @noindent
14128 @var{name} can be an Ada name with dots or the GNAT name of the unit,
14129 where the dots representing child units or subunit are replaced by
14130 hyphens. The only confusion arises if a name ends in @code{.ads} or
14131 @code{.adb}. @code{gnatkr} takes this to be an extension if there are
14132 no other dots in the name^ and the whole name is in lowercase^^.
14134 @var{length} represents the length of the krunched name. The default
14135 when no argument is given is ^8^39^ characters. A length of zero stands for
14136 unlimited, in other words do not chop except for system files which are
14137 always ^8^39^.
14139 @noindent
14140 The output is the krunched name. The output has an extension only if the
14141 original argument was a file name with an extension.
14143 @node Krunching Method
14144 @section Krunching Method
14146 @noindent
14147 The initial file name is determined by the name of the unit that the file
14148 contains. The name is formed by taking the full expanded name of the
14149 unit and replacing the separating dots with hyphens and
14150 using ^lowercase^uppercase^
14151 for all letters, except that a hyphen in the second character position is
14152 replaced by a ^tilde^dollar sign^ if the first character is
14153 ^a, i, g, or s^A, I, G, or S^.
14154 The extension is @code{.ads} for a
14155 specification and @code{.adb} for a body.
14156 Krunching does not affect the extension, but the file name is shortened to
14157 the specified length by following these rules:
14159 @itemize @bullet
14160 @item
14161 The name is divided into segments separated by hyphens, tildes or
14162 underscores and all hyphens, tildes, and underscores are
14163 eliminated. If this leaves the name short enough, we are done.
14165 @item
14166 If the name is too long, the longest segment is located (left-most if there are two
14167 of equal length), and shortened by dropping its last character. This is
14168 repeated until the name is short enough.
14170 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
14171 to fit the name into 8 characters as required by some operating systems.
14173 @smallexample
14174 our-strings-wide_fixed 22
14175 our strings wide fixed 19
14176 our string  wide fixed 18
14177 our strin   wide fixed 17
14178 our stri    wide fixed 16
14179 our stri    wide fixe  15
14180 our str     wide fixe  14
14181 our str     wid  fixe  13
14182 our str     wid  fix   12
14183 ou  str     wid  fix   11
14184 ou  st      wid  fix   10
14185 ou  st      wi   fix   9
14186 ou  st      wi   fi    8
14187 Final file name: oustwifi.adb
14188 @end smallexample
14190 @item
14191 The file names for all predefined units are always krunched to eight
14192 characters. The krunching of these predefined units uses the following
14193 special prefix replacements:
14195 @table @file
14196 @item ada-
14197 replaced by @file{^a^A^-}
14199 @item gnat-
14200 replaced by @file{^g^G^-}
14202 @item interfaces-
14203 replaced by @file{^i^I^-}
14205 @item system-
14206 replaced by @file{^s^S^-}
14207 @end table
14209 These system files have a hyphen in the second character position. That
14210 is why normal user files replace such a character with a
14211 ^tilde^dollar sign^, to
14212 avoid confusion with system file names.
14214 As an example of this special rule, consider
14215 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
14217 @smallexample
14218 ada-strings-wide_fixed 22
14219 a-  strings wide fixed 18
14220 a-  string  wide fixed 17
14221 a-  strin   wide fixed 16
14222 a-  stri    wide fixed 15
14223 a-  stri    wide fixe  14
14224 a-  str     wide fixe  13
14225 a-  str     wid  fixe  12
14226 a-  str     wid  fix   11
14227 a-  st      wid  fix   10
14228 a-  st      wi   fix   9
14229 a-  st      wi   fi    8
14230 Final file name: a-stwifi.adb
14231 @end smallexample
14232 @end itemize
14234 Of course no file shortening algorithm can guarantee uniqueness over all
14235 possible unit names, and if file name krunching is used then it is your
14236 responsibility to ensure that no name clashes occur. The utility
14237 program @code{gnatkr} is supplied for conveniently determining the
14238 krunched name of a file.
14240 @node Examples of gnatkr Usage
14241 @section Examples of @code{gnatkr} Usage
14243 @smallexample
14244 @iftex
14245 @leftskip=0cm
14246 @end iftex
14247 @ifclear vms
14248 $ gnatkr very_long_unit_name.ads      --> velounna.ads
14249 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
14250 $ gnatkr Grandparent.Parent.Child     --> grparchi
14251 @end ifclear
14252 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
14253 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
14254 @end smallexample
14256 @node Preprocessing Using gnatprep
14257 @chapter Preprocessing Using @code{gnatprep}
14258 @findex gnatprep
14260 @noindent
14261 The @code{gnatprep} utility provides
14262 a simple preprocessing capability for Ada programs.
14263 It is designed for use with GNAT, but is not dependent on any special
14264 features of GNAT.
14266 @menu
14267 * Using gnatprep::
14268 * Switches for gnatprep::
14269 * Form of Definitions File::
14270 * Form of Input Text for gnatprep::
14271 @end menu
14273 @node Using gnatprep
14274 @section Using @code{gnatprep}
14276 @noindent
14277 To call @code{gnatprep} use
14279 @smallexample
14280 $ gnatprep [-bcrsu] [-Dsymbol=value] infile outfile [deffile]
14281 @end smallexample
14283 @noindent
14284 where
14285 @table @code
14286 @item infile
14287 is the full name of the input file, which is an Ada source
14288 file containing preprocessor directives.
14290 @item outfile
14291 is the full name of the output file, which is an Ada source
14292 in standard Ada form. When used with GNAT, this file name will
14293 normally have an ads or adb suffix.
14295 @item deffile
14296 is the full name of a text file containing definitions of
14297 symbols to be referenced by the preprocessor. This argument is
14298 optional, and can be replaced by the use of the @code{-D} switch.
14300 @item switches
14301 is an optional sequence of switches as described in the next section.
14302 @end table
14304 @node Switches for gnatprep
14305 @section Switches for @code{gnatprep}
14307 @table @code
14309 @item ^-b^/BLANK_LINES^
14310 Causes both preprocessor lines and the lines deleted by
14311 preprocessing to be replaced by blank lines in the output source file,
14312 preserving line numbers in the output file.
14314 @item ^-c^/COMMENTS^
14315 Causes both preprocessor lines and the lines deleted
14316 by preprocessing to be retained in the output source as comments marked
14317 with the special string "--! ". This option will result in line numbers
14318 being preserved in the output file.
14320 @item -Dsymbol=value
14321 Defines a new symbol, associated with value. If no value is given on the
14322 command line, then symbol is considered to be @code{True}. This switch
14323 can be used in place of a definition file.
14325 @ifset vms
14326 @item /REMOVE (default)
14327 This is the default setting which causes lines deleted by preprocessing
14328 to be entirely removed from the output file.
14329 @end ifset
14331 @item ^-r^/REFERENCE^
14332 Causes a @code{Source_Reference} pragma to be generated that
14333 references the original input file, so that error messages will use
14334 the file name of this original file. The use of this switch implies
14335 that preprocessor lines are not to be removed from the file, so its
14336 use will force @code{^-b^/BLANK_LINES^} mode if
14337 @code{^-c^/COMMENTS^}
14338 has not been specified explicitly.
14340 Note that if the file to be preprocessed contains multiple units, then
14341 it will be necessary to @code{gnatchop} the output file from
14342 @code{gnatprep}. If a @code{Source_Reference} pragma is present
14343 in the preprocessed file, it will be respected by
14344 @code{gnatchop ^-r^/REFERENCE^}
14345 so that the final chopped files will correctly refer to the original
14346 input source file for @code{gnatprep}.
14348 @item ^-s^/SYMBOLS^
14349 Causes a sorted list of symbol names and values to be
14350 listed on the standard output file.
14352 @item ^-u^/UNDEFINED^
14353 Causes undefined symbols to be treated as having the value FALSE in the context
14354 of a preprocessor test. In the absence of this option, an undefined symbol in
14355 a @code{#if} or @code{#elsif} test will be treated as an error.
14357 @end table
14359 @ifclear vms
14360 @noindent
14361 Note: if neither @code{-b} nor @code{-c} is present,
14362 then preprocessor lines and
14363 deleted lines are completely removed from the output, unless -r is
14364 specified, in which case -b is assumed.
14365 @end ifclear
14367 @node Form of Definitions File
14368 @section Form of Definitions File
14370 @noindent
14371 The definitions file contains lines of the form
14373 @smallexample
14374 symbol := value
14375 @end smallexample
14377 @noindent
14378 where symbol is an identifier, following normal Ada (case-insensitive)
14379 rules for its syntax, and value is one of the following:
14381 @itemize @bullet
14382 @item
14383 Empty, corresponding to a null substitution
14384 @item
14385 A string literal using normal Ada syntax
14386 @item
14387 Any sequence of characters from the set
14388 (letters, digits, period, underline).
14389 @end itemize
14391 @noindent
14392 Comment lines may also appear in the definitions file, starting with
14393 the usual @code{--},
14394 and comments may be added to the definitions lines.
14396 @node Form of Input Text for gnatprep
14397 @section Form of Input Text for @code{gnatprep}
14399 @noindent
14400 The input text may contain preprocessor conditional inclusion lines,
14401 as well as general symbol substitution sequences.
14403 The preprocessor conditional inclusion commands have the form
14405 @smallexample
14406 @group
14407 @cartouche
14408 #if @i{expression} [then]
14409    lines
14410 #elsif @i{expression} [then]
14411    lines
14412 #elsif @i{expression} [then]
14413    lines
14415 #else
14416    lines
14417 #end if;
14418 @end cartouche
14419 @end group
14420 @end smallexample
14422 @noindent
14423 In this example, @i{expression} is defined by the following grammar:
14424 @smallexample
14425 @i{expression} ::=  <symbol>
14426 @i{expression} ::=  <symbol> = "<value>"
14427 @i{expression} ::=  <symbol> = <symbol>
14428 @i{expression} ::=  <symbol> 'Defined
14429 @i{expression} ::=  not @i{expression}
14430 @i{expression} ::=  @i{expression} and @i{expression}
14431 @i{expression} ::=  @i{expression} or @i{expression}
14432 @i{expression} ::=  @i{expression} and then @i{expression}
14433 @i{expression} ::=  @i{expression} or else @i{expression}
14434 @i{expression} ::=  ( @i{expression} )
14435 @end smallexample
14437 @noindent
14438 For the first test (@i{expression} ::= <symbol>) the symbol must have
14439 either the value true or false, that is to say the right-hand of the
14440 symbol definition must be one of the (case-insensitive) literals
14441 @code{True} or @code{False}. If the value is true, then the
14442 corresponding lines are included, and if the value is false, they are
14443 excluded.
14445 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
14446 the symbol has been defined in the definition file or by a @code{-D}
14447 switch on the command line. Otherwise, the test is false.
14449 The equality tests are case insensitive, as are all the preprocessor lines.
14451 If the symbol referenced is not defined in the symbol definitions file,
14452 then the effect depends on whether or not switch @code{-u}
14453 is specified. If so, then the symbol is treated as if it had the value
14454 false and the test fails. If this switch is not specified, then
14455 it is an error to reference an undefined symbol. It is also an error to
14456 reference a symbol that is defined with a value other than @code{True}
14457 or @code{False}.
14459 The use of the @code{not} operator inverts the sense of this logical test, so
14460 that the lines are included only if the symbol is not defined.
14461 The @code{then} keyword is optional as shown
14463 The @code{#} must be the first non-blank character on a line, but
14464 otherwise the format is free form. Spaces or tabs may appear between
14465 the @code{#} and the keyword. The keywords and the symbols are case
14466 insensitive as in normal Ada code. Comments may be used on a
14467 preprocessor line, but other than that, no other tokens may appear on a
14468 preprocessor line. Any number of @code{elsif} clauses can be present,
14469 including none at all. The @code{else} is optional, as in Ada.
14471 The @code{#} marking the start of a preprocessor line must be the first
14472 non-blank character on the line, i.e. it must be preceded only by
14473 spaces or horizontal tabs.
14475 Symbol substitution outside of preprocessor lines is obtained by using
14476 the sequence
14478 @smallexample
14479 $symbol
14480 @end smallexample
14482 @noindent
14483 anywhere within a source line, except in a comment or within a
14484 string literal. The identifier
14485 following the @code{$} must match one of the symbols defined in the symbol
14486 definition file, and the result is to substitute the value of the
14487 symbol in place of @code{$symbol} in the output file.
14489 Note that although the substitution of strings within a string literal
14490 is not possible, it is possible to have a symbol whose defined value is
14491 a string literal. So instead of setting XYZ to @code{hello} and writing:
14493 @smallexample
14494 Header : String := "$XYZ";
14495 @end smallexample
14497 @noindent
14498 you should set XYZ to @code{"hello"} and write:
14500 @smallexample
14501 Header : String := $XYZ;
14502 @end smallexample
14504 @noindent
14505 and then the substitution will occur as desired.
14507 @ifset vms
14508 @node The GNAT Run-Time Library Builder gnatlbr
14509 @chapter The GNAT Run-Time Library Builder @code{gnatlbr}
14510 @findex gnatlbr
14511 @cindex Library builder
14513 @noindent
14514 @code{gnatlbr} is a tool for rebuilding the GNAT run time with user
14515 supplied configuration pragmas.
14517 @menu
14518 * Running gnatlbr::
14519 * Switches for gnatlbr::
14520 * Examples of gnatlbr Usage::
14521 @end menu
14523 @node Running gnatlbr
14524 @section Running @code{gnatlbr}
14526 @noindent
14527 The @code{gnatlbr} command has the form
14529 @smallexample
14530 @ifclear vms
14531 $ gnatlbr --[create | set | delete]=directory --config=file
14532 @end ifclear
14533 @ifset vms
14534 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
14535 @end ifset
14536 @end smallexample
14538 @node Switches for gnatlbr
14539 @section Switches for @code{gnatlbr}
14541 @noindent
14542 @code{gnatlbr} recognizes the following switches:
14544 @table @code
14545 @item ^--create^/CREATE^=directory
14546 @cindex @code{^--create^/CREATE^=directory} (@code{gnatlbr})
14547      Create the new run-time library in the specified directory.
14549 @item ^--set^/SET^=directory
14550 @cindex @code{^--set^/SET^=directory} (@code{gnatlbr})
14551      Make the library in the specified directory the current run-time
14552      library.
14554 @item ^--delete^/DELETE^=directory
14555 @cindex @code{^--delete^/DELETE^=directory} (@code{gnatlbr})
14556      Delete the run-time library in the specified directory.
14558 @item ^--config^/CONFIG^=file
14559 @cindex @code{^--config^/CONFIG^=file} (@code{gnatlbr})
14560      With ^--create^/CREATE^:
14561      Use the configuration pragmas in the specified file when building
14562      the library.
14564      With ^--set^/SET^:
14565      Use the configuration pragmas in the specified file when compiling.
14567 @end table
14569 @node Examples of gnatlbr Usage
14570 @section Example of @code{gnatlbr} Usage
14572 @smallexample
14573 Contents of VAXFLOAT.ADC:
14574 pragma Float_Representation (VAX_Float);
14576 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
14578 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
14580 @end smallexample
14581 @end ifset
14583 @node The GNAT Library Browser gnatls
14584 @chapter The GNAT Library Browser @code{gnatls}
14585 @findex gnatls
14586 @cindex Library browser
14588 @noindent
14589 @code{gnatls} is a tool that outputs information about compiled
14590 units. It gives the relationship between objects, unit names and source
14591 files. It can also be used to check the source dependencies of a unit
14592 as well as various characteristics.
14594 @menu
14595 * Running gnatls::
14596 * Switches for gnatls::
14597 * Examples of gnatls Usage::
14598 @end menu
14600 @node Running gnatls
14601 @section Running @code{gnatls}
14603 @noindent
14604 The @code{gnatls} command has the form
14606 @smallexample
14607 $ gnatls switches @var{object_or_ali_file}
14608 @end smallexample
14610 @noindent
14611 The main argument is the list of object or @file{ali} files
14612 (@pxref{The Ada Library Information Files})
14613 for which information is requested.
14615 In normal mode, without additional option, @code{gnatls} produces a
14616 four-column listing. Each line represents information for a specific
14617 object. The first column gives the full path of the object, the second
14618 column gives the name of the principal unit in this object, the third
14619 column gives the status of the source and the fourth column gives the
14620 full path of the source representing this unit.
14621 Here is a simple example of use:
14623 @smallexample
14624 $ gnatls *.o
14625 ^./^[]^demo1.o            demo1            DIF demo1.adb
14626 ^./^[]^demo2.o            demo2             OK demo2.adb
14627 ^./^[]^hello.o            h1                OK hello.adb
14628 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
14629 ^./^[]^instr.o            instr             OK instr.adb
14630 ^./^[]^tef.o              tef              DIF tef.adb
14631 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
14632 ^./^[]^tgef.o             tgef             DIF tgef.adb
14633 @end smallexample
14635 @noindent
14636 The first line can be interpreted as follows: the main unit which is
14637 contained in
14638 object file @file{demo1.o} is demo1, whose main source is in
14639 @file{demo1.adb}. Furthermore, the version of the source used for the
14640 compilation of demo1 has been modified (DIF). Each source file has a status
14641 qualifier which can be:
14643 @table @code
14644 @item OK (unchanged)
14645 The version of the source file used for the compilation of the
14646 specified unit corresponds exactly to the actual source file.
14648 @item MOK (slightly modified)
14649 The version of the source file used for the compilation of the
14650 specified unit differs from the actual source file but not enough to
14651 require recompilation. If you use gnatmake with the qualifier
14652 @code{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
14653 MOK will not be recompiled.
14655 @item DIF (modified)
14656 No version of the source found on the path corresponds to the source
14657 used to build this object.
14659 @item ??? (file not found)
14660 No source file was found for this unit.
14662 @item HID (hidden,  unchanged version not first on PATH)
14663 The version of the source that corresponds exactly to the source used
14664 for compilation has been found on the path but it is hidden by another
14665 version of the same source that has been modified.
14667 @end table
14669 @node Switches for gnatls
14670 @section Switches for @code{gnatls}
14672 @noindent
14673 @code{gnatls} recognizes the following switches:
14675 @table @code
14676 @item ^-a^/ALL_UNITS^
14677 @cindex @code{^-a^/ALL_UNITS^} (@code{gnatls})
14678 Consider all units, including those of the predefined Ada library.
14679 Especially useful with @code{^-d^/DEPENDENCIES^}.
14681 @item ^-d^/DEPENDENCIES^
14682 @cindex @code{^-d^/DEPENDENCIES^} (@code{gnatls})
14683 List sources from which specified units depend on.
14685 @item ^-h^/OUTPUT=OPTIONS^
14686 @cindex @code{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
14687 Output the list of options.
14689 @item ^-o^/OUTPUT=OBJECTS^
14690 @cindex @code{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
14691 Only output information about object files.
14693 @item ^-s^/OUTPUT=SOURCES^
14694 @cindex @code{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
14695 Only output information about source files.
14697 @item ^-u^/OUTPUT=UNITS^
14698 @cindex @code{^-u^/OUTPUT=UNITS^} (@code{gnatls})
14699 Only output information about compilation units.
14701 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
14702 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
14703 @itemx ^-I^/SEARCH=^@var{dir}
14704 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
14705 @itemx -nostdinc
14706 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
14707 (see @ref{Switches for gnatmake}).
14709 @item --RTS=@var{rts-path}
14710 @cindex @code{--RTS} (@code{gnatls})
14711 Specifies the default location of the runtime library. Same meaning as the
14712 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
14714 @item ^-v^/OUTPUT=VERBOSE^
14715 @cindex @code{^-s^/OUTPUT=VERBOSE^} (@code{gnatls})
14716 Verbose mode. Output the complete source and object paths. Do not use
14717 the default column layout but instead use long format giving as much as
14718 information possible on each requested units, including special
14719 characteristics such as:
14721 @table @code
14722 @item  Preelaborable
14723 The unit is preelaborable in the Ada 95 sense.
14725 @item No_Elab_Code
14726 No elaboration code has been produced by the compiler for this unit.
14728 @item Pure
14729 The unit is pure in the Ada 95 sense.
14731 @item Elaborate_Body
14732 The unit contains a pragma Elaborate_Body.
14734 @item Remote_Types
14735 The unit contains a pragma Remote_Types.
14737 @item Shared_Passive
14738 The unit contains a pragma Shared_Passive.
14740 @item Predefined
14741 This unit is part of the predefined environment and cannot be modified
14742 by the user.
14744 @item Remote_Call_Interface
14745 The unit contains a pragma Remote_Call_Interface.
14747 @end table
14749 @end table
14751 @node Examples of gnatls Usage
14752 @section Example of @code{gnatls} Usage
14753 @ifclear vms
14755 @noindent
14756 Example of using the verbose switch. Note how the source and
14757 object paths are affected by the ^-I^/SEARCH^ switch.
14759 @smallexample
14760 $ gnatls -v -I.. demo1.o
14762 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
14764 Source Search Path:
14765    <Current_Directory>
14766    ../
14767    /home/comar/local/adainclude/
14769 Object Search Path:
14770    <Current_Directory>
14771    ../
14772    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
14774 ./demo1.o
14775    Unit =>
14776      Name   => demo1
14777      Kind   => subprogram body
14778      Flags  => No_Elab_Code
14779      Source => demo1.adb    modified
14780 @end smallexample
14782 @noindent
14783 The following is an example of use of the dependency list.
14784 Note the use of the -s switch
14785 which gives a straight list of source files. This can be useful for
14786 building specialized scripts.
14788 @smallexample
14789 $ gnatls -d demo2.o
14790 ./demo2.o   demo2        OK demo2.adb
14791                          OK gen_list.ads
14792                          OK gen_list.adb
14793                          OK instr.ads
14794                          OK instr-child.ads
14796 $ gnatls -d -s -a demo1.o
14797 demo1.adb
14798 /home/comar/local/adainclude/ada.ads
14799 /home/comar/local/adainclude/a-finali.ads
14800 /home/comar/local/adainclude/a-filico.ads
14801 /home/comar/local/adainclude/a-stream.ads
14802 /home/comar/local/adainclude/a-tags.ads
14803 gen_list.ads
14804 gen_list.adb
14805 /home/comar/local/adainclude/gnat.ads
14806 /home/comar/local/adainclude/g-io.ads
14807 instr.ads
14808 /home/comar/local/adainclude/system.ads
14809 /home/comar/local/adainclude/s-exctab.ads
14810 /home/comar/local/adainclude/s-finimp.ads
14811 /home/comar/local/adainclude/s-finroo.ads
14812 /home/comar/local/adainclude/s-secsta.ads
14813 /home/comar/local/adainclude/s-stalib.ads
14814 /home/comar/local/adainclude/s-stoele.ads
14815 /home/comar/local/adainclude/s-stratt.ads
14816 /home/comar/local/adainclude/s-tasoli.ads
14817 /home/comar/local/adainclude/s-unstyp.ads
14818 /home/comar/local/adainclude/unchconv.ads
14819 @end smallexample
14820 @end ifclear
14822 @ifset vms
14823 @smallexample
14824 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
14826 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
14827 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
14828 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
14829 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
14830 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
14831 demo1.adb
14832 gen_list.ads
14833 gen_list.adb
14834 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
14835 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
14836 instr.ads
14837 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
14838 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
14839 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
14840 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
14841 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
14842 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
14843 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
14844 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
14845 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
14846 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
14847 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
14848 @end smallexample
14849 @end ifset
14851 @ifclear vms
14852 @node GNAT and Libraries
14853 @chapter GNAT and Libraries
14854 @cindex Library, building, installing
14856 @noindent
14857 This chapter addresses some of the issues related to building and using
14858 a library with GNAT. It also shows how the GNAT run-time library can be
14859 recompiled.
14861 @menu
14862 * Creating an Ada Library::
14863 * Installing an Ada Library::
14864 * Using an Ada Library::
14865 * Creating an Ada Library to be Used in a Non-Ada Context::
14866 * Rebuilding the GNAT Run-Time Library::
14867 @end menu
14869 @node Creating an Ada Library
14870 @section Creating an Ada Library
14872 @noindent
14873 In the GNAT environment, a library has two components:
14874 @itemize @bullet
14875 @item
14876 Source files.
14877 @item
14878 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
14879 @end itemize
14881 @noindent
14882 In order to use other packages @ref{The GNAT Compilation Model}
14883 requires a certain number of sources to be available to the compiler.
14884 The minimal set of
14885 sources required includes the specs of all the packages that make up the
14886 visible part of the library as well as all the sources upon which they
14887 depend. The bodies of all visible generic units must also be provided.
14888 @noindent
14889 Although it is not strictly mandatory, it is recommended that all sources
14890 needed to recompile the library be provided, so that the user can make
14891 full use of inter-unit inlining and source-level debugging. This can also
14892 make the situation easier for users that need to upgrade their compilation
14893 toolchain and thus need to recompile the library from sources.
14895 @noindent
14896 The compiled code can be provided in different ways. The simplest way is
14897 to provide directly the set of objects produced by the compiler during
14898 the compilation of the library. It is also possible to group the objects
14899 into an archive using whatever commands are provided by the operating
14900 system. Finally, it is also possible to create a shared library (see
14901 option -shared in the GCC manual).
14903 @noindent
14904 There are various possibilities for compiling the units that make up the
14905 library: for example with a Makefile @ref{Using the GNU make Utility},
14906 or with a conventional script.
14907 For simple libraries, it is also possible to create a
14908 dummy main program which depends upon all the packages that comprise the
14909 interface of the library. This dummy main program can then be given to
14910 gnatmake, in order to build all the necessary objects. Here is an example
14911 of such a dummy program and the generic commands used to build an
14912 archive or a shared library.
14914 @smallexample
14915 @iftex
14916 @leftskip=.7cm
14917 @end iftex
14918 @b{with} My_Lib.Service1;
14919 @b{with} My_Lib.Service2;
14920 @b{with} My_Lib.Service3;
14921 @b{procedure} My_Lib_Dummy @b{is}
14922 @b{begin}
14923    @b{null};
14924 @b{end};
14926 # compiling the library
14927 $ gnatmake -c my_lib_dummy.adb
14929 # we don't need the dummy object itself
14930 $ rm my_lib_dummy.o my_lib_dummy.ali
14932 # create an archive with the remaining objects
14933 $ ar rc libmy_lib.a *.o
14934 # some systems may require "ranlib" to be run as well
14936 # or create a shared library
14937 $ gcc -shared -o libmy_lib.so *.o
14938 # some systems may require the code to have been compiled with -fPIC
14939 @end smallexample
14941 @noindent
14942 When the objects are grouped in an archive or a shared library, the user
14943 needs to specify the desired library at link time, unless a pragma
14944 linker_options has been used in one of the sources:
14945 @smallexample
14946 @b{pragma} Linker_Options ("-lmy_lib");
14947 @end smallexample
14949 @node Installing an Ada Library
14950 @section Installing an Ada Library
14952 @noindent
14953 In the GNAT model, installing a library consists in copying into a specific
14954 location the files that make up this library. It is possible to install
14955 the sources in a different directory from the other files (ALI, objects,
14956 archives) since the source path and the object path can easily be
14957 specified separately.
14959 @noindent
14960 For general purpose libraries, it is possible for the system
14961 administrator to put those libraries in the default compiler paths. To
14962 achieve this, he must specify their location in the configuration files
14963 "ada_source_path" and "ada_object_path" that must be located in the GNAT
14964 installation tree at the same place as the gcc spec file. The location of
14965 the gcc spec file can be determined as follows:
14966 @smallexample
14967 $ gcc -v
14968 @end smallexample
14970 @noindent
14971 The configuration files mentioned above have simple format: each line in them
14972 must contain one unique
14973 directory name. Those names are added to the corresponding path
14974 in their order of appearance in the file. The names can be either absolute
14975 or relative, in the latter case, they are relative to where theses files
14976 are located.
14978 @noindent
14979 "ada_source_path" and "ada_object_path" might actually not be present in a
14980 GNAT installation, in which case, GNAT will look for its run-time library in
14981 the directories "adainclude" for the sources and "adalib" for the
14982 objects and ALI files. When the files exist, the compiler does not
14983 look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file
14984 must contain the location for the GNAT run-time sources (which can simply
14985 be "adainclude"). In the same way, the "ada_object_path" file must contain
14986 the location for the GNAT run-time objects (which can simply
14987 be "adalib").
14989 @noindent
14990 You can also specify a new default path to the runtime library at compilation
14991 time with the switch "--RTS=@var{rts-path}". You can easily choose and change
14992 the runtime you want your program to be compiled with. This switch is
14993 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
14995 @noindent
14996 It is possible to install a library before or after the standard GNAT
14997 library, by reordering the lines in the configuration files. In general, a
14998 library must be installed before the GNAT library if it redefines any part of it.
15000 @node Using an Ada Library
15001 @section Using an Ada Library
15003 @noindent
15004 In order to use a Ada library, you need to make sure that this
15005 library is on both your source and object path
15006 @ref{Search Paths and the Run-Time Library (RTL)}
15007 and @ref{Search Paths for gnatbind}. For
15008 instance, you can use the library "mylib" installed in "/dir/my_lib_src"
15009 and "/dir/my_lib_obj" with the following commands:
15011 @smallexample
15012 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15013   -largs -lmy_lib
15014 @end smallexample
15016 @noindent
15017 This can be simplified down to the following:
15018 @smallexample
15019 $ gnatmake my_appl
15020 @end smallexample
15021 when the following conditions are met:
15022 @itemize @bullet
15023 @item
15024 "/dir/my_lib_src" has been added by the user to the environment
15025 variable "ADA_INCLUDE_PATH", or by the administrator to the file
15026 "ada_source_path"
15027 @item
15028 "/dir/my_lib_obj" has been added by the user to the environment
15029 variable "ADA_OBJECTS_PATH", or by the administrator to the file
15030 "ada_object_path"
15031 @item
15032 a pragma linker_options, as mentioned in @ref{Creating an Ada Library}
15033 as been added to the sources.
15034 @end itemize
15035 @noindent
15037 @node Creating an Ada Library to be Used in a Non-Ada Context
15038 @section Creating an Ada Library to be Used in a Non-Ada Context
15040 @noindent
15041 The previous sections detailed how to create and install a library that
15042 was usable from an Ada main program. Using this library in a non-Ada
15043 context is not possible, because the elaboration of the library is
15044 automatically done as part of the main program elaboration.
15046 GNAT also provides the ability to build libraries that can be used both
15047 in an Ada and non-Ada context.  This section describes how to build such
15048 a library, and then how to use it from a C program. The method for
15049 interfacing with the library from other languages such as Fortran for
15050 instance remains the same.
15052 @subsection Creating the Library
15054 @itemize @bullet
15055 @item Identify the units representing the interface of the library.
15057 Here is an example of simple library interface:
15059 @smallexample
15060 package Interface is
15062    procedure Do_Something;
15064    procedure Do_Something_Else;
15066 end Interface;
15067 @end smallexample
15069 @item Use @code{pragma Export} or @code{pragma Convention} for the
15070 exported entities.
15072 Our package @code{Interface} is then updated as follow:
15073 @smallexample
15074 package Interface is
15076    procedure Do_Something;
15077    pragma Export (C, Do_Something, "do_something");
15079    procedure Do_Something_Else;
15080    pragma Export (C, Do_Something_Else, "do_something_else");
15082 end Interface;
15083 @end smallexample
15085 @item Compile all the units composing the library.
15087 @item Bind the library objects.
15089 This step is performed by invoking gnatbind with the @code{-L<prefix>}
15090 switch. @code{gnatbind} will then generate the library elaboration
15091 procedure (named @code{<prefix>init}) and the run-time finalization
15092 procedure (named @code{<prefix>final}).
15094 @smallexample
15095 # generate the binder file in Ada
15096 $ gnatbind -Lmylib interface
15098 # generate the binder file in C
15099 $ gnatbind -C -Lmylib interface
15100 @end smallexample
15102 @item Compile the files generated by the binder
15104 @smallexample
15105 $ gcc -c b~interface.adb
15106 @end smallexample
15108 @item Create the library;
15110 The procedure is identical to the procedure explained in
15111 @ref{Creating an Ada Library},
15112 except that @file{b~interface.o} needs to be added to
15113 the list of objects.
15115 @smallexample
15116 # create an archive file
15117 $ ar cr libmylib.a b~interface.o <other object files>
15119 # create a shared library
15120 $ gcc -shared -o libmylib.so b~interface.o <other object files>
15121 @end smallexample
15123 @item Provide a "foreign" view of the library interface;
15125 The example below shows the content of @code{mylib_interface.h} (note
15126 that there is no rule for the naming of this file, any name can be used)
15127 @smallexample
15128 /* the library elaboration procedure */
15129 extern void mylibinit (void);
15131 /* the library finalization procedure */
15132 extern void mylibfinal (void);
15134 /* the interface exported by the library */
15135 extern void do_something (void);
15136 extern void do_something_else (void);
15137 @end smallexample
15138 @end itemize
15140 @subsection Using the Library
15142 @noindent
15143 Libraries built as explained above can be used from any program, provided
15144 that the elaboration procedures (named @code{mylibinit} in the previous
15145 example) are called before the library services are used. Any number of
15146 libraries can be used simultaneously, as long as the elaboration
15147 procedure of each library is called.
15149 Below is an example of C program that uses our @code{mylib} library.
15151 @smallexample
15152 #include "mylib_interface.h"
15155 main (void)
15157    /* First, elaborate the library before using it */
15158    mylibinit ();
15160    /* Main program, using the library exported entities */
15161    do_something ();
15162    do_something_else ();
15164    /* Library finalization at the end of the program */
15165    mylibfinal ();
15166    return 0;
15168 @end smallexample
15170 @noindent
15171 Note that this same library can be used from an equivalent Ada main
15172 program. In addition, if the libraries are installed as detailed in
15173 @ref{Installing an Ada Library}, it is not necessary to invoke the
15174 library elaboration and finalization routines. The binder will ensure
15175 that this is done as part of the main program elaboration and
15176 finalization phases.
15178 @subsection The Finalization Phase
15180 @noindent
15181 Invoking any library finalization procedure generated by @code{gnatbind}
15182 shuts down the Ada run time permanently. Consequently, the finalization
15183 of all Ada libraries must be performed at the end of the program. No
15184 call to these libraries nor the Ada run time should be made past the
15185 finalization phase.
15187 @subsection Restrictions in Libraries
15189 @noindent
15190 The pragmas listed below should be used with caution inside libraries,
15191 as they can create incompatibilities with other Ada libraries:
15192 @itemize @bullet
15193 @item pragma @code{Locking_Policy}
15194 @item pragma @code{Queuing_Policy}
15195 @item pragma @code{Task_Dispatching_Policy}
15196 @item pragma @code{Unreserve_All_Interrupts}
15197 @end itemize
15198 When using a library that contains such pragmas, the user must make sure
15199 that all libraries use the same pragmas with the same values. Otherwise,
15200 a @code{Program_Error} will
15201 be raised during the elaboration of the conflicting
15202 libraries. The usage of these pragmas and its consequences for the user
15203 should therefore be well documented.
15205 Similarly, the traceback in exception occurrences mechanism should be
15206 enabled or disabled in a consistent manner across all libraries.
15207 Otherwise, a Program_Error will be raised during the elaboration of the
15208 conflicting libraries.
15210 If the @code{'Version} and @code{'Body_Version}
15211 attributes are used inside a library, then it is necessary to
15212 perform a @code{gnatbind} step that mentions all ali files in all
15213 libraries, so that version identifiers can be properly computed.
15214 In practice these attributes are rarely used, so this is unlikely
15215 to be a consideration.
15217 @node  Rebuilding the GNAT Run-Time Library
15218 @section Rebuilding the GNAT Run-Time Library
15220 @noindent
15221 It may be useful to recompile the GNAT library in various contexts, the
15222 most important one being the use of partition-wide configuration pragmas
15223 such as Normalize_Scalar. A special Makefile called
15224 @code{Makefile.adalib} is provided to that effect and can be found in
15225 the directory containing the GNAT library. The location of this
15226 directory depends on the way the GNAT environment has been installed and can
15227 be determined by means of the command:
15229 @smallexample
15230 $ gnatls -v
15231 @end smallexample
15233 @noindent
15234 The last entry in the object search path usually contains the
15235 gnat library. This Makefile contains its own documentation and in
15236 particular the set of instructions needed to rebuild a new library and
15237 to use it.
15239 @node Using the GNU make Utility
15240 @chapter Using the GNU @code{make} Utility
15241 @findex make
15243 @noindent
15244 This chapter offers some examples of makefiles that solve specific
15245 problems. It does not explain how to write a makefile (see the GNU make
15246 documentation), nor does it try to replace the @code{gnatmake} utility
15247 (@pxref{The GNAT Make Program gnatmake}).
15249 All the examples in this section are specific to the GNU version of
15250 make. Although @code{make} is a standard utility, and the basic language
15251 is the same, these examples use some advanced features found only in
15252 @code{GNU make}.
15254 @menu
15255 * Using gnatmake in a Makefile::
15256 * Automatically Creating a List of Directories::
15257 * Generating the Command Line Switches::
15258 * Overcoming Command Line Length Limits::
15259 @end menu
15261 @node Using gnatmake in a Makefile
15262 @section Using gnatmake in a Makefile
15263 @findex makefile
15264 @cindex GNU make
15266 @noindent
15267 Complex project organizations can be handled in a very powerful way by
15268 using GNU make combined with gnatmake. For instance, here is a Makefile
15269 which allows you to build each subsystem of a big project into a separate
15270 shared library. Such a makefile allows you to significantly reduce the link
15271 time of very big applications while maintaining full coherence at
15272 each step of the build process.
15274 The list of dependencies are handled automatically by
15275 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
15276 the appropriate directories.
15278 Note that you should also read the example on how to automatically
15279 create the list of directories (@pxref{Automatically Creating a List of Directories})
15280 which might help you in case your project has a lot of
15281 subdirectories.
15283 @smallexample
15284 @iftex
15285 @leftskip=0cm
15286 @font@heightrm=cmr8
15287 @heightrm
15288 @end iftex
15289 ## This Makefile is intended to be used with the following directory
15290 ## configuration:
15291 ##  - The sources are split into a series of csc (computer software components)
15292 ##    Each of these csc is put in its own directory.
15293 ##    Their name are referenced by the directory names.
15294 ##    They will be compiled into shared library (although this would also work
15295 ##    with static libraries
15296 ##  - The main program (and possibly other packages that do not belong to any
15297 ##    csc is put in the top level directory (where the Makefile is).
15298 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
15299 ##                    \_ second_csc (sources) __ lib (will contain the library)
15300 ##                    \_ ...
15301 ## Although this Makefile is build for shared library, it is easy to modify
15302 ## to build partial link objects instead (modify the lines with -shared and
15303 ## gnatlink below)
15305 ## With this makefile, you can change any file in the system or add any new
15306 ## file, and everything will be recompiled correctly (only the relevant shared
15307 ## objects will be recompiled, and the main program will be re-linked).
15309 # The list of computer software component for your project. This might be
15310 # generated automatically.
15311 CSC_LIST=aa bb cc
15313 # Name of the main program (no extension)
15314 MAIN=main
15316 # If we need to build objects with -fPIC, uncomment the following line
15317 #NEED_FPIC=-fPIC
15319 # The following variable should give the directory containing libgnat.so
15320 # You can get this directory through 'gnatls -v'. This is usually the last
15321 # directory in the Object_Path.
15322 GLIB=...
15324 # The directories for the libraries
15325 # (This macro expands the list of CSC to the list of shared libraries, you
15326 # could simply use the expanded form :
15327 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
15328 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
15330 $@{MAIN@}: objects $@{LIB_DIR@}
15331     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
15332     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
15334 objects::
15335     # recompile the sources
15336     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
15338 # Note: In a future version of GNAT, the following commands will be simplified
15339 # by a new tool, gnatmlib
15340 $@{LIB_DIR@}:
15341     mkdir -p $@{dir $@@ @}
15342     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
15343     cd $@{dir $@@ @}; cp -f ../*.ali .
15345 # The dependencies for the modules
15346 # Note that we have to force the expansion of *.o, since in some cases make won't
15347 # be able to do it itself.
15348 aa/lib/libaa.so: $@{wildcard aa/*.o@}
15349 bb/lib/libbb.so: $@{wildcard bb/*.o@}
15350 cc/lib/libcc.so: $@{wildcard cc/*.o@}
15352 # Make sure all of the shared libraries are in the path before starting the
15353 # program
15354 run::
15355     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
15357 clean::
15358     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
15359     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
15360     $@{RM@} $@{CSC_LIST:%=%/*.o@}
15361     $@{RM@} *.o *.ali $@{MAIN@}
15362 @end smallexample
15364 @node Automatically Creating a List of Directories
15365 @section Automatically Creating a List of Directories
15367 @noindent
15368 In most makefiles, you will have to specify a list of directories, and
15369 store it in a variable. For small projects, it is often easier to
15370 specify each of them by hand, since you then have full control over what
15371 is the proper order for these directories, which ones should be
15372 included...
15374 However, in larger projects, which might involve hundreds of
15375 subdirectories, it might be more convenient to generate this list
15376 automatically.
15378 The example below presents two methods. The first one, although less
15379 general, gives you more control over the list. It involves wildcard
15380 characters, that are automatically expanded by @code{make}. Its
15381 shortcoming is that you need to explicitly specify some of the
15382 organization of your project, such as for instance the directory tree
15383 depth, whether some directories are found in a separate tree,...
15385 The second method is the most general one. It requires an external
15386 program, called @code{find}, which is standard on all Unix systems. All
15387 the directories found under a given root directory will be added to the
15388 list.
15390 @smallexample
15391 @iftex
15392 @leftskip=0cm
15393 @font@heightrm=cmr8
15394 @heightrm
15395 @end iftex
15396 # The examples below are based on the following directory hierarchy:
15397 # All the directories can contain any number of files
15398 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
15399 #                       ->  ab
15400 #                       ->  ac
15401 #                ->  b  ->  ba  ->  baa
15402 #                       ->  bb
15403 #                       ->  bc
15404 # This Makefile creates a variable called DIRS, that can be reused any time
15405 # you need this list (see the other examples in this section)
15407 # The root of your project's directory hierarchy
15408 ROOT_DIRECTORY=.
15410 ####
15411 # First method: specify explicitly the list of directories
15412 # This allows you to specify any subset of all the directories you need.
15413 ####
15415 DIRS := a/aa/ a/ab/ b/ba/
15417 ####
15418 # Second method: use wildcards
15419 # Note that the argument(s) to wildcard below should end with a '/'.
15420 # Since wildcards also return file names, we have to filter them out
15421 # to avoid duplicate directory names.
15422 # We thus use make's @code{dir} and @code{sort} functions.
15423 # It sets DIRs to the following value (note that the directories aaa and baa
15424 # are not given, unless you change the arguments to wildcard).
15425 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
15426 ####
15428 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@}
15430 ####
15431 # Third method: use an external program
15432 # This command is much faster if run on local disks, avoiding NFS slowdowns.
15433 # This is the most complete command: it sets DIRs to the following value:
15434 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
15435 ####
15437 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
15439 @end smallexample
15441 @node Generating the Command Line Switches
15442 @section Generating the Command Line Switches
15444 @noindent
15445 Once you have created the list of directories as explained in the
15446 previous section (@pxref{Automatically Creating a List of Directories}),
15447 you can easily generate the command line arguments to pass to gnatmake.
15449 For the sake of completeness, this example assumes that the source path
15450 is not the same as the object path, and that you have two separate lists
15451 of directories.
15453 @smallexample
15454 # see "Automatically creating a list of directories" to create
15455 # these variables
15456 SOURCE_DIRS=
15457 OBJECT_DIRS=
15459 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
15460 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
15462 all:
15463         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
15464 @end smallexample
15466 @node Overcoming Command Line Length Limits
15467 @section Overcoming Command Line Length Limits
15469 @noindent
15470 One problem that might be encountered on big projects is that many
15471 operating systems limit the length of the command line. It is thus hard to give
15472 gnatmake the list of source and object directories.
15474 This example shows how you can set up environment variables, which will
15475 make @code{gnatmake} behave exactly as if the directories had been
15476 specified on the command line, but have a much higher length limit (or
15477 even none on most systems).
15479 It assumes that you have created a list of directories in your Makefile,
15480 using one of the methods presented in
15481 @ref{Automatically Creating a List of Directories}.
15482 For the sake of completeness, we assume that the object
15483 path (where the ALI files are found) is different from the sources patch.
15485 Note a small trick in the Makefile below: for efficiency reasons, we
15486 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
15487 expanded immediately by @code{make}. This way we overcome the standard
15488 make behavior which is to expand the variables only when they are
15489 actually used.
15491 @smallexample
15492 @iftex
15493 @leftskip=0cm
15494 @font@heightrm=cmr8
15495 @heightrm
15496 @end iftex
15497 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
15498 # This is the same thing as putting the -I arguments on the command line.
15499 # (the equivalent of using -aI on the command line would be to define
15500 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
15501 # You can of course have different values for these variables.
15503 # Note also that we need to keep the previous values of these variables, since
15504 # they might have been set before running 'make' to specify where the GNAT
15505 # library is installed.
15507 # see "Automatically creating a list of directories" to create these
15508 # variables
15509 SOURCE_DIRS=
15510 OBJECT_DIRS=
15512 empty:=
15513 space:=$@{empty@} $@{empty@}
15514 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
15515 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
15516 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
15517 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
15518 export ADA_INCLUDE_PATH
15519 export ADA_OBJECT_PATH
15521 all:
15522         gnatmake main_unit
15523 @end smallexample
15525 @ifclear vxworks
15526 @node Finding Memory Problems with gnatmem
15527 @chapter Finding Memory Problems with @code{gnatmem}
15528 @findex gnatmem
15530 @noindent
15531 @code{gnatmem}, is a tool that monitors dynamic allocation and
15532 deallocation activity in a program, and displays information about
15533 incorrect deallocations and possible sources of memory leaks. Gnatmem
15534 provides three type of information:
15535 @itemize @bullet
15536 @item
15537 General information concerning memory management, such as the total
15538 number of allocations and deallocations, the amount of allocated
15539 memory and the high water mark, i.e. the largest amount of allocated
15540 memory in the course of program execution.
15542 @item
15543 Backtraces for all incorrect deallocations, that is to say deallocations
15544 which do not correspond to a valid allocation.
15546 @item
15547 Information on each allocation that is potentially the origin of a memory
15548 leak.
15549 @end itemize
15551 The @code{gnatmem} command has two modes. It can be used with @code{gdb}
15552 or with instrumented allocation and deallocation routines. The later
15553 mode is called the @code{GMEM} mode. Both modes produce the very same
15554 output.
15556 @menu
15557 * Running gnatmem (GDB Mode)::
15558 * Running gnatmem (GMEM Mode)::
15559 * Switches for gnatmem::
15560 * Examples of gnatmem Usage::
15561 * GDB and GMEM Modes::
15562 * Implementation Note::
15563 @end menu
15565 @node Running gnatmem (GDB Mode)
15566 @section Running @code{gnatmem} (GDB Mode)
15568 @noindent
15569 The @code{gnatmem} command has the form
15571 @smallexample
15572    $ gnatmem [-q] [n] [-o file] user_program [program_arg]*
15574    $ gnatmem [-q] [n] -i file
15575 @end smallexample
15577 @noindent
15578 Gnatmem must be supplied with the executable to examine, followed by its
15579 run-time inputs. For example, if a program is executed with the command:
15580 @smallexample
15581 $ my_program arg1 arg2
15582 @end smallexample
15583 then it can be run under @code{gnatmem} control using the command:
15584 @smallexample
15585 $ gnatmem my_program arg1 arg2
15586 @end smallexample
15588 The program is transparently executed under the control of the debugger
15589 @ref{The GNAT Debugger GDB}. This does not affect the behavior
15590 of the program, except for sensitive real-time programs. When the program
15591 has completed execution, @code{gnatmem} outputs a report containing general
15592 allocation/deallocation information and potential memory leak.
15593 For better results, the user program should be compiled with
15594 debugging options @ref{Switches for gcc}.
15596 Here is a simple example of use:
15598 *************** debut cc
15599 @smallexample
15600 $ gnatmem test_gm
15602 Global information
15603 ------------------
15604    Total number of allocations        :  45
15605    Total number of deallocations      :   6
15606    Final Water Mark (non freed mem)   :  11.29 Kilobytes
15607    High Water Mark                    :  11.40 Kilobytes
15612 Allocation Root # 2
15613 -------------------
15614  Number of non freed allocations    :  11
15615  Final Water Mark (non freed mem)   :   1.16 Kilobytes
15616  High Water Mark                    :   1.27 Kilobytes
15617  Backtrace                          :
15618    test_gm.adb:23 test_gm.alloc
15622 @end smallexample
15624 The first block of output give general information. In this case, the
15625 Ada construct "@b{new}" was executed 45 times, and only 6 calls to an
15626 unchecked deallocation routine occurred.
15628 Subsequent paragraphs display  information on all allocation roots.
15629 An allocation root is a specific point in the execution of the program
15630 that generates some dynamic allocation, such as a "@b{new}" construct. This
15631 root is represented by an execution backtrace (or subprogram call
15632 stack). By default the backtrace depth for allocations roots is 1, so
15633 that a root corresponds exactly to a source location. The backtrace can
15634 be made deeper, to make the root more specific.
15636 @node Running gnatmem (GMEM Mode)
15637 @section Running @code{gnatmem} (GMEM Mode)
15638 @cindex @code{GMEM} (@code{gnatmem})
15640 @noindent
15641 The @code{gnatmem} command has the form
15643 @smallexample
15644    $ gnatmem [-q] [n] -i gmem.out user_program [program_arg]*
15645 @end smallexample
15647 The program must have been linked with the instrumented version of the
15648 allocation and deallocation routines. This is done with linking with the
15649 @file{libgmem.a} library. For better results, the user program should be
15650 compiled with debugging options @ref{Switches for gcc}. For example to
15651 build @file{my_program}:
15653 @smallexample
15654 $ gnatmake -g my_program -largs -lgmem
15655 @end smallexample
15657 @noindent
15658 When running @file{my_program} the file @file{gmem.out} is produced. This file
15659 contains information about all allocations and deallocations done by the
15660 program. It is produced by the instrumented allocations and
15661 deallocations routines and will be used by @code{gnatmem}.
15663 @noindent
15664 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
15665 examine followed by its run-time inputs. For example, if a program is
15666 executed with the command:
15667 @smallexample
15668 $ my_program arg1 arg2
15669 @end smallexample
15670 then @file{gmem.out} can be analysed by @code{gnatmem} using the command:
15671 @smallexample
15672 $ gnatmem -i gmem.out my_program arg1 arg2
15673 @end smallexample
15675 @node Switches for gnatmem
15676 @section Switches for @code{gnatmem}
15678 @noindent
15679 @code{gnatmem} recognizes the following switches:
15681 @table @code
15683 @item @code{-q}
15684 @cindex @code{-q} (@code{gnatmem})
15685 Quiet. Gives the minimum output needed to identify the origin of the
15686 memory leaks. Omit statistical information.
15688 @item @code{n}
15689 @cindex @code{n} (@code{gnatmem})
15690 N is an integer literal (usually between 1 and 10) which controls the
15691 depth of the backtraces defining allocation root. The default value for
15692 N is 1. The deeper the backtrace, the more precise the localization of
15693 the root. Note that the total number of roots can depend on this
15694 parameter.
15696 @item @code{-o file}
15697 @cindex @code{-o} (@code{gnatmem})
15698 Direct the gdb output to the specified file. The @code{gdb} script used
15699 to generate this output is also saved in the file @file{gnatmem.tmp}.
15701 @item @code{-i file}
15702 @cindex @code{-i} (@code{gnatmem})
15703 Do the @code{gnatmem} processing starting from @file{file} which has
15704 been generated by a previous call to @code{gnatmem} with the -o
15705 switch or @file{gmem.out} produced by @code{GMEM} mode. This is useful
15706 for post mortem processing.
15708 @end table
15710 @node Examples of gnatmem Usage
15711 @section Example of @code{gnatmem} Usage
15713 @noindent
15714 This section is based on the @code{GDB} mode of @code{gnatmem}. The same
15715 results can be achieved using @code{GMEM} mode. See section
15716 @ref{Running gnatmem (GMEM Mode)}.
15718 @noindent
15719 The first example shows the use of @code{gnatmem}
15720 on a simple leaking program.
15721 Suppose that we have the following Ada program:
15723 @smallexample
15724 @group
15725 @cartouche
15726 @b{with} Unchecked_Deallocation;
15727 @b{procedure} Test_Gm @b{is}
15729    @b{type} T @b{is array} (1..1000) @b{of} Integer;
15730    @b{type} Ptr @b{is access} T;
15731    @b{procedure} Free @b{is new} Unchecked_Deallocation (T, Ptr);
15732    A : Ptr;
15734    @b{procedure} My_Alloc @b{is}
15735    @b{begin}
15736       A := @b{new} T;
15737    @b{end} My_Alloc;
15739    @b{procedure} My_DeAlloc @b{is}
15740       B : Ptr := A;
15741    @b{begin}
15742       Free (B);
15743    @b{end} My_DeAlloc;
15745 @b{begin}
15746    My_Alloc;
15747    @b{for} I @b{in} 1 .. 5 @b{loop}
15748       @b{for} J @b{in} I .. 5 @b{loop}
15749          My_Alloc;
15750       @b{end loop};
15751       My_Dealloc;
15752    @b{end loop};
15753 @b{end};
15754 @end cartouche
15755 @end group
15756 @end smallexample
15758 @noindent
15759 The program needs to be compiled with debugging option:
15761 @smallexample
15762 $ gnatmake -g test_gm
15763 @end smallexample
15765 @code{gnatmem} is invoked simply with
15766 @smallexample
15767 $ gnatmem test_gm
15768 @end smallexample
15770 @noindent
15771 which produces the following output:
15773 @smallexample
15774 Global information
15775 ------------------
15776    Total number of allocations        :  18
15777    Total number of deallocations      :   5
15778    Final Water Mark (non freed mem)   :  53.00 Kilobytes
15779    High Water Mark                    :  56.90 Kilobytes
15781 Allocation Root # 1
15782 -------------------
15783  Number of non freed allocations    :  11
15784  Final Water Mark (non freed mem)   :  42.97 Kilobytes
15785  High Water Mark                    :  46.88 Kilobytes
15786  Backtrace                          :
15787    test_gm.adb:11 test_gm.my_alloc
15789 Allocation Root # 2
15790 -------------------
15791  Number of non freed allocations    :   1
15792  Final Water Mark (non freed mem)   :  10.02 Kilobytes
15793  High Water Mark                    :  10.02 Kilobytes
15794  Backtrace                          :
15795    s-secsta.adb:81 system.secondary_stack.ss_init
15797 Allocation Root # 3
15798 -------------------
15799  Number of non freed allocations    :   1
15800  Final Water Mark (non freed mem)   :  12 Bytes
15801  High Water Mark                    :  12 Bytes
15802  Backtrace                          :
15803    s-secsta.adb:181 system.secondary_stack.ss_init
15804 @end smallexample
15806 @noindent
15807 Note that the GNAT run time contains itself a certain number of
15808 allocations that have no  corresponding deallocation,
15809 as shown here for root #2 and root
15810 #1. This is a normal behavior when the number of non freed allocations
15811 is one, it locates dynamic data structures that the run time needs for
15812 the complete lifetime of the program. Note also that there is only one
15813 allocation root in the user program with a single line back trace:
15814 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
15815 program shows that 'My_Alloc' is called at 2 different points in the
15816 source (line 21 and line 24). If those two allocation roots need to be
15817 distinguished, the backtrace depth parameter can be used:
15819 @smallexample
15820 $ gnatmem 3 test_gm
15821 @end smallexample
15823 @noindent
15824 which will give the following output:
15826 @smallexample
15827 Global information
15828 ------------------
15829    Total number of allocations        :  18
15830    Total number of deallocations      :   5
15831    Final Water Mark (non freed mem)   :  53.00 Kilobytes
15832    High Water Mark                    :  56.90 Kilobytes
15834 Allocation Root # 1
15835 -------------------
15836  Number of non freed allocations    :  10
15837  Final Water Mark (non freed mem)   :  39.06 Kilobytes
15838  High Water Mark                    :  42.97 Kilobytes
15839  Backtrace                          :
15840    test_gm.adb:11 test_gm.my_alloc
15841    test_gm.adb:24 test_gm
15842    b_test_gm.c:52 main
15844 Allocation Root # 2
15845 -------------------
15846  Number of non freed allocations    :   1
15847  Final Water Mark (non freed mem)   :  10.02 Kilobytes
15848  High Water Mark                    :  10.02 Kilobytes
15849  Backtrace                          :
15850    s-secsta.adb:81  system.secondary_stack.ss_init
15851    s-secsta.adb:283 <system__secondary_stack___elabb>
15852    b_test_gm.c:33   adainit
15854 Allocation Root # 3
15855 -------------------
15856  Number of non freed allocations    :   1
15857  Final Water Mark (non freed mem)   :   3.91 Kilobytes
15858  High Water Mark                    :   3.91 Kilobytes
15859  Backtrace                          :
15860    test_gm.adb:11 test_gm.my_alloc
15861    test_gm.adb:21 test_gm
15862    b_test_gm.c:52 main
15864 Allocation Root # 4
15865 -------------------
15866  Number of non freed allocations    :   1
15867  Final Water Mark (non freed mem)   :  12 Bytes
15868  High Water Mark                    :  12 Bytes
15869  Backtrace                          :
15870    s-secsta.adb:181 system.secondary_stack.ss_init
15871    s-secsta.adb:283 <system__secondary_stack___elabb>
15872    b_test_gm.c:33   adainit
15873 @end smallexample
15875 @noindent
15876 The allocation root #1 of the first example has been split in 2 roots #1
15877 and #3 thanks to the more precise associated backtrace.
15879 @node GDB and GMEM Modes
15880 @section GDB and GMEM Modes
15882 @noindent
15883 The main advantage of the @code{GMEM} mode is that it is a lot faster than the
15884 @code{GDB} mode where the application must be monitored by a @code{GDB} script.
15885 But the @code{GMEM} mode is available only for DEC Unix, Linux x86,
15886 Solaris (sparc and x86) and Windows 95/98/NT/2000 (x86).
15888 @noindent
15889 The main advantage of the @code{GDB} mode is that it is available on all
15890 supported platforms. But it can be very slow if the application does a
15891 lot of allocations and deallocations.
15893 @node Implementation Note
15894 @section Implementation Note
15896 @menu
15897 * gnatmem Using GDB Mode::
15898 * gnatmem Using GMEM Mode::
15899 @end menu
15901 @node gnatmem Using GDB Mode
15902 @subsection @code{gnatmem} Using @code{GDB} Mode
15904 @noindent
15905 @code{gnatmem} executes the user program under the control of @code{GDB} using
15906 a script that sets breakpoints and gathers information on each dynamic
15907 allocation and deallocation. The output of the script is then analyzed
15908 by @code{gnatmem}
15909 in order to locate memory leaks and their origin in the
15910 program. Gnatmem works by recording each address returned by the
15911 allocation procedure (@code{__gnat_malloc})
15912 along with the backtrace at the
15913 allocation point. On each deallocation, the deallocated address is
15914 matched with the corresponding allocation. At the end of the processing,
15915 the unmatched allocations are considered potential leaks. All the
15916 allocations associated with the same backtrace are grouped together and
15917 form an allocation root. The allocation roots are then sorted so that
15918 those with the biggest number of unmatched allocation are printed
15919 first. A delicate aspect of this technique is to distinguish between the
15920 data produced by the user program and the data produced by the gdb
15921 script. Currently, on systems that allow probing the terminal, the gdb
15922 command "tty" is used to force the program output to be redirected to the
15923 current terminal while the @code{gdb} output is directed to a file or to a
15924 pipe in order to be processed subsequently by @code{gnatmem}.
15926 @node gnatmem Using GMEM Mode
15927 @subsection @code{gnatmem} Using @code{GMEM} Mode
15929 @noindent
15930 This mode use the same algorithm to detect memory leak as the @code{GDB}
15931 mode of @code{gnatmem}, the only difference is in the way data are
15932 gathered. In @code{GMEM} mode the program is linked with instrumented
15933 version of @code{__gnat_malloc} and @code{__gnat_free}
15934 routines. Information needed to find memory leak are recorded by these
15935 routines in file @file{gmem.out}. This mode also require that the stack
15936 traceback be available, this is only implemented on some platforms
15937 @ref{GDB and GMEM Modes}.
15939 @end ifclear
15940 @end ifclear
15942 @node Finding Memory Problems with GNAT Debug Pool
15943 @chapter Finding Memory Problems with GNAT Debug Pool
15944 @findex Debug Pool
15945 @cindex storage, pool, memory corruption
15947 @noindent
15948 The use of unchecked deallocation and unchecked conversion can easily
15949 lead to incorrect memory references. The problems generated by such
15950 references are usually difficult to tackle because the symptoms can be
15951 very remote from the origin of the problem. In such cases, it is
15952 very helpful to detect the problem as early as possible. This is the
15953 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
15955 @noindent
15956 In order to use the GNAT specific debugging pool, the user must
15957 associate a debug pool object with each of the access types that may be
15958 related to suspected memory problems. See Ada Reference Manual
15959 13.11.
15960 @smallexample
15961 @b{type} Ptr @b{is} @b{access} Some_Type;
15962 Pool : GNAT.Debug_Pools.Debug_Pool;
15963 @b{for} Ptr'Storage_Pool @b{use} Pool;
15964 @end smallexample
15966 @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of
15967 pool: the Checked_Pool. Such pools, like standard Ada storage pools,
15968 allow the user to redefine allocation and deallocation strategies. They
15969 also provide a checkpoint for each dereference, through the use of
15970 the primitive operation @code{Dereference} which is implicitly called at
15971 each dereference of an access value.
15973 Once an access type has been associated with a debug pool, operations on
15974 values of the type may raise four distinct exceptions,
15975 which correspond to four potential kinds of memory corruption:
15976 @itemize @bullet
15977 @item
15978 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
15979 @item
15980 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
15981 @item
15982 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
15983 @item
15984 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
15985 @end itemize
15987 @noindent
15988 For types associated with a Debug_Pool, dynamic allocation is performed using
15989 the standard
15990 GNAT allocation routine. References to all allocated chunks of memory
15991 are kept in an internal dictionary. The deallocation strategy consists
15992 in not releasing the memory to the underlying system but rather to fill
15993 it with a memory pattern easily recognizable during debugging sessions:
15994 The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#.
15995 Upon each dereference, a check is made that the access value denotes a properly
15996 allocated memory location. Here is a complete example of use of
15997 @code{Debug_Pools}, that includes typical instances of  memory corruption:
15998 @smallexample
15999 @iftex
16000 @leftskip=0cm
16001 @end iftex
16002 @b{with} Gnat.Io; @b{use} Gnat.Io;
16003 @b{with} Unchecked_Deallocation;
16004 @b{with} Unchecked_Conversion;
16005 @b{with} GNAT.Debug_Pools;
16006 @b{with} System.Storage_Elements;
16007 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
16008 @b{procedure} Debug_Pool_Test @b{is}
16010    @b{type} T @b{is} @b{access} Integer;
16011    @b{type} U @b{is} @b{access} @b{all} T;
16013    P : GNAT.Debug_Pools.Debug_Pool;
16014    @b{for} T'Storage_Pool @b{use} P;
16016    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
16017    @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
16018    A, B : @b{aliased} T;
16020    @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
16022 @b{begin}
16023    Info (P);
16024    A := @b{new} Integer;
16025    B := @b{new} Integer;
16026    B := A;
16027    Info (P);
16028    Free (A);
16029    @b{begin}
16030       Put_Line (Integer'Image(B.@b{all}));
16031    @b{exception}
16032       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16033    @b{end};
16034    @b{begin}
16035       Free (B);
16036    @b{exception}
16037       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16038    @b{end};
16039    B := UC(A'Access);
16040    @b{begin}
16041       Put_Line (Integer'Image(B.@b{all}));
16042    @b{exception}
16043       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16044    @b{end};
16045    @b{begin}
16046       Free (B);
16047    @b{exception}
16048       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16049    @b{end};
16050    Info (P);
16051 @b{end} Debug_Pool_Test;
16052 @end smallexample
16053 @noindent
16054 The debug pool mechanism provides the following precise diagnostics on the
16055 execution of this erroneous program:
16056 @smallexample
16057 Debug Pool info:
16058   Total allocated bytes :  0
16059   Total deallocated bytes :  0
16060   Current Water Mark:  0
16061   High Water Mark:  0
16063 Debug Pool info:
16064   Total allocated bytes :  8
16065   Total deallocated bytes :  0
16066   Current Water Mark:  8
16067   High Water Mark:  8
16069 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16070 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16071 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16072 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16073 Debug Pool info:
16074   Total allocated bytes :  8
16075   Total deallocated bytes :  4
16076   Current Water Mark:  4
16077   High Water Mark:  8
16079 @end smallexample
16081 @node Creating Sample Bodies Using gnatstub
16082 @chapter Creating Sample Bodies Using @code{gnatstub}
16083 @findex gnatstub
16085 @noindent
16086 @code{gnatstub} creates body stubs, that is, empty but compilable bodies
16087 for library unit declarations.
16089 To create a body stub, @code{gnatstub} has to compile the library
16090 unit declaration. Therefore, bodies can be created only for legal
16091 library units. Moreover, if a library unit depends semantically upon
16092 units located outside the current directory, you have to provide
16093 the source search path when calling @code{gnatstub}, see the description
16094 of @code{gnatstub} switches below.
16096 @menu
16097 * Running gnatstub::
16098 * Switches for gnatstub::
16099 @end menu
16101 @node Running gnatstub
16102 @section Running @code{gnatstub}
16104 @noindent
16105 @code{gnatstub} has the command-line interface of the form
16107 @smallexample
16108 $ gnatstub [switches] filename [directory]
16109 @end smallexample
16111 @noindent
16112 where
16113 @table @code
16114 @item filename
16115 is the name of the source file that contains a library unit declaration
16116 for which a body must be created. This name should follow the GNAT file name
16117 conventions. No crunching is allowed for this file name. The file
16118 name may contain the path information.
16120 @item directory
16121 indicates the directory to place a body stub (default is the
16122 current directory)
16124 @item switches
16125 is an optional sequence of switches as described in the next section
16126 @end table
16128 @node Switches for gnatstub
16129 @section Switches for @code{gnatstub}
16131 @table @code
16133 @item ^-f^/FULL^
16134 If the destination directory already contains a file with a name of the body file
16135 for the argument spec file, replace it with the generated body stub.
16137 @item ^-hs^/HEADER=SPEC^
16138 Put the comment header (i.e. all the comments preceding the
16139 compilation unit) from the source of the library unit declaration
16140 into the body stub.
16142 @item ^-hg^/HEADER=GENERAL^
16143 Put a sample comment header into the body stub.
16145 @item -IDIR
16146 @itemx ^-I-^/NOCURRENT_DIRECTORY^
16147 These switches have the same meaning as in calls to gcc.
16148 They define the source search path in the call to gcc issued
16149 by @code{gnatstub} to compile an argument source file.
16151 @item ^-i^/INDENTATION=^@var{n}
16152 (@var{n} is a decimal natural number). Set the indentation level in the
16153 generated body sample to n, '^-i0^/INDENTATION=0^' means "no indentation",
16154 the default indentation is 3.
16156 @item ^-k^/TREE_FILE=SAVE^
16157 Do not remove the tree file (i.e. the snapshot of the compiler internal
16158 structures used by @code{gnatstub}) after creating the body stub.
16160 @item ^-l^/LINE_LENGTH=^@var{n}
16161 (@var{n} is a decimal positive number) Set the maximum line length in the
16162 body stub to n, the default is 78.
16164 @item ^-q^/QUIET^
16165 Quiet mode: do not generate a confirmation when a body is
16166 successfully created or a message when a body is not required for an
16167 argument unit.
16169 @item ^-r^/TREE_FILE=REUSE^
16170 Reuse the tree file (if it exists) instead of creating it: instead of
16171 creating the tree file for the library unit declaration, gnatstub
16172 tries to find it in the current directory and use it for creating
16173 a body. If the tree file is not found, no body is created. @code{^-r^/REUSE^}
16174 also implies @code{^-k^/SAVE^}, whether or not
16175 @code{^-k^/SAVE^} is set explicitly.
16177 @item ^-t^/TREE_FILE=OVERWRITE^
16178 Overwrite the existing tree file: if the current directory already
16179 contains the file which, according to the GNAT file name rules should
16180 be considered as a tree file for the argument source file, gnatstub
16181 will refuse to create the tree file needed to create a body sampler,
16182 unless @code{-t} option is set
16184 @item ^-v^/VERBOSE^
16185 Verbose mode: generate version information.
16187 @end table
16189 @node Reducing the Size of Ada Executables with gnatelim
16190 @chapter Reducing the Size of Ada Executables with @code{gnatelim}
16191 @findex gnatelim
16193 @menu
16194 * About gnatelim::
16195 * Eliminate Pragma::
16196 * Tree Files::
16197 * Preparing Tree and Bind Files for gnatelim::
16198 * Running gnatelim::
16199 * Correcting the List of Eliminate Pragmas::
16200 * Making Your Executables Smaller::
16201 * Summary of the gnatelim Usage Cycle::
16202 @end menu
16204 @node About gnatelim
16205 @section About @code{gnatelim}
16207 @noindent
16208 When a program shares a set of Ada
16209 packages with other programs, it may happen that this program uses
16210 only a fraction of the subprograms defined in these packages. The code
16211 created for these unused subprograms increases the size of the executable.
16213 @code{gnatelim} tracks unused subprograms in an Ada program and
16214 outputs a list of GNAT-specific @code{Eliminate} pragmas (see next
16215 section) marking all the subprograms that are declared but never called.
16216 By placing the list of @code{Eliminate} pragmas in the GNAT configuration
16217 file @file{gnat.adc} and recompiling your program, you may decrease the
16218 size of its executable, because the compiler will not generate the code
16219 for 'eliminated' subprograms.
16221 @code{gnatelim} needs as its input data a set of tree files
16222 (see @ref{Tree Files}) representing all the components of a program to
16223 process and a bind file for a main subprogram (see
16224 @ref{Preparing Tree and Bind Files for gnatelim}).
16226 @node Eliminate Pragma
16227 @section @code{Eliminate} Pragma
16228 @findex Eliminate
16230 @noindent
16231 The simplified syntax of the Eliminate pragma used by @code{gnatelim} is:
16233 @smallexample
16234 @cartouche
16235 @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name);
16236 @end cartouche
16237 @end smallexample
16239 @noindent
16240 where
16241 @table @code
16242 @item Library_Unit_Name
16243 full expanded Ada name of a library unit
16245 @item Subprogram_Name
16246 a simple or expanded name of a subprogram declared within this
16247 compilation unit
16249 @end table
16251 @noindent
16252 The effect of an @code{Eliminate} pragma placed in the GNAT configuration
16253 file @file{gnat.adc} is:
16255 @itemize @bullet
16257 @item
16258 If the subprogram @code{Subprogram_Name} is declared within
16259 the library unit @code{Library_Unit_Name}, the compiler will not generate
16260 code for this subprogram. This applies to all overloaded subprograms denoted
16261 by @code{Subprogram_Name}.
16263 @item
16264 If a subprogram marked by the pragma @code{Eliminate} is used (called)
16265 in a program, the compiler will produce an error message in the place where
16266 it is called.
16267 @end itemize
16269 @node Tree Files
16270 @section Tree Files
16271 @cindex Tree file
16273 @noindent
16274 A tree file stores a snapshot of the compiler internal data
16275 structures at the very end of a successful compilation. It contains all the
16276 syntactic and semantic information for the compiled unit and all the
16277 units upon which it depends semantically.
16278 To use tools that make use of tree files, you
16279 need to first produce the right set of tree files.
16281 GNAT produces correct tree files when -gnatt -gnatc options are set
16282 in a gcc call. The tree files have an .adt extension.
16283 Therefore, to produce a tree file for the compilation unit contained in a file
16284 named @file{foo.adb}, you must use the command
16286 @smallexample
16287 $ gcc -c -gnatc -gnatt foo.adb
16288 @end smallexample
16290 @noindent
16291 and you will get the tree file @file{foo.adt}.
16292 compilation.
16294 @node Preparing Tree and Bind Files for gnatelim
16295 @section Preparing Tree and Bind Files for @code{gnatelim}
16297 @noindent
16298 A set of tree files covering the program to be analyzed with
16299 @code{gnatelim} and
16300 the bind file for the main subprogram does not have to
16301 be in the current directory.
16302 '-T' gnatelim option may be used to provide
16303 the search path for tree files, and '-b'
16304 option may be used to point to the bind
16305 file to process (see @ref{Running gnatelim})
16307 If you do not have the appropriate set of tree
16308 files and the right bind file, you
16309 may create them in the current directory using the following procedure.
16311 Let @code{Main_Prog} be the name of a main subprogram, and suppose
16312 this subprogram is in a file named @file{main_prog.adb}.
16314 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
16315 the main subprogram. @code{gnatelim} can work with both Ada and C
16316 bind files; when both are present, it uses the Ada bind file.
16317 The following commands will build the program and create the bind file:
16319 @smallexample
16320 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
16321 $ gnatbind main_prog
16322 @end smallexample
16324 @noindent
16325 To create a minimal set of tree files covering the whole program, call
16326 @code{gnatmake} for this program as follows:
16328 @smallexample
16329 @ifset vms
16330 $ GNAT MAKE /FORCE_COMPILE /ACTIONS=COMPILE /NOLOAD /TREE_OUTPUT MAIN_PROG
16331 @end ifset
16332 @ifclear vms
16333 $ gnatmake -f -c -gnatc -gnatt Main_Prog
16334 @end ifclear
16335 @end smallexample
16337 @noindent
16338 The @code{^-c^/ACTIONS=COMPILE^} gnatmake option turns off the bind and link
16339 steps, that are useless anyway because the sources are compiled with
16340 @option{-gnatc} option which turns off code generation.
16342 The @code{^-f^/FORCE_COMPILE^} gnatmake option forces
16343 recompilation of all the needed sources.
16345 This sequence of actions will create all the data needed by @code{gnatelim}
16346 from scratch and therefore guarantee its consistency. If you would like to
16347 use some existing set of files as @code{gnatelim} output, you must make
16348 sure that the set of files is complete and consistent. You can use the
16349 @code{-m} switch to check if there are missed tree files
16351 Note, that @code{gnatelim} needs neither object nor ALI files.
16353 @node Running gnatelim
16354 @section Running @code{gnatelim}
16356 @noindent
16357 @code{gnatelim} has the following command-line interface:
16359 @smallexample
16360 $ gnatelim [options] name
16361 @end smallexample
16363 @noindent
16364 @code{name} should be a full expanded Ada name of a main subprogram
16365 of a program (partition).
16367 @code{gnatelim} options:
16369 @table @code
16370 @item ^-q^/QUIET^
16371 Quiet mode: by default @code{gnatelim} generates to the standard error
16372 stream a trace of the source file names of the compilation units being
16373 processed. This option turns this trace off.
16375 @item ^-v^/VERBOSE^
16376 Verbose mode: @code{gnatelim} version information is printed as Ada
16377 comments to the standard output stream.
16379 @item ^-a^/ALL^
16380 Also look for subprograms from the GNAT run time that can be eliminated.
16382 @item ^-m^/MISSED^
16383 Check if any tree files are missing for an accurate result.
16385 @item ^-T^/TREE_DIRS=^@var{dir}
16386 When looking for tree files also look in directory @var{dir}
16388 @item ^-b^/BIND_FILE=^@var{bind_file}
16389 Specifies @var{bind_file} as the bind file to process. If not set, the name
16390 of the bind file is computed from the full expanded Ada name of a main subprogram.
16392 @item -d@var{x}
16393 Activate internal debugging switches. @var{x} is a letter or digit, or
16394 string of letters or digits, which specifies the type of debugging
16395 mode desired.  Normally these are used only for internal development
16396 or system debugging purposes. You can find full documentation for these
16397 switches in the body of the @code{Gnatelim.Options} unit in the compiler
16398 source file @file{gnatelim-options.adb}.
16399 @end table
16401 @noindent
16402 @code{gnatelim} sends its output to the standard output stream, and all the
16403 tracing and debug information is sent to the standard error stream.
16404 In order to produce a proper GNAT configuration file
16405 @file{gnat.adc}, redirection must be used:
16407 @smallexample
16408 @ifset vms
16409 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
16410 @end ifset
16411 @ifclear vms
16412 $ gnatelim Main_Prog > gnat.adc
16413 @end ifclear
16414 @end smallexample
16416 @ifclear vms
16417 @noindent
16420 @smallexample
16421 $ gnatelim Main_Prog >> gnat.adc
16422 @end smallexample
16423 @end ifclear
16425 @noindent
16426 In order to append the @code{gnatelim} output to the existing contents of
16427 @file{gnat.adc}.
16429 @node Correcting the List of Eliminate Pragmas
16430 @section Correcting the List of Eliminate Pragmas
16432 @noindent
16433 In some rare cases it may happen that @code{gnatelim} will try to eliminate
16434 subprograms which are actually called in the program. In this case, the
16435 compiler will generate an error message of the form:
16437 @smallexample
16438 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
16439 @end smallexample
16441 @noindent
16442 You will need to manually remove the wrong @code{Eliminate} pragmas from
16443 the @file{gnat.adc} file. It is advised that you recompile your program
16444 from scratch after that because you need a consistent @file{gnat.adc} file
16445 during the entire compilation.
16447 @node Making Your Executables Smaller
16448 @section Making Your Executables Smaller
16450 @noindent
16451 In order to get a smaller executable for your program you now have to
16452 recompile the program completely with the new @file{gnat.adc} file
16453 created by @code{gnatelim} in your current directory:
16455 @smallexample
16456 $ gnatmake ^-f Main_Prog^/FORCE_COMPILE MAIN_PROG^
16457 @end smallexample
16459 @noindent
16460 (you will need @code{^-f^/FORCE_COMPILE^} option for gnatmake to
16461 recompile everything
16462 with the set of pragmas @code{Eliminate} you have obtained with
16463 @code{gnatelim}).
16465 Be aware that the set of @code{Eliminate} pragmas is specific to each
16466 program. It is not recommended to merge sets of @code{Eliminate}
16467 pragmas created for different programs in one @file{gnat.adc} file.
16469 @node Summary of the gnatelim Usage Cycle
16470 @section Summary of the gnatelim Usage Cycle
16472 @noindent
16473 Here is a quick summary of the steps to be taken in order to reduce
16474 the size of your executables with @code{gnatelim}. You may use
16475 other GNAT options to control the optimization level,
16476 to produce the debugging information, to set search path, etc.
16478 @enumerate
16479 @item
16480 Produce a bind file and a set of tree files
16482 @smallexample
16483 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
16484 $ gnatbind main_prog
16485 @ifset vms
16486 $ GNAT MAKE /FORCE_COMPILE /NO_LINK /NOLOAD /TREE_OUTPUT MAIN_PROG
16487 @end ifset
16488 @ifclear vms
16489 $ gnatmake -f -c -gnatc -gnatt Main_Prog
16490 @end ifclear
16491 @end smallexample
16493 @item
16494 Generate a list of @code{Eliminate} pragmas
16495 @smallexample
16496 @ifset vms
16497 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
16498 @end ifset
16499 @ifclear vms
16500 $ gnatelim Main_Prog >[>] gnat.adc
16501 @end ifclear
16502 @end smallexample
16504 @item
16505 Recompile the application
16507 @smallexample
16508 $ gnatmake ^-f Main_Prog^/FORCE_COMPILE MAIN_PROG^
16509 @end smallexample
16511 @end enumerate
16513 @node Other Utility Programs
16514 @chapter Other Utility Programs
16516 @noindent
16517 This chapter discusses some other utility programs available in the Ada
16518 environment.
16520 @menu
16521 * Using Other Utility Programs with GNAT::
16522 * The gnatpsta Utility Program::
16523 * The External Symbol Naming Scheme of GNAT::
16524 * Ada Mode for Glide::
16525 * Converting Ada Files to html with gnathtml::
16526 * Installing gnathtml::
16527 @ifset vms
16528 * LSE::
16529 * Profiling::
16530 @end ifset
16531 @end menu
16533 @node Using Other Utility Programs with GNAT
16534 @section Using Other Utility Programs with GNAT
16536 @noindent
16537 The object files generated by GNAT are in standard system format and in
16538 particular the debugging information uses this format. This means
16539 programs generated by GNAT can be used with existing utilities that
16540 depend on these formats.
16542 @ifclear vms
16543 In general, any utility program that works with C will also often work with
16544 Ada programs generated by GNAT. This includes software utilities such as
16545 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
16546 as Purify.
16547 @end ifclear
16549 @node The gnatpsta Utility Program
16550 @section The @code{gnatpsta} Utility Program
16552 @noindent
16553 Many of the definitions in package Standard are implementation-dependent.
16554 However, the source of this package does not exist as an Ada source
16555 file, so these values cannot be determined by inspecting the source.
16556 They can be determined by examining in detail the coding of
16557 @file{cstand.adb} which creates the image of Standard in the compiler,
16558 but this is awkward and requires a great deal of internal knowledge
16559 about the system.
16561 The @code{gnatpsta} utility is designed to deal with this situation.
16562 It is an Ada program that dynamically determines the
16563 values of all the relevant parameters in Standard, and prints them
16564 out in the form of an Ada source listing for Standard, displaying all
16565 the values of interest. This output is generated to
16566 @file{stdout}.
16568 To determine the value of any parameter in package Standard, simply
16569 run @code{gnatpsta} with no qualifiers or arguments, and examine
16570 the output. This is preferable to consulting documentation, because
16571 you know that the values you are getting are the actual ones provided
16572 by the executing system.
16574 @node The External Symbol Naming Scheme of GNAT
16575 @section The External Symbol Naming Scheme of GNAT
16577 @noindent
16578 In order to interpret the output from GNAT, when using tools that are
16579 originally intended for use with other languages, it is useful to
16580 understand the conventions used to generate link names from the Ada
16581 entity names.
16583 All link names are in all lowercase letters. With the exception of library
16584 procedure names, the mechanism used is simply to use the full expanded
16585 Ada name with dots replaced by double underscores. For example, suppose
16586 we have the following package spec:
16588 @smallexample
16589 @group
16590 @cartouche
16591 @b{package} QRS @b{is}
16592    MN : Integer;
16593 @b{end} QRS;
16594 @end cartouche
16595 @end group
16596 @end smallexample
16598 @noindent
16599 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
16600 the corresponding link name is @code{qrs__mn}.
16601 @findex Export
16602 Of course if a @code{pragma Export} is used this may be overridden:
16604 @smallexample
16605 @group
16606 @cartouche
16607 @b{package} Exports @b{is}
16608    Var1 : Integer;
16609    @b{pragma} Export (Var1, C, External_Name => "var1_name");
16610    Var2 : Integer;
16611    @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
16612 @b{end} Exports;
16613 @end cartouche
16614 @end group
16615 @end smallexample
16617 @noindent
16618 In this case, the link name for @var{Var1} is whatever link name the
16619 C compiler would assign for the C function @var{var1_name}. This typically
16620 would be either @var{var1_name} or @var{_var1_name}, depending on operating
16621 system conventions, but other possibilities exist. The link name for
16622 @var{Var2} is @var{var2_link_name}, and this is not operating system
16623 dependent.
16625 @findex _main
16626 One exception occurs for library level procedures. A potential ambiguity
16627 arises between the required name @code{_main} for the C main program,
16628 and the name we would otherwise assign to an Ada library level procedure
16629 called @code{Main} (which might well not be the main program).
16631 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
16632 names. So if we have a library level procedure such as
16634 @smallexample
16635 @group
16636 @cartouche
16637 @b{procedure} Hello (S : String);
16638 @end cartouche
16639 @end group
16640 @end smallexample
16642 @noindent
16643 the external name of this procedure will be @var{_ada_hello}.
16645 @node Ada Mode for Glide
16646 @section Ada Mode for @code{Glide}
16648 @noindent
16649 The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the
16650 user in understanding existing code and facilitates writing new code. It
16651 furthermore provides some utility functions for easier integration of
16652 standard Emacs features when programming in Ada.
16654 @subsection General Features:
16656 @itemize @bullet
16657 @item
16658 Full Integrated Development Environment :
16660 @itemize @bullet
16661 @item
16662 support of 'project files' for the configuration (directories,
16663 compilation options,...)
16665 @item
16666 compiling and stepping through error messages.
16668 @item
16669 running and debugging your applications within Glide.
16670 @end itemize
16672 @item
16673 easy to use for beginners by pull-down menus,
16675 @item
16676 user configurable by many user-option variables.
16677 @end itemize
16679 @subsection Ada Mode Features That Help Understanding Code:
16681 @itemize @bullet
16682 @item
16683 functions for easy and quick stepping through Ada code,
16685 @item
16686 getting cross reference information for identifiers (e.g. find the
16687 defining place by a keystroke),
16689 @item
16690 displaying an index menu of types and subprograms and move point to
16691 the chosen one,
16693 @item
16694 automatic color highlighting of the various entities in Ada code.
16695 @end itemize
16697 @subsection Glide Support for Writing Ada Code:
16699 @itemize @bullet
16700 @item
16701 switching between spec and body files with possible
16702 autogeneration of body files,
16704 @item
16705 automatic formating of subprograms parameter lists.
16707 @item
16708 automatic smart indentation according to Ada syntax,
16710 @item
16711 automatic completion of identifiers,
16713 @item
16714 automatic casing of identifiers, keywords, and attributes,
16716 @item
16717 insertion of statement templates,
16719 @item
16720 filling comment paragraphs like filling normal text,
16721 @end itemize
16723 For more information, please refer to the online Glide documentation
16724 available in the Glide --> Help Menu.
16726 @node Converting Ada Files to html with gnathtml
16727 @section Converting Ada Files to html with @code{gnathtml}
16729 @noindent
16730 This @code{Perl} script allows Ada source files to be browsed using
16731 standard Web browsers. For installation procedure, see the section
16732 @xref{Installing gnathtml}.
16734 Ada reserved keywords are highlighted in a bold font and Ada comments in
16735 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
16736 switch to suppress the generation of cross-referencing information, user
16737 defined variables and types will appear in a different color; you will
16738 be able to click on any identifier and go to its declaration.
16740 The command line is as follow:
16741 @smallexample
16742 $ perl gnathtml.pl [switches] ada-files
16743 @end smallexample
16745 You can pass it as many Ada files as you want. @code{gnathtml} will generate
16746 an html file for every ada file, and a global file called @file{index.htm}.
16747 This file is an index of every identifier defined in the files.
16749 The available switches are the following ones :
16751 @table @code
16752 @item -83
16753 @cindex @code{-83} (@code{gnathtml})
16754 Only the subset on the Ada 83 keywords will be highlighted, not the full
16755 Ada 95 keywords set.
16757 @item -cc @var{color}
16758 This option allows you to change the color used for comments. The default
16759 value is green. The color argument can be any name accepted by html.
16761 @item -d
16762 @cindex @code{-d} (@code{gnathtml})
16763 If the ada files depend on some other files (using for instance the
16764 @code{with} command, the latter will also be converted to html.
16765 Only the files in the user project will be converted to html, not the files
16766 in the run-time library itself.
16768 @item -D
16769 This command is the same as -d above, but @code{gnathtml} will also look
16770 for files in the run-time library, and generate html files for them.
16772 @item -f
16773 @cindex @code{-f} (@code{gnathtml})
16774 By default, gnathtml will generate html links only for global entities
16775 ('with'ed units, global variables and types,...). If you specify the
16776 @code{-f} on the command line, then links will be generated for local
16777 entities too.
16779 @item -l @var{number}
16780 @cindex @code{-l} (@code{gnathtml})
16781 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
16782 will number the html files every @var{number} line.
16784 @item -I @var{dir}
16785 @cindex @code{-I} (@code{gnathtml})
16786 Specify a directory to search for library files (@file{.ali} files) and
16787 source files. You can provide several -I switches on the command line,
16788 and the directories will be parsed in the order of the command line.
16790 @item -o @var{dir}
16791 @cindex @code{-o} (@code{gnathtml})
16792 Specify the output directory for html files. By default, gnathtml will
16793 saved the generated html files in a subdirectory named @file{html/}.
16795 @item -p @var{file}
16796 @cindex @code{-p} (@code{gnathtml})
16797 If you are using Emacs and the most recent Emacs Ada mode, which provides
16798 a full Integrated Development Environment for compiling, checking,
16799 running and debugging applications, you may be using @file{.adp} files
16800 to give the directories where Emacs can find sources and object files.
16802 Using this switch, you can tell gnathtml to use these files. This allows
16803 you to get an html version of your application, even if it is spread
16804 over multiple directories.
16806 @item -sc @var{color}
16807 @cindex @code{-sc} (@code{gnathtml})
16808 This option allows you to change the color used for symbol definitions.
16809 The default value is red. The color argument can be any name accepted by html.
16811 @item -t @var{file}
16812 @cindex @code{-t} (@code{gnathtml})
16813 This switch provides the name of a file. This file contains a list of
16814 file names to be converted, and the effect is exactly as though they had
16815 appeared explicitly on the command line. This
16816 is the recommended way to work around the command line length limit on some
16817 systems.
16819 @end table
16821 @node Installing gnathtml
16822 @section Installing @code{gnathtml}
16824 @noindent
16825 @code{Perl} needs to be installed on your machine to run this script.
16826 @code{Perl} is freely available for almost every architecture and
16827 Operating System via the Internet.
16829 On Unix systems, you  may want to modify  the  first line of  the script
16830 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
16831 is. The syntax of this line is :
16832 @smallexample
16833 #!full_path_name_to_perl
16834 @end smallexample
16836 @noindent
16837 Alternatively, you may run the script using the following command line:
16839 @smallexample
16840 $ perl gnathtml.pl [switches] files
16841 @end smallexample
16843 @ifset vms
16844 @node LSE
16845 @section LSE
16846 @findex LSE
16848 @noindent
16849 The GNAT distribution provides an Ada 95 template for the Digital Language
16850 Sensitive Editor (LSE), a component of DECset. In order to
16851 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
16853 @node Profiling
16854 @section Profiling
16855 @findex PCA
16857 @noindent
16858 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
16859 of DECset. To use it proceed as outlined under "HELP PCA", except for running
16860 the collection phase with the /DEBUG qualifier.
16862 @smallexample
16863 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
16864 $ DEFINE LIB$DEBUG PCA$COLLECTOR
16865 $ RUN/DEBUG <PROGRAM_NAME>
16866 @end smallexample
16867 @noindent
16868 @end ifset
16870 @node Running and Debugging Ada Programs
16871 @chapter Running and Debugging Ada Programs
16872 @cindex Debugging
16874 @noindent
16875 This chapter discusses how to debug Ada programs. An incorrect Ada program
16876 may be handled in three ways by the GNAT compiler:
16878 @enumerate
16879 @item
16880 The illegality may be a violation of the static semantics of Ada. In
16881 that case GNAT diagnoses the constructs in the program that are illegal.
16882 It is then a straightforward matter for the user to modify those parts of
16883 the program.
16885 @item
16886 The illegality may be a violation of the dynamic semantics of Ada. In
16887 that case the program compiles and executes, but may generate incorrect
16888 results, or may terminate abnormally with some exception.
16890 @item
16891 When presented with a program that contains convoluted errors, GNAT
16892 itself may terminate abnormally without providing full diagnostics on
16893 the incorrect user program.
16894 @end enumerate
16896 @menu
16897 * The GNAT Debugger GDB::
16898 * Running GDB::
16899 * Introduction to GDB Commands::
16900 * Using Ada Expressions::
16901 * Calling User-Defined Subprograms::
16902 * Using the Next Command in a Function::
16903 * Ada Exceptions::
16904 * Ada Tasks::
16905 * Debugging Generic Units::
16906 * GNAT Abnormal Termination or Failure to Terminate::
16907 * Naming Conventions for GNAT Source Files::
16908 * Getting Internal Debugging Information::
16909 * Stack Traceback::
16910 @end menu
16912 @cindex Debugger
16913 @findex gdb
16915 @node The GNAT Debugger GDB
16916 @section The GNAT Debugger GDB
16918 @noindent
16919 @code{GDB} is a general purpose, platform-independent debugger that
16920 can be used to debug mixed-language programs compiled with @code{GCC},
16921 and in particular is capable of debugging Ada programs compiled with
16922 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
16923 complex Ada data structures.
16925 The manual @cite{Debugging with GDB}
16926 @ifset vms
16927 , located in the GNU:[DOCS] directory,
16928 @end ifset
16929 contains full details on the usage of @code{GDB}, including a section on
16930 its usage on programs. This manual should be consulted for full
16931 details. The section that follows is a brief introduction to the
16932 philosophy and use of @code{GDB}.
16934 When GNAT programs are compiled, the compiler optionally writes debugging
16935 information into the generated object file, including information on
16936 line numbers, and on declared types and variables. This information is
16937 separate from the generated code. It makes the object files considerably
16938 larger, but it does not add to the size of the actual executable that
16939 will be loaded into memory, and has no impact on run-time performance. The
16940 generation of debug information is triggered by the use of the
16941 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
16942 the compilations. It is important to emphasize that the use of these
16943 options does not change the generated code.
16945 The debugging information is written in standard system formats that
16946 are used by many tools, including debuggers and profilers. The format
16947 of the information is typically designed to describe C types and
16948 semantics, but GNAT implements a translation scheme which allows full
16949 details about Ada types and variables to be encoded into these
16950 standard C formats. Details of this encoding scheme may be found in
16951 the file exp_dbug.ads in the GNAT source distribution. However, the
16952 details of this encoding are, in general, of no interest to a user,
16953 since @code{GDB} automatically performs the necessary decoding.
16955 When a program is bound and linked, the debugging information is
16956 collected from the object files, and stored in the executable image of
16957 the program. Again, this process significantly increases the size of
16958 the generated executable file, but it does not increase the size of
16959 the executable program itself. Furthermore, if this program is run in
16960 the normal manner, it runs exactly as if the debug information were
16961 not present, and takes no more actual memory.
16963 However, if the program is run under control of @code{GDB}, the
16964 debugger is activated.  The image of the program is loaded, at which
16965 point it is ready to run.  If a run command is given, then the program
16966 will run exactly as it would have if @code{GDB} were not present. This
16967 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
16968 entirely non-intrusive until a breakpoint is encountered.  If no
16969 breakpoint is ever hit, the program will run exactly as it would if no
16970 debugger were present. When a breakpoint is hit, @code{GDB} accesses
16971 the debugging information and can respond to user commands to inspect
16972 variables, and more generally to report on the state of execution.
16974 @node Running GDB
16975 @section Running GDB
16977 @ifclear vxworks
16978 @noindent
16979 The debugger can be launched directly and simply from @code{glide} or
16980 through its graphical interface: @code{gvd}. It can also be used
16981 directly in text mode. Here is described the basic use of @code{GDB}
16982 in text mode. All the commands described below can be used in the
16983 @code{gvd} console window eventhough there is usually other more
16984 graphical ways to achieve the same goals.
16986 @ifclear vms
16987 @noindent
16988 The command to run de graphical interface of the debugger is
16989 @smallexample
16990 $ gvd program
16991 @end smallexample
16992 @end ifclear
16994 @noindent
16995 The command to run @code{GDB} in text mode is
16997 @smallexample
16998 $ ^gdb program^$ GDB PROGRAM^
16999 @end smallexample
17001 @noindent
17002 where @code{^program^PROGRAM^} is the name of the executable file. This
17003 activates the debugger and results in a prompt for debugger commands.
17004 The simplest command is simply @code{run}, which causes the program to run
17005 exactly as if the debugger were not present. The following section
17006 describes some of the additional commands that can be given to @code{GDB}.
17007 @end ifclear
17009 @ifset vxworks
17010 Please refer to the debugging section of the chapter specific to your
17011 cross environment at the end of this manual.
17012 @end ifset
17014 @node Introduction to GDB Commands
17015 @section Introduction to GDB Commands
17017 @noindent
17018 @code{GDB} contains a large repertoire of commands. The manual
17019 @cite{Debugging with GDB}
17020 @ifset vms
17021 , located in the GNU:[DOCS] directory,
17022 @end ifset
17023 includes extensive documentation on the use
17024 of these commands, together with examples of their use. Furthermore,
17025 the command @var{help} invoked from within @code{GDB} activates a simple help
17026 facility which summarizes the available commands and their options.
17027 In this section we summarize a few of the most commonly
17028 used commands to give an idea of what @code{GDB} is about. You should create
17029 a simple program with debugging information and experiment with the use of
17030 these @code{GDB} commands on the program as you read through the
17031 following section.
17033 @table @code
17034 @item set args @var{arguments}
17035 The @var{arguments} list above is a list of arguments to be passed to
17036 the program on a subsequent run command, just as though the arguments
17037 had been entered on a normal invocation of the program. The @code{set args}
17038 command is not needed if the program does not require arguments.
17040 @item run
17041 The @code{run} command causes execution of the program to start from
17042 the beginning. If the program is already running, that is to say if
17043 you are currently positioned at a breakpoint, then a prompt will ask
17044 for confirmation that you want to abandon the current execution and
17045 restart.
17047 @item breakpoint @var{location}
17048 The breakpoint command sets a breakpoint, that is to say a point at which
17049 execution will halt and @code{GDB} will await further
17050 commands. @var{location} is
17051 either a line number within a file, given in the format @code{file:linenumber},
17052 or it is the name of a subprogram. If you request that a breakpoint be set on
17053 a subprogram that is overloaded, a prompt will ask you to specify on which of
17054 those subprograms you want to breakpoint. You can also
17055 specify that all of them should be breakpointed. If the program is run
17056 and execution encounters the breakpoint, then the program
17057 stops and @code{GDB} signals that the breakpoint was encountered by
17058 printing the line of code before which the program is halted.
17060 @item breakpoint exception @var{name}
17061 A special form of the breakpoint command which breakpoints whenever
17062 exception @var{name} is raised.
17063 If @var{name} is omitted,
17064 then a breakpoint will occur when any exception is raised.
17066 @item print @var{expression}
17067 This will print the value of the given expression. Most simple
17068 Ada expression formats are properly handled by @code{GDB}, so the expression
17069 can contain function calls, variables, operators, and attribute references.
17071 @item continue
17072 Continues execution following a breakpoint, until the next breakpoint or the
17073 termination of the program.
17075 @item step
17076 Executes a single line after a breakpoint. If the next statement is a subprogram
17077 call, execution continues into (the first statement of) the
17078 called subprogram.
17080 @item next
17081 Executes a single line. If this line is a subprogram call, executes and
17082 returns from the call.
17084 @item list
17085 Lists a few lines around the current source location. In practice, it
17086 is usually more convenient to have a separate edit window open with the
17087 relevant source file displayed. Successive applications of this command
17088 print subsequent lines. The command can be given an argument which is a
17089 line number, in which case it displays a few lines around the specified one.
17091 @item backtrace
17092 Displays a backtrace of the call chain. This command is typically
17093 used after a breakpoint has occurred, to examine the sequence of calls that
17094 leads to the current breakpoint. The display includes one line for each
17095 activation record (frame) corresponding to an active subprogram.
17097 @item up
17098 At a breakpoint, @code{GDB} can display the values of variables local
17099 to the current frame. The command @code{up} can be used to
17100 examine the contents of other active frames, by moving the focus up
17101 the stack, that is to say from callee to caller, one frame at a time.
17103 @item down
17104 Moves the focus of @code{GDB} down from the frame currently being
17105 examined to the frame of its callee (the reverse of the previous command),
17107 @item frame @var{n}
17108 Inspect the frame with the given number. The value 0 denotes the frame
17109 of the current breakpoint, that is to say the top of the call stack.
17111 @end table
17113 The above list is a very short introduction to the commands that
17114 @code{GDB} provides. Important additional capabilities, including conditional
17115 breakpoints, the ability to execute command sequences on a breakpoint,
17116 the ability to debug at the machine instruction level and many other
17117 features are described in detail in @cite{Debugging with GDB}.
17118 Note that most commands can be abbreviated
17119 (for example, c for continue, bt for backtrace).
17121 @node Using Ada Expressions
17122 @section Using Ada Expressions
17123 @cindex Ada expressions
17125 @noindent
17126 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
17127 extensions. The philosophy behind the design of this subset is
17129 @itemize @bullet
17130 @item
17131 That @code{GDB} should provide basic literals and access to operations for
17132 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
17133 leaving more sophisticated computations to subprograms written into the
17134 program (which therefore may be called from @code{GDB}).
17136 @item
17137 That type safety and strict adherence to Ada language restrictions
17138 are not particularly important to the @code{GDB} user.
17140 @item
17141 That brevity is important to the @code{GDB} user.
17142 @end itemize
17144 Thus, for brevity, the debugger acts as if there were
17145 implicit @code{with} and @code{use} clauses in effect for all user-written
17146 packages, thus making it unnecessary to fully qualify most names with
17147 their packages, regardless of context. Where this causes ambiguity,
17148 @code{GDB} asks the user's intent.
17150 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
17152 @node Calling User-Defined Subprograms
17153 @section Calling User-Defined Subprograms
17155 @noindent
17156 An important capability of @code{GDB} is the ability to call user-defined
17157 subprograms while debugging. This is achieved simply by entering
17158 a subprogram call statement in the form:
17160 @smallexample
17161 call subprogram-name (parameters)
17162 @end smallexample
17164 @noindent
17165 The keyword @code{call} can be omitted in the normal case where the
17166 @code{subprogram-name} does not coincide with any of the predefined
17167 @code{GDB} commands.
17169 The effect is to invoke the given subprogram, passing it the
17170 list of parameters that is supplied. The parameters can be expressions and
17171 can include variables from the program being debugged. The
17172 subprogram must be defined
17173 at the library level within your program, and @code{GDB} will call the
17174 subprogram within the environment of your program execution (which
17175 means that the subprogram is free to access or even modify variables
17176 within your program).
17178 The most important use of this facility is in allowing the inclusion of
17179 debugging routines that are tailored to particular data structures
17180 in your program. Such debugging routines can be written to provide a suitably
17181 high-level description of an abstract type, rather than a low-level dump
17182 of its physical layout. After all, the standard
17183 @code{GDB print} command only knows the physical layout of your
17184 types, not their abstract meaning. Debugging routines can provide information
17185 at the desired semantic level and are thus enormously useful.
17187 For example, when debugging GNAT itself, it is crucial to have access to
17188 the contents of the tree nodes used to represent the program internally.
17189 But tree nodes are represented simply by an integer value (which in turn
17190 is an index into a table of nodes).
17191 Using the @code{print} command on a tree node would simply print this integer
17192 value, which is not very useful. But the PN routine (defined in file
17193 treepr.adb in the GNAT sources) takes a tree node as input, and displays
17194 a useful high level representation of the tree node, which includes the
17195 syntactic category of the node, its position in the source, the integers
17196 that denote descendant nodes and parent node, as well as varied
17197 semantic information. To study this example in more detail, you might want to
17198 look at the body of the PN procedure in the stated file.
17200 @node Using the Next Command in a Function
17201 @section Using the Next Command in a Function
17203 @noindent
17204 When you use the @code{next} command in a function, the current source
17205 location will advance to the next statement as usual. A special case
17206 arises in the case of a @code{return} statement.
17208 Part of the code for a return statement is the "epilog" of the function.
17209 This is the code that returns to the caller. There is only one copy of
17210 this epilog code, and it is typically associated with the last return
17211 statement in the function if there is more than one return. In some
17212 implementations, this epilog is associated with the first statement
17213 of the function.
17215 The result is that if you use the @code{next} command from a return
17216 statement that is not the last return statement of the function you
17217 may see a strange apparent jump to the last return statement or to
17218 the start of the function. You should simply ignore this odd jump.
17219 The value returned is always that from the first return statement
17220 that was stepped through.
17222 @node Ada Exceptions
17223 @section Breaking on Ada Exceptions
17224 @cindex Exceptions
17226 @noindent
17227 You can set breakpoints that trip when your program raises
17228 selected exceptions.
17230 @table @code
17231 @item break exception
17232 Set a breakpoint that trips whenever (any task in the) program raises
17233 any exception.
17235 @item break exception @var{name}
17236 Set a breakpoint that trips whenever (any task in the) program raises
17237 the exception @var{name}.
17239 @item break exception unhandled
17240 Set a breakpoint that trips whenever (any task in the) program raises an
17241 exception for which there is no handler.
17243 @item info exceptions
17244 @itemx info exceptions @var{regexp}
17245 The @code{info exceptions} command permits the user to examine all defined
17246 exceptions within Ada programs. With a regular expression, @var{regexp}, as
17247 argument, prints out only those exceptions whose name matches @var{regexp}.
17248 @end table
17250 @node Ada Tasks
17251 @section Ada Tasks
17252 @cindex Tasks
17254 @noindent
17255 @code{GDB} allows the following task-related commands:
17257 @table @code
17258 @item info tasks
17259 This command shows a list of current Ada tasks, as in the following example:
17261 @smallexample
17262 @iftex
17263 @leftskip=0cm
17264 @end iftex
17265 (gdb) info tasks
17266   ID       TID P-ID   Thread Pri State                 Name
17267    1   8088000   0   807e000  15 Child Activation Wait main_task
17268    2   80a4000   1   80ae000  15 Accept/Select Wait    b
17269    3   809a800   1   80a4800  15 Child Activation Wait a
17270 *  4   80ae800   3   80b8000  15 Running               c
17271 @end smallexample
17273 @noindent
17274 In this listing, the asterisk before the first task indicates it to be the
17275 currently running task. The first column lists the task ID that is used
17276 to refer to tasks in the following commands.
17278 @item break @var{linespec} task @var{taskid}
17279 @itemx break @var{linespec} task @var{taskid} if @dots{}
17280 @cindex Breakpoints and tasks
17281 These commands are like the @code{break @dots{} thread @dots{}}.
17282 @var{linespec} specifies source lines.
17284 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
17285 to specify that you only want @code{GDB} to stop the program when a
17286 particular Ada task reaches this breakpoint. @var{taskid} is one of the
17287 numeric task identifiers assigned by @code{GDB}, shown in the first
17288 column of the @samp{info tasks} display.
17290 If you do not specify @samp{task @var{taskid}} when you set a
17291 breakpoint, the breakpoint applies to @emph{all} tasks of your
17292 program.
17294 You can use the @code{task} qualifier on conditional breakpoints as
17295 well; in this case, place @samp{task @var{taskid}} before the
17296 breakpoint condition (before the @code{if}).
17298 @item task @var{taskno}
17299 @cindex Task switching
17301 This command allows to switch to the task referred by @var{taskno}. In
17302 particular, This allows to browse the backtrace of the specified
17303 task. It is advised to switch back to the original task before
17304 continuing execution otherwise the scheduling of the program may be
17305 perturbated.
17306 @end table
17308 @noindent
17309 For more detailed information on the tasking support, see @cite{Debugging with GDB}.
17311 @node Debugging Generic Units
17312 @section Debugging Generic Units
17313 @cindex Debugging Generic Units
17314 @cindex Generics
17316 @noindent
17317 GNAT always uses code expansion for generic instantiation. This means that
17318 each time an instantiation occurs, a complete copy of the original code is
17319 made, with appropriate substitutions of formals by actuals.
17321 It is not possible to refer to the original generic entities in
17322 @code{GDB}, but it is always possible to debug a particular instance of
17323 a generic, by using the appropriate expanded names. For example, if we have
17325 @smallexample
17326 @group
17327 @cartouche
17328 @b{procedure} g @b{is}
17330    @b{generic package} k @b{is}
17331       @b{procedure} kp (v1 : @b{in out} integer);
17332    @b{end} k;
17334    @b{package body} k @b{is}
17335       @b{procedure} kp (v1 : @b{in out} integer) @b{is}
17336       @b{begin}
17337          v1 := v1 + 1;
17338       @b{end} kp;
17339    @b{end} k;
17341    @b{package} k1 @b{is new} k;
17342    @b{package} k2 @b{is new} k;
17344    var : integer := 1;
17346 @b{begin}
17347    k1.kp (var);
17348    k2.kp (var);
17349    k1.kp (var);
17350    k2.kp (var);
17351 @b{end};
17352 @end cartouche
17353 @end group
17354 @end smallexample
17356 @noindent
17357 Then to break on a call to procedure kp in the k2 instance, simply
17358 use the command:
17360 @smallexample
17361 (gdb) break g.k2.kp
17362 @end smallexample
17364 @noindent
17365 When the breakpoint occurs, you can step through the code of the
17366 instance in the normal manner and examine the values of local variables, as for
17367 other units.
17369 @node GNAT Abnormal Termination or Failure to Terminate
17370 @section GNAT Abnormal Termination or Failure to Terminate
17371 @cindex GNAT Abnormal Termination or Failure to Terminate
17373 @noindent
17374 When presented with programs that contain serious errors in syntax
17375 or semantics,
17376 GNAT may on rare occasions  experience problems in operation, such
17377 as aborting with a
17378 segmentation fault or illegal memory access, raising an internal
17379 exception, terminating abnormally, or failing to terminate at all.
17380 In such cases, you can activate
17381 various features of GNAT that can help you pinpoint the construct in your
17382 program that is the likely source of the problem.
17384 The following strategies are presented in increasing order of
17385 difficulty, corresponding to your experience in using GNAT and your
17386 familiarity with compiler internals.
17388 @enumerate
17389 @item
17390 Run @code{gcc} with the @option{-gnatf}. This first
17391 switch causes all errors on a given line to be reported. In its absence,
17392 only the first error on a line is displayed.
17394 The @option{-gnatdO} switch causes errors to be displayed as soon as they
17395 are encountered, rather than after compilation is terminated. If GNAT
17396 terminates prematurely or goes into an infinite loop, the last error
17397 message displayed may help to pinpoint the culprit.
17399 @item
17400 Run @code{gcc} with the @code{^-v (verbose)^/VERBOSE^} switch. In this mode,
17401 @code{gcc} produces ongoing information about the progress of the
17402 compilation and provides the name of each procedure as code is
17403 generated. This switch allows you to find which Ada procedure was being
17404 compiled when it encountered a code generation problem.
17406 @item
17407 @cindex @option{-gnatdc} switch
17408 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
17409 switch that does for the front-end what @code{^-v^VERBOSE^} does for the back end.
17410 The system prints the name of each unit, either a compilation unit or
17411 nested unit, as it is being analyzed.
17412 @item
17413 Finally, you can start
17414 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
17415 front-end of GNAT, and can be run independently (normally it is just
17416 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
17417 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
17418 @code{where} command is the first line of attack; the variable
17419 @code{lineno} (seen by @code{print lineno}), used by the second phase of
17420 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
17421 which the execution stopped, and @code{input_file name} indicates the name of
17422 the source file.
17423 @end enumerate
17425 @node Naming Conventions for GNAT Source Files
17426 @section Naming Conventions for GNAT Source Files
17428 @noindent
17429 In order to examine the workings of the GNAT system, the following
17430 brief description of its organization may be helpful:
17432 @itemize @bullet
17433 @item
17434 Files with prefix @file{^sc^SC^} contain the lexical scanner.
17436 @item
17437 All files prefixed with @file{^par^PAR^} are components of the parser. The
17438 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
17439 parsing of select statements can be found in @file{par-ch9.adb}.
17441 @item
17442 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
17443 numbers correspond to chapters of the Ada standard. For example, all
17444 issues involving context clauses can be found in @file{sem_ch10.adb}. In
17445 addition, some features of the language require sufficient special processing
17446 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
17447 dynamic dispatching, etc.
17449 @item
17450 All files prefixed with @file{^exp^EXP^} perform normalization and
17451 expansion of the intermediate representation (abstract syntax tree, or AST).
17452 these files use the same numbering scheme as the parser and semantics files.
17453 For example, the construction of record initialization procedures is done in
17454 @file{exp_ch3.adb}.
17456 @item
17457 The files prefixed with @file{^bind^BIND^} implement the binder, which
17458 verifies the consistency of the compilation, determines an order of
17459 elaboration, and generates the bind file.
17461 @item
17462 The files @file{atree.ads} and @file{atree.adb} detail the low-level
17463 data structures used by the front-end.
17465 @item
17466 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
17467 the abstract syntax tree as produced by the parser.
17469 @item
17470 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
17471 all entities, computed during semantic analysis.
17473 @item
17474 Library management issues are dealt with in files with prefix
17475 @file{^lib^LIB^}.
17477 @item
17478 @findex Ada
17479 @cindex Annex A
17480 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
17481 defined in Annex A.
17483 @item
17484 @findex Interfaces
17485 @cindex Annex B
17486 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
17487 defined in Annex B.
17489 @item
17490 @findex System
17491 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
17492 both language-defined children and GNAT run-time routines.
17494 @item
17495 @findex GNAT
17496 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
17497 general-purpose packages, fully documented in their specifications. All
17498 the other @file{.c} files are modifications of common @code{gcc} files.
17499 @end itemize
17501 @node Getting Internal Debugging Information
17502 @section Getting Internal Debugging Information
17504 @noindent
17505 Most compilers have internal debugging switches and modes. GNAT
17506 does also, except GNAT internal debugging switches and modes are not
17507 secret. A summary and full description of all the compiler and binder
17508 debug flags are in the file @file{debug.adb}. You must obtain the
17509 sources of the compiler to see the full detailed effects of these flags.
17511 The switches that print the source of the program (reconstructed from
17512 the internal tree) are of general interest for user programs, as are the
17513 options to print
17514 the full internal tree, and the entity table (the symbol table
17515 information). The reconstructed source provides a readable version of the
17516 program after the front-end has completed analysis and  expansion, and is useful
17517 when studying the performance of specific constructs. For example, constraint
17518 checks are indicated, complex aggregates are replaced with loops and
17519 assignments, and tasking primitives are replaced with run-time calls.
17521 @node Stack Traceback
17522 @section Stack Traceback
17523 @cindex traceback
17524 @cindex stack traceback
17525 @cindex stack unwinding
17527 @noindent
17528 Traceback is a mechanism to display the sequence of subprogram calls that
17529 leads to a specified execution point in a program. Often (but not always)
17530 the execution point is an instruction at which an exception has been raised.
17531 This mechanism is also known as @i{stack unwinding} because it obtains
17532 its information by scanning the run-time stack and recovering the activation
17533 records of all active subprograms. Stack unwinding is one of the most
17534 important tools for program debugging.
17536 @noindent
17537 The first entry stored in traceback corresponds to the deepest calling level,
17538 that is to say the subprogram currently executing the instruction
17539 from which we want to obtain the traceback.
17541 @noindent
17542 Note that there is no runtime performance penalty when stack traceback
17543 is enabled and no exception are raised during program execution.
17545 @menu
17546 * Non-Symbolic Traceback::
17547 * Symbolic Traceback::
17548 @end menu
17550 @node Non-Symbolic Traceback
17551 @subsection Non-Symbolic Traceback
17552 @cindex traceback, non-symbolic
17554 @noindent
17555 Note: this feature is not supported on all platforms. See
17556 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
17557 platforms.
17559 @menu
17560 * Tracebacks From an Unhandled Exception::
17561 * Tracebacks From Exception Occurrences (non-symbolic)::
17562 * Tracebacks From Anywhere in a Program (non-symbolic)::
17563 @end menu
17565 @node Tracebacks From an Unhandled Exception
17566 @subsubsection Tracebacks From an Unhandled Exception
17568 @noindent
17569 A runtime non-symbolic traceback is a list of addresses of call instructions.
17570 To enable this feature you must use the @code{-E}
17571 @code{gnatbind}'s option. With this option a stack traceback is stored as part
17572 of exception information. It is possible to retrieve this information using the
17573 standard @code{Ada.Exception.Exception_Information} routine.
17575 @noindent
17576 Let's have a look at a simple example:
17578 @smallexample
17579 @cartouche
17580 @group
17581 procedure STB is
17583    procedure P1 is
17584    begin
17585       raise Constraint_Error;
17586    end P1;
17588    procedure P2 is
17589    begin
17590       P1;
17591    end P2;
17593 begin
17594    P2;
17595 end STB;
17596 @end group
17597 @end cartouche
17598 @end smallexample
17600 @smallexample
17601 $ gnatmake stb -bargs -E
17602 $ stb
17604 Execution terminated by unhandled exception
17605 Exception name: CONSTRAINT_ERROR
17606 Message: stb.adb:5
17607 Call stack traceback locations:
17608 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
17609 @end smallexample
17611 @noindent
17612 As we see the traceback lists a sequence of addresses for the unhandled
17613 exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to
17614 guess that this exception come from procedure P1. To translate these
17615 addresses into the source lines where the calls appear, the
17616 @code{addr2line} tool, described below, is invaluable. The use of this tool
17617 requires the program to be compiled with debug information.
17619 @smallexample
17620 $ gnatmake -g stb -bargs -E
17621 $ stb
17623 Execution terminated by unhandled exception
17624 Exception name: CONSTRAINT_ERROR
17625 Message: stb.adb:5
17626 Call stack traceback locations:
17627 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
17629 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
17630    0x4011f1 0x77e892a4
17632 00401373 at d:/stb/stb.adb:5
17633 0040138B at d:/stb/stb.adb:10
17634 0040139C at d:/stb/stb.adb:14
17635 00401335 at d:/stb/b~stb.adb:104
17636 004011C4 at /build/.../crt1.c:200
17637 004011F1 at /build/.../crt1.c:222
17638 77E892A4 in ?? at ??:0
17639 @end smallexample
17641 @noindent
17642 @code{addr2line} has a number of other useful options:
17644 @table @code
17645 @item --functions
17646 to get the function name corresponding to any location
17648 @item --demangle=gnat
17649 to use the @b{gnat} decoding mode for the function names. Note that
17650 for binutils version 2.9.x the option is simply @code{--demangle}.
17651 @end table
17653 @smallexample
17654 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
17655    0x40139c 0x401335 0x4011c4 0x4011f1
17657 00401373 in stb.p1 at d:/stb/stb.adb:5
17658 0040138B in stb.p2 at d:/stb/stb.adb:10
17659 0040139C in stb at d:/stb/stb.adb:14
17660 00401335 in main at d:/stb/b~stb.adb:104
17661 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
17662 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
17663 @end smallexample
17665 @noindent
17666 From this traceback we can see that the exception was raised in
17667 @file{stb.adb} at line 5, which was reached from a procedure call in
17668 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
17669 which contains the call to the main program.
17670 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
17671 and the output will vary from platform to platform.
17673 @noindent
17674 It is also possible to use @code{GDB} with these traceback addresses to debug
17675 the program. For example, we can break at a given code location, as reported
17676 in the stack traceback:
17678 @smallexample
17679 $ gdb -nw stb
17680 @ifset wnt
17681 @noindent
17682 Furthermore, this feature is not implemented inside Windows DLL. Only
17683 the non-symbolic traceback is reported in this case.
17684 @end ifset
17686 (gdb) break *0x401373
17687 Breakpoint 1 at 0x401373: file stb.adb, line 5.
17688 @end smallexample
17690 @noindent
17691 It is important to note that the stack traceback addresses
17692 do not change when debug information is included. This is particularly useful
17693 because it makes it possible to release software without debug information (to
17694 minimize object size), get a field report that includes a stack traceback
17695 whenever an internal bug occurs, and then be able to retrieve the sequence
17696 of calls with the same program compiled with debug information.
17698 @node Tracebacks From Exception Occurrences (non-symbolic)
17699 @subsubsection Tracebacks From Exception Occurrences
17701 @noindent
17702 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
17703 The stack traceback is attached to the exception information string, and can
17704 be retrieved in an exception handler within the Ada program, by means of the
17705 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
17707 @smallexample
17708 @cartouche
17709 @group
17710 with Ada.Text_IO;
17711 with Ada.Exceptions;
17713 procedure STB is
17715    use Ada;
17716    use Ada.Exceptions;
17718    procedure P1 is
17719       K : Positive := 1;
17720    begin
17721       K := K - 1;
17722    exception
17723       when E : others =>
17724          Text_IO.Put_Line (Exception_Information (E));
17725    end P1;
17727    procedure P2 is
17728    begin
17729       P1;
17730    end P2;
17732 begin
17733    P2;
17734 end STB;
17735 @end group
17736 @end cartouche
17737 @end smallexample
17739 @noindent
17740 This program will output:
17742 @smallexample
17743 $ stb
17745 Exception name: CONSTRAINT_ERROR
17746 Message: stb.adb:12
17747 Call stack traceback locations:
17748 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
17749 @end smallexample
17751 @node Tracebacks From Anywhere in a Program (non-symbolic)
17752 @subsubsection Tracebacks From Anywhere in a Program
17754 @noindent
17755 It is also possible to retrieve a stack traceback from anywhere in a
17756 program. For this you need to
17757 use the @code{GNAT.Traceback} API. This package includes a procedure called
17758 @code{Call_Chain} that computes a complete stack traceback, as well as useful
17759 display procedures described below. It is not necessary to use the
17760 @code{-E gnatbind} option in this case, because the stack traceback mechanism
17761 is invoked explicitly.
17763 @noindent
17764 In the following example we compute a traceback at a specific location in
17765 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
17766 convert addresses to strings:
17768 @smallexample
17769 @cartouche
17770 @group
17771 with Ada.Text_IO;
17772 with GNAT.Traceback;
17773 with GNAT.Debug_Utilities;
17775 procedure STB is
17777    use Ada;
17778    use GNAT;
17779    use GNAT.Traceback;
17781    procedure P1 is
17782       TB  : Tracebacks_Array (1 .. 10);
17783       --  We are asking for a maximum of 10 stack frames.
17784       Len : Natural;
17785       --  Len will receive the actual number of stack frames returned.
17786    begin
17787       Call_Chain (TB, Len);
17789       Text_IO.Put ("In STB.P1 : ");
17791       for K in 1 .. Len loop
17792          Text_IO.Put (Debug_Utilities.Image (TB (K)));
17793          Text_IO.Put (' ');
17794       end loop;
17796       Text_IO.New_Line;
17797    end P1;
17799    procedure P2 is
17800    begin
17801       P1;
17802    end P2;
17804 begin
17805    P2;
17806 end STB;
17807 @end group
17808 @end cartouche
17809 @end smallexample
17811 @smallexample
17812 $ gnatmake stb
17813 $ stb
17815 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
17816 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
17817 @end smallexample
17819 @node Symbolic Traceback
17820 @subsection Symbolic Traceback
17821 @cindex traceback, symbolic
17823 @noindent
17824 A symbolic traceback is a stack traceback in which procedure names are
17825 associated with each code location.
17827 @noindent
17828 Note that this feature is not supported on all platforms. See
17829 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
17830 list of currently supported platforms.
17832 @noindent
17833 Note that the symbolic traceback requires that the program be compiled
17834 with debug information. If it is not compiled with debug information
17835 only the non-symbolic information will be valid.
17837 @menu
17838 * Tracebacks From Exception Occurrences (symbolic)::
17839 * Tracebacks From Anywhere in a Program (symbolic)::
17840 @end menu
17842 @node Tracebacks From Exception Occurrences (symbolic)
17843 @subsubsection Tracebacks From Exception Occurrences
17845 @smallexample
17846 @cartouche
17847 @group
17848 with Ada.Text_IO;
17849 with GNAT.Traceback.Symbolic;
17851 procedure STB is
17853    procedure P1 is
17854    begin
17855       raise Constraint_Error;
17856    end P1;
17858    procedure P2 is
17859    begin
17860       P1;
17861    end P2;
17863    procedure P3 is
17864    begin
17865       P2;
17866    end P3;
17868 begin
17869    P3;
17870 exception
17871    when E : others =>
17872       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
17873 end STB;
17874 @end group
17875 @end cartouche
17876 @end smallexample
17878 @smallexample
17879 $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl
17880 $ stb
17882 0040149F in stb.p1 at stb.adb:8
17883 004014B7 in stb.p2 at stb.adb:13
17884 004014CF in stb.p3 at stb.adb:18
17885 004015DD in ada.stb at stb.adb:22
17886 00401461 in main at b~stb.adb:168
17887 004011C4 in __mingw_CRTStartup at crt1.c:200
17888 004011F1 in mainCRTStartup at crt1.c:222
17889 77E892A4 in ?? at ??:0
17890 @end smallexample
17892 @noindent
17893 The exact sequence of linker options may vary from platform to platform.
17894 The above @code{-largs} section is for Windows platforms. By contrast,
17895 under Unix there is no need for the @code{-largs} section.
17896 Differences across platforms are due to details of linker implementation.
17898 @node Tracebacks From Anywhere in a Program (symbolic)
17899 @subsubsection Tracebacks From Anywhere in a Program
17901 @noindent
17902 It is possible to get a symbolic stack traceback
17903 from anywhere in a program, just as for non-symbolic tracebacks.
17904 The first step is to obtain a non-symbolic
17905 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
17906 information. Here is an example:
17908 @smallexample
17909 @cartouche
17910 @group
17911 with Ada.Text_IO;
17912 with GNAT.Traceback;
17913 with GNAT.Traceback.Symbolic;
17915 procedure STB is
17917    use Ada;
17918    use GNAT.Traceback;
17919    use GNAT.Traceback.Symbolic;
17921    procedure P1 is
17922       TB  : Tracebacks_Array (1 .. 10);
17923       --  We are asking for a maximum of 10 stack frames.
17924       Len : Natural;
17925       --  Len will receive the actual number of stack frames returned.
17926    begin
17927       Call_Chain (TB, Len);
17928       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
17929    end P1;
17931    procedure P2 is
17932    begin
17933       P1;
17934    end P2;
17936 begin
17937    P2;
17938 end STB;
17939 @end group
17940 @end cartouche
17941 @end smallexample
17943 @ifset vms
17944 @node Compatibility with DEC Ada
17945 @chapter Compatibility with DEC Ada
17946 @cindex Compatibility
17948 @noindent
17949 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
17950 OpenVMS Alpha. GNAT achieves a high level of compatibility
17951 with DEC Ada, and it should generally be straightforward to port code
17952 from the DEC Ada environment to GNAT. However, there are a few language
17953 and implementation differences of which the user must be aware. These
17954 differences are discussed in this section. In
17955 addition, the operating environment and command structure for the
17956 compiler are different, and these differences are also discussed.
17958 Note that this discussion addresses specifically the implementation
17959 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
17960 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems, GNAT
17961 always follows the Alpha implementation.
17963 @menu
17964 * Ada 95 Compatibility::
17965 * Differences in the Definition of Package System::
17966 * Language-Related Features::
17967 * The Package STANDARD::
17968 * The Package SYSTEM::
17969 * Tasking and Task-Related Features::
17970 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
17971 * Pragmas and Pragma-Related Features::
17972 * Library of Predefined Units::
17973 * Bindings::
17974 * Main Program Definition::
17975 * Implementation-Defined Attributes::
17976 * Compiler and Run-Time Interfacing::
17977 * Program Compilation and Library Management::
17978 * Input-Output::
17979 * Implementation Limits::
17980 * Tools::
17981 @end menu
17983 @node Ada 95 Compatibility
17984 @section Ada 95 Compatibility
17986 @noindent
17987 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
17988 compiler. Ada 95 is almost completely upwards compatible
17989 with Ada 83, and therefore Ada 83 programs will compile
17990 and run under GNAT with
17991 no changes or only minor changes. The Ada 95 Reference
17992 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
17993 incompatibilities.
17995 GNAT provides the switch /83 on the GNAT COMPILE command,
17996 as well as the pragma ADA_83, to force the compiler to
17997 operate in Ada 83 mode. This mode does not guarantee complete
17998 conformance to Ada 83, but in practice is sufficient to
17999 eliminate most sources of incompatibilities.
18000 In particular, it eliminates the recognition of the
18001 additional Ada 95 keywords, so that their use as identifiers
18002 in Ada83 program is legal, and handles the cases of packages
18003 with optional bodies, and generics that instantiate unconstrained
18004 types without the use of @code{(<>)}.
18006 @node Differences in the Definition of Package System
18007 @section Differences in the Definition of Package System
18009 @noindent
18010 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
18011 implementation-dependent declarations to package System. In normal mode,
18012 GNAT does not take advantage of this permission, and the version of System
18013 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
18015 However, DEC Ada adds an extensive set of declarations to package System,
18016 as fully documented in the DEC Ada manuals. To minimize changes required
18017 for programs that make use of these extensions, GNAT provides the pragma
18018 Extend_System for extending the definition of package System. By using:
18020 @smallexample
18021 @group
18022 @cartouche
18023 @b{pragma} Extend_System (Aux_DEC);
18024 @end cartouche
18025 @end group
18026 @end smallexample
18028 @noindent
18029 The set of definitions in System is extended to include those in package
18030 @code{System.Aux_DEC}.
18031 These definitions are incorporated directly into package
18032 System, as though they had been declared there in the first place. For a
18033 list of the declarations added, see the specification of this package,
18034 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
18035 The pragma Extend_System is a configuration pragma, which means that
18036 it can be placed in the file @file{gnat.adc}, so that it will automatically
18037 apply to all subsequent compilations. See the section on Configuration
18038 Pragmas for further details.
18040 An alternative approach that avoids the use of the non-standard
18041 Extend_System pragma is to add a context clause to the unit that
18042 references these facilities:
18044 @smallexample
18045 @group
18046 @cartouche
18047 @b{with} System.Aux_DEC;
18048 @b{use}  System.Aux_DEC;
18049 @end cartouche
18050 @end group
18051 @end smallexample
18053 @noindent
18054 The effect is not quite semantically identical to incorporating the declarations
18055 directly into package @code{System},
18056 but most programs will not notice a difference
18057 unless they use prefix notation (e.g. @code{System.Integer_8})
18058 to reference the
18059 entities directly in package @code{System}.
18060 For units containing such references,
18061 the prefixes must either be removed, or the pragma @code{Extend_System}
18062 must be used.
18064 @node Language-Related Features
18065 @section Language-Related Features
18067 @noindent
18068 The following sections highlight differences in types,
18069 representations of types, operations, alignment, and
18070 related topics.
18072 @menu
18073 * Integer Types and Representations::
18074 * Floating-Point Types and Representations::
18075 * Pragmas Float_Representation and Long_Float::
18076 * Fixed-Point Types and Representations::
18077 * Record and Array Component Alignment::
18078 * Address Clauses::
18079 * Other Representation Clauses::
18080 @end menu
18082 @node Integer Types and Representations
18083 @subsection Integer Types and Representations
18085 @noindent
18086 The set of predefined integer types is identical in DEC Ada and GNAT.
18087 Furthermore the representation of these integer types is also identical,
18088 including the capability of size clauses forcing biased representation.
18090 In addition,
18091 DEC Ada for OpenVMS Alpha systems has defined the
18092 following additional integer types in package System:
18094 @itemize @bullet
18096 @item
18097 INTEGER_8
18099 @item
18100 INTEGER_16
18102 @item
18103 INTEGER_32
18105 @item
18106 INTEGER_64
18108 @item
18109 LARGEST_INTEGER
18110 @end itemize
18112 @noindent
18113 When using GNAT, the first four of these types may be obtained from the
18114 standard Ada 95 package @code{Interfaces}.
18115 Alternatively, by use of the pragma
18116 @code{Extend_System}, identical
18117 declarations can be referenced directly in package @code{System}.
18118 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
18120 @node Floating-Point Types and Representations
18121 @subsection Floating-Point Types and Representations
18122 @cindex Floating-Point types
18124 @noindent
18125 The set of predefined floating-point types is identical in DEC Ada and GNAT.
18126 Furthermore the representation of these floating-point
18127 types is also identical. One important difference is that the default
18128 representation for DEC Ada is VAX_Float, but the default representation
18129 for GNAT is IEEE.
18131 Specific types may be declared to be VAX_Float or IEEE, using the pragma
18132 @code{Float_Representation} as described in the DEC Ada documentation.
18133 For example, the declarations:
18135 @smallexample
18136 @group
18137 @cartouche
18138 @b{type} F_Float @b{is digits} 6;
18139 @b{pragma} Float_Representation (VAX_Float, F_Float);
18140 @end cartouche
18141 @end group
18142 @end smallexample
18144 @noindent
18145 declare a type F_Float that will be represented in VAX_Float format.
18146 This set of declarations actually appears in System.Aux_DEC, which provides
18147 the full set of additional floating-point declarations provided in
18148 the DEC Ada version of package
18149 System. This and similar declarations may be accessed in a user program by using
18150 pragma @code{Extend_System}. The use of this
18151 pragma, and the related pragma @code{Long_Float} is described in further
18152 detail in the following section.
18154 @node Pragmas Float_Representation and Long_Float
18155 @subsection Pragmas Float_Representation and Long_Float
18157 @noindent
18158 DEC Ada provides the pragma @code{Float_Representation}, which
18159 acts as a program library switch to allow control over
18160 the internal representation chosen for the predefined
18161 floating-point types declared in the package @code{Standard}.
18162 The format of this pragma is as follows:
18164 @smallexample
18165 @group
18166 @cartouche
18167 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
18168 @end cartouche
18169 @end group
18170 @end smallexample
18172 @noindent
18173 This pragma controls the representation of floating-point
18174 types as follows:
18176 @itemize @bullet
18177 @item
18178 @code{VAX_Float} specifies that floating-point
18179 types are represented by default with the VAX hardware types
18180 F-floating, D-floating, G-floating. Note that the H-floating
18181 type is available only on DIGITAL Vax systems, and is not available
18182 in either DEC Ada or GNAT for Alpha systems.
18184 @item
18185 @code{IEEE_Float} specifies that floating-point
18186 types are represented by default with the IEEE single and
18187 double floating-point types.
18188 @end itemize
18190 @noindent
18191 GNAT provides an identical implementation of the pragma
18192 @code{Float_Representation}, except that it functions as a
18193 configuration pragma, as defined by Ada 95. Note that the
18194 notion of configuration pragma corresponds closely to the
18195 DEC Ada notion of a program library switch.
18197 When no pragma is used in GNAT, the default is IEEE_Float, which is different
18198 from DEC Ada 83, where the default is VAX_Float. In addition, the
18199 predefined libraries in GNAT are built using IEEE_Float, so it is not
18200 advisable to change the format of numbers passed to standard library
18201 routines, and if necessary explicit type conversions may be needed.
18203 The use of IEEE_Float is recommended in GNAT since it is more efficient,
18204 and (given that it conforms to an international standard) potentially more
18205 portable. The situation in which VAX_Float may be useful is in interfacing
18206 to existing code and data that expects the use of VAX_Float. There are
18207 two possibilities here. If the requirement for the use of VAX_Float is
18208 localized, then the best approach is to use the predefined VAX_Float
18209 types in package @code{System}, as extended by
18210 @code{Extend_System}. For example, use @code{System.F_Float}
18211 to specify the 32-bit @code{F-Float} format.
18213 Alternatively, if an entire program depends heavily on the use of
18214 the @code{VAX_Float} and in particular assumes that the types in
18215 package @code{Standard} are in @code{Vax_Float} format, then it
18216 may be desirable to reconfigure GNAT to assume Vax_Float by default.
18217 This is done by using the GNAT LIBRARY command to rebuild the library, and
18218 then using the general form of the @code{Float_Representation}
18219 pragma to ensure that this default format is used throughout.
18220 The form of the GNAT LIBRARY command is:
18222 @smallexample
18223 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
18224 @end smallexample
18226 @noindent
18227 where @i{file} contains the new configuration pragmas
18228 and @i{directory} is the directory to be created to contain
18229 the new library.
18231 @noindent
18232 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
18233 to allow control over the internal representation chosen
18234 for the predefined type @code{Long_Float} and for floating-point
18235 type declarations with digits specified in the range 7 .. 15.
18236 The format of this pragma is as follows:
18238 @smallexample
18239 @cartouche
18240 @b{pragma} Long_Float (D_FLOAT | G_FLOAT);
18241 @end cartouche
18242 @end smallexample
18244 @node Fixed-Point Types and Representations
18245 @subsection Fixed-Point Types and Representations
18247 @noindent
18248 On DEC Ada for OpenVMS Alpha systems, rounding is
18249 away from zero for both positive and negative numbers.
18250 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
18252 On GNAT for OpenVMS Alpha, the results of operations
18253 on fixed-point types are in accordance with the Ada 95
18254 rules. In particular, results of operations on decimal
18255 fixed-point types are truncated.
18257 @node Record and Array Component Alignment
18258 @subsection Record and Array Component Alignment
18260 @noindent
18261 On DEC Ada for OpenVMS Alpha, all non composite components
18262 are aligned on natural boundaries. For example, 1-byte
18263 components are aligned on byte boundaries, 2-byte
18264 components on 2-byte boundaries, 4-byte components on 4-byte
18265 byte boundaries, and so on. The OpenVMS Alpha hardware
18266 runs more efficiently with naturally aligned data.
18268 ON GNAT for OpenVMS Alpha, alignment rules are compatible
18269 with DEC Ada for OpenVMS Alpha.
18271 @node Address Clauses
18272 @subsection Address Clauses
18274 @noindent
18275 In DEC Ada and GNAT, address clauses are supported for
18276 objects and imported subprograms.
18277 The predefined type @code{System.Address} is a private type
18278 in both compilers, with the same representation (it is simply
18279 a machine pointer). Addition, subtraction, and comparison
18280 operations are available in the standard Ada 95 package
18281 @code{System.Storage_Elements}, or in package @code{System}
18282 if it is extended to include @code{System.Aux_DEC} using a
18283 pragma @code{Extend_System} as previously described.
18285 Note that code that with's both this extended package @code{System}
18286 and the package @code{System.Storage_Elements} should not @code{use}
18287 both packages, or ambiguities will result. In general it is better
18288 not to mix these two sets of facilities. The Ada 95 package was
18289 designed specifically to provide the kind of features that DEC Ada
18290 adds directly to package @code{System}.
18292 GNAT is compatible with DEC Ada in its handling of address
18293 clauses, except for some limitations in
18294 the form of address clauses for composite objects with
18295 initialization. Such address clauses are easily replaced
18296 by the use of an explicitly-defined constant as described
18297 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
18298 of declarations:
18300 @smallexample
18301 @group
18302 @cartouche
18303 X, Y : Integer := Init_Func;
18304 Q : String (X .. Y) := "abc";
18306 @b{for} Q'Address @b{use} Compute_Address;
18307 @end cartouche
18308 @end group
18309 @end smallexample
18311 @noindent
18312 will be rejected by GNAT, since the address cannot be computed at the time
18313 that Q is declared. To achieve the intended effect, write instead:
18315 @smallexample
18316 @group
18317 @cartouche
18318 X, Y : Integer := Init_Func;
18319 Q_Address : @b{constant} Address := Compute_Address;
18320 Q : String (X .. Y) := "abc";
18322 @b{for} Q'Address @b{use} Q_Address;
18323 @end cartouche
18324 @end group
18325 @end smallexample
18327 @noindent
18328 which will be accepted by GNAT (and other Ada 95 compilers), and is also
18329 backwards compatible with Ada 83. A fuller description of the restrictions
18330 on address specifications is found in the GNAT Reference Manual.
18332 @node Other Representation Clauses
18333 @subsection Other Representation Clauses
18335 @noindent
18336 GNAT supports in a compatible manner all the representation
18337 clauses supported by DEC Ada. In addition, it
18338 supports representation clause forms that are new in Ada 95
18339 including COMPONENT_SIZE and SIZE clauses for objects.
18341 @node The Package STANDARD
18342 @section The Package STANDARD
18344 @noindent
18345 The package STANDARD, as implemented by DEC Ada, is fully
18346 described in the Reference Manual for the Ada Programming
18347 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
18348 Language Reference Manual. As implemented by GNAT, the
18349 package STANDARD is described in the Ada 95 Reference
18350 Manual.
18352 In addition, DEC Ada supports the Latin-1 character set in
18353 the type CHARACTER. GNAT supports the Latin-1 character set
18354 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
18355 the type WIDE_CHARACTER.
18357 The floating-point types supported by GNAT are those
18358 supported by DEC Ada, but defaults are different, and are controlled by
18359 pragmas. See @pxref{Floating-Point Types and Representations} for details.
18361 @node The Package SYSTEM
18362 @section The Package SYSTEM
18364 @noindent
18365 DEC Ada provides a system-specific version of the package
18366 SYSTEM for each platform on which the language ships.
18367 For the complete specification of the package SYSTEM, see
18368 Appendix F of the DEC Ada Language Reference Manual.
18370 On DEC Ada, the package SYSTEM includes the following conversion functions:
18371 @itemize @bullet
18372 @item TO_ADDRESS(INTEGER)
18374 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
18376 @item  TO_ADDRESS(universal_integer)
18378 @item  TO_INTEGER(ADDRESS)
18380 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
18382 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
18383                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
18384 @end itemize
18386 @noindent
18387 By default, GNAT supplies a version of SYSTEM that matches
18388 the definition given in the Ada 95 Reference Manual.
18389 This
18390 is a subset of the DIGITAL system definitions, which is as
18391 close as possible to the original definitions. The only difference
18392 is that the definition of SYSTEM_NAME is different:
18394 @smallexample
18395 @group
18396 @cartouche
18397 @b{type} Name @b{is} (SYSTEM_NAME_GNAT);
18398 System_Name : @b{constant} Name := SYSTEM_NAME_GNAT;
18399 @end cartouche
18400 @end group
18401 @end smallexample
18403 @noindent
18404 Also, GNAT adds the new Ada 95 declarations for
18405 BIT_ORDER and DEFAULT_BIT_ORDER.
18407 However, the use of the following pragma causes GNAT
18408 to extend the definition of package SYSTEM so that it
18409 encompasses the full set of DIGITAL-specific extensions,
18410 including the functions listed above:
18412 @smallexample
18413 @cartouche
18414 @b{pragma} Extend_System (Aux_DEC);
18415 @end cartouche
18416 @end smallexample
18418 @noindent
18419 The pragma Extend_System is a configuration pragma that
18420 is most conveniently placed in the @file{gnat.adc} file. See the
18421 GNAT Reference Manual for further details.
18423 DEC Ada does not allow the recompilation of the package
18424 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
18425 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
18426 the package SYSTEM. On OpenVMS Alpha systems, the pragma
18427 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
18428 its single argument.
18430 GNAT does permit the recompilation of package SYSTEM using
18431 a special switch (-gnatg) and this switch can be used if
18432 it is necessary to change constants in SYSTEM. GNAT does
18433 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
18434 or MEMORY_SIZE by any other means.
18436 On GNAT systems, the pragma SYSTEM_NAME takes the
18437 enumeration literal SYSTEM_NAME_GNAT.
18439 The definitions provided by the use of
18441 @smallexample
18442 pragma Extend_System (AUX_Dec);
18443 @end smallexample
18445 @noindent
18446 are virtually identical to those provided by the DEC Ada 83 package
18447 System. One important difference is that the name of the TO_ADDRESS
18448 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
18449 See the GNAT Reference manual for a discussion of why this change was
18450 necessary.
18452 @noindent
18453 The version of TO_ADDRESS taking a universal integer argument is in fact
18454 an extension to Ada 83 not strictly compatible with the reference manual.
18455 In GNAT, we are constrained to be exactly compatible with the standard,
18456 and this means we cannot provide this capability. In DEC Ada 83, the
18457 point of this definition is to deal with a call like:
18459 @smallexample
18460 TO_ADDRESS (16#12777#);
18461 @end smallexample
18463 @noindent
18464 Normally, according to the Ada 83 standard, one would expect this to be
18465 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
18466 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
18467 definition using universal_integer takes precedence.
18469 In GNAT, since the version with universal_integer cannot be supplied, it is
18470 not possible to be 100% compatible. Since there are many programs using
18471 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
18472 to change the name of the function in the UNSIGNED_LONGWORD case, so the
18473 declarations provided in the GNAT version of AUX_Dec are:
18475 @smallexample
18476 function To_Address (X : Integer) return Address;
18477 pragma Pure_Function (To_Address);
18479 function To_Address_Long (X : Unsigned_Longword) return Address;
18480 pragma Pure_Function (To_Address_Long);
18481 @end smallexample
18483 @noindent
18484 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
18485 change the name to TO_ADDRESS_LONG.
18487 @node Tasking and Task-Related Features
18488 @section Tasking and Task-Related Features
18490 @noindent
18491 The concepts relevant to a comparison of tasking on GNAT
18492 and on DEC Ada for OpenVMS Alpha systems are discussed in
18493 the following sections.
18495 For detailed information on concepts related to tasking in
18496 DEC Ada, see the DEC Ada Language Reference Manual and the
18497 relevant run-time reference manual.
18499 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
18500 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
18502 @noindent
18503 On OpenVMS Alpha systems, each Ada task (except a passive
18504 task) is implemented as a single stream of execution
18505 that is created and managed by the kernel. On these
18506 systems, DEC Ada tasking support is based on DECthreads,
18507 an implementation of the POSIX standard for threads.
18509 Although tasks are implemented as threads, all tasks in
18510 an Ada program are part of the same process. As a result,
18511 resources such as open files and virtual memory can be
18512 shared easily among tasks. Having all tasks in one process
18513 allows better integration with the programming environment
18514 (the shell and the debugger, for example).
18516 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
18517 code that calls DECthreads routines can be used together.
18518 The interaction between Ada tasks and DECthreads routines
18519 can have some benefits. For example when on OpenVMS Alpha,
18520 DEC Ada can call C code that is already threaded.
18521 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
18522 and Ada tasks are mapped to threads.
18524 @menu
18525 * Assigning Task IDs::
18526 * Task IDs and Delays::
18527 * Task-Related Pragmas::
18528 * Scheduling and Task Priority::
18529 * The Task Stack::
18530 * External Interrupts::
18531 @end menu
18533 @node Assigning Task IDs
18534 @subsection Assigning Task IDs
18536 @noindent
18537 The DEC Ada Run-Time Library always assigns %TASK 1 to
18538 the environment task that executes the main program. On
18539 OpenVMS Alpha systems, %TASK 0 is often used for tasks
18540 that have been created but are not yet activated.
18542 On OpenVMS Alpha systems, task IDs are assigned at
18543 activation. On GNAT systems, task IDs are also assigned at
18544 task creation but do not have the same form or values as
18545 task ID values in DEC Ada. There is no null task, and the
18546 environment task does not have a specific task ID value.
18548 @node Task IDs and Delays
18549 @subsection Task IDs and Delays
18551 @noindent
18552 On OpenVMS Alpha systems, tasking delays are implemented
18553 using Timer System Services. The Task ID is used for the
18554 identification of the timer request (the REQIDT parameter).
18555 If Timers are used in the application take care not to use
18556 0 for the identification, because cancelling such a timer
18557 will cancel all timers and may lead to unpredictable results.
18559 @node Task-Related Pragmas
18560 @subsection Task-Related Pragmas
18562 @noindent
18563 Ada supplies the pragma TASK_STORAGE, which allows
18564 specification of the size of the guard area for a task
18565 stack. (The guard area forms an area of memory that has no
18566 read or write access and thus helps in the detection of
18567 stack overflow.) On OpenVMS Alpha systems, if the pragma
18568 TASK_STORAGE specifies a value of zero, a minimal guard
18569 area is created. In the absence of a pragma TASK_STORAGE, a default guard
18570 area is created.
18572 GNAT supplies the following task-related pragmas:
18574 @itemize @bullet
18575 @item  TASK_INFO
18577               This pragma appears within a task definition and
18578               applies to the task in which it appears. The argument
18579               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
18581 @item  TASK_STORAGE
18583               GNAT implements pragma TASK_STORAGE in the same way as
18584               DEC Ada.
18585               Both DEC Ada and GNAT supply the pragmas PASSIVE,
18586               SUPPRESS, and VOLATILE.
18587 @end itemize
18588 @node Scheduling and Task Priority
18589 @subsection Scheduling and Task Priority
18591 @noindent
18592 DEC Ada implements the Ada language requirement that
18593 when two tasks are eligible for execution and they have
18594 different priorities, the lower priority task does not
18595 execute while the higher priority task is waiting. The DEC
18596 Ada Run-Time Library keeps a task running until either the
18597 task is suspended or a higher priority task becomes ready.
18599 On OpenVMS Alpha systems, the default strategy is round-
18600 robin with preemption. Tasks of equal priority take turns
18601 at the processor. A task is run for a certain period of
18602 time and then placed at the rear of the ready queue for
18603 its priority level.
18605 DEC Ada provides the implementation-defined pragma TIME_SLICE,
18606 which can be used to enable or disable round-robin
18607 scheduling of tasks with the same priority.
18608 See the relevant DEC Ada run-time reference manual for
18609 information on using the pragmas to control DEC Ada task
18610 scheduling.
18612 GNAT follows the scheduling rules of Annex D (real-time
18613 Annex) of the Ada 95 Reference Manual. In general, this
18614 scheduling strategy is fully compatible with DEC Ada
18615 although it provides some additional constraints (as
18616 fully documented in Annex D).
18617 GNAT implements time slicing control in a manner compatible with
18618 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
18619 to the DEC Ada 83 pragma of the same name.
18620 Note that it is not possible to mix GNAT tasking and
18621 DEC Ada 83 tasking in the same program, since the two run times are
18622 not compatible.
18624 @node The Task Stack
18625 @subsection The Task Stack
18627 @noindent
18628 In DEC Ada, a task stack is allocated each time a
18629 non passive task is activated. As soon as the task is
18630 terminated, the storage for the task stack is deallocated.
18631 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
18632 a default stack size is used. Also, regardless of the size
18633 specified, some additional space is allocated for task
18634 management purposes. On OpenVMS Alpha systems, at least
18635 one page is allocated.
18637 GNAT handles task stacks in a similar manner. According to
18638 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
18639 an alternative method for controlling the task stack size.
18640 The specification of the attribute T'STORAGE_SIZE is also
18641 supported in a manner compatible with DEC Ada.
18643 @node External Interrupts
18644 @subsection External Interrupts
18646 @noindent
18647 On DEC Ada, external interrupts can be associated with task entries.
18648 GNAT is compatible with DEC Ada in its handling of external interrupts.
18650 @node Pragmas and Pragma-Related Features
18651 @section Pragmas and Pragma-Related Features
18653 @noindent
18654 Both DEC Ada and GNAT supply all language-defined pragmas
18655 as specified by the Ada 83 standard. GNAT also supplies all
18656 language-defined pragmas specified in the Ada 95 Reference Manual.
18657 In addition, GNAT implements the implementation-defined pragmas
18658 from DEC Ada 83.
18660 @itemize @bullet
18661 @item  AST_ENTRY
18663 @item  COMMON_OBJECT
18665 @item  COMPONENT_ALIGNMENT
18667 @item  EXPORT_EXCEPTION
18669 @item  EXPORT_FUNCTION
18671 @item  EXPORT_OBJECT
18673 @item  EXPORT_PROCEDURE
18675 @item  EXPORT_VALUED_PROCEDURE
18677 @item  FLOAT_REPRESENTATION
18679 @item  IDENT
18681 @item  IMPORT_EXCEPTION
18683 @item  IMPORT_FUNCTION
18685 @item  IMPORT_OBJECT
18687 @item  IMPORT_PROCEDURE
18689 @item  IMPORT_VALUED_PROCEDURE
18691 @item  INLINE_GENERIC
18693 @item  INTERFACE_NAME
18695 @item  LONG_FLOAT
18697 @item  MAIN_STORAGE
18699 @item  PASSIVE
18701 @item  PSET_OBJECT
18703 @item  SHARE_GENERIC
18705 @item  SUPPRESS_ALL
18707 @item  TASK_STORAGE
18709 @item  TIME_SLICE
18711 @item  TITLE
18712 @end itemize
18714 @noindent
18715 These pragmas are all fully implemented, with the exception of @code{Title},
18716 @code{Passive}, and @code{Share_Generic}, which are
18717 recognized, but which have no
18718 effect in GNAT. The effect of @code{Passive} may be obtained by the
18719 use of protected objects in Ada 95. In GNAT, all generics are inlined.
18721 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
18722 a separate subprogram specification which must appear before the
18723 subprogram body.
18725 GNAT also supplies a number of implementation-defined pragmas as follows:
18726 @itemize @bullet
18727 @item  C_PASS_BY_COPY
18729 @item  EXTEND_SYSTEM
18731 @item  SOURCE_FILE_NAME
18733 @item  UNSUPPRESS
18735 @item  WARNINGS
18737 @item  ABORT_DEFER
18739 @item  ADA_83
18741 @item  ADA_95
18743 @item  ANNOTATE
18745 @item  ASSERT
18747 @item  CPP_CLASS
18749 @item  CPP_CONSTRUCTOR
18751 @item  CPP_DESTRUCTOR
18753 @item  CPP_VIRTUAL
18755 @item  CP_VTABLE
18757 @item  DEBUG
18759 @item  LINKER_ALIAS
18761 @item  LINKER_SECTION
18763 @item  MACHINE_ATTRIBUTE
18765 @item  NO_RETURN
18767 @item  PURE_FUNCTION
18769 @item  SOURCE_REFERENCE
18771 @item  TASK_INFO
18773 @item  UNCHECKED_UNION
18775 @item  UNIMPLEMENTED_UNIT
18777 @item  WEAK_EXTERNAL
18778 @end itemize
18780 @noindent
18781 For full details on these GNAT implementation-defined pragmas, see
18782 the GNAT Reference Manual.
18784 @menu
18785 * Restrictions on the Pragma INLINE::
18786 * Restrictions on the Pragma INTERFACE::
18787 * Restrictions on the Pragma SYSTEM_NAME::
18788 @end menu
18790 @node Restrictions on the Pragma INLINE
18791 @subsection Restrictions on the Pragma INLINE
18793 @noindent
18794 DEC Ada applies the following restrictions to the pragma INLINE:
18795 @itemize @bullet
18796 @item  Parameters cannot be a task type.
18798 @item  Function results cannot be task types, unconstrained
18799 array types, or unconstrained types with discriminants.
18801 @item  Bodies cannot declare the following:
18802 @itemize @bullet
18803 @item  Subprogram body or stub (imported subprogram is allowed)
18805 @item  Tasks
18807 @item  Generic declarations
18809 @item  Instantiations
18811 @item  Exceptions
18813 @item  Access types (types derived from access types allowed)
18815 @item  Array or record types
18817 @item  Dependent tasks
18819 @item  Direct recursive calls of subprogram or containing
18820 subprogram, directly or via a renaming
18822 @end itemize
18823 @end itemize
18825 @noindent
18826 In GNAT, the only restriction on pragma INLINE is that the
18827 body must occur before the call if both are in the same
18828 unit, and the size must be appropriately small. There are
18829 no other specific restrictions which cause subprograms to
18830 be incapable of being inlined.
18832 @node  Restrictions on the Pragma INTERFACE
18833 @subsection  Restrictions on the Pragma INTERFACE
18835 @noindent
18836 The following lists and describes the restrictions on the
18837 pragma INTERFACE on DEC Ada and GNAT:
18838 @itemize @bullet
18839 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
18840 Default is the default on OpenVMS Alpha systems.
18842 @item  Parameter passing: Language specifies default
18843 mechanisms but can be overridden with an EXPORT pragma.
18845 @itemize @bullet
18846 @item  Ada: Use internal Ada rules.
18848 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
18849 record or task type. Result cannot be a string, an
18850 array, or a record.
18852 @item  Fortran: Parameters cannot be a task. Result cannot
18853 be a string, an array, or a record.
18854 @end itemize
18855 @end itemize
18857 @noindent
18858 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
18859 record parameters for all languages.
18861 @node  Restrictions on the Pragma SYSTEM_NAME
18862 @subsection  Restrictions on the Pragma SYSTEM_NAME
18864 @noindent
18865 For DEC Ada for OpenVMS Alpha, the enumeration literal
18866 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
18867 literal for the type NAME is SYSTEM_NAME_GNAT.
18869 @node  Library of Predefined Units
18870 @section  Library of Predefined Units
18872 @noindent
18873 A library of predefined units is provided as part of the
18874 DEC Ada and GNAT implementations. DEC Ada does not provide
18875 the package MACHINE_CODE but instead recommends importing
18876 assembler code.
18878 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
18879 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
18880 version. During GNAT installation, the DEC Ada Predefined
18881 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
18882 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
18883 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
18884 for details.
18886 The GNAT RTL is contained in
18887 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
18888 the default search path is set up to find DECLIB units in preference
18889 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
18890 for example).
18892 However, it is possible to change the default so that the
18893 reverse is true, or even to mix them using child package
18894 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
18895 is the package name, and the Ada units are available in the
18896 standard manner defined for Ada 95, that is to say as Ada.xxx. To
18897 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
18898 appropriately. For example, to change the default to use the Ada95
18899 versions do:
18901 @smallexample
18902 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
18903                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
18904 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
18905                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
18906 @end smallexample
18908 @menu
18909 * Changes to DECLIB::
18910 @end menu
18912 @node Changes to DECLIB
18913 @subsection Changes to DECLIB
18915 @noindent
18916 The changes made to the DEC Ada predefined library for GNAT and Ada 95
18917 compatibility are minor and include the following:
18919 @itemize @bullet
18920 @item  Adjusting the location of pragmas and record representation
18921 clauses to obey Ada 95 rules
18923 @item  Adding the proper notation to generic formal parameters
18924 that take unconstrained types in instantiation
18926 @item  Adding pragma ELABORATE_BODY to package specifications
18927 that have package bodies not otherwise allowed
18929 @item  Occurrences of the identifier "PROTECTED" are renamed to "PROTECTD".
18930 Currently these are found only in the STARLET package spec.
18931 @end itemize
18933 @noindent
18934 None of the above changes is visible to users.
18936 @node Bindings
18937 @section Bindings
18939 @noindent
18940 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
18941 @itemize @bullet
18943 @item  Command Language Interpreter (CLI interface)
18945 @item  DECtalk Run-Time Library (DTK interface)
18947 @item  Librarian utility routines (LBR interface)
18949 @item  General Purpose Run-Time Library (LIB interface)
18951 @item  Math Run-Time Library (MTH interface)
18953 @item  National Character Set Run-Time Library (NCS interface)
18955 @item  Compiled Code Support Run-Time Library (OTS interface)
18957 @item  Parallel Processing Run-Time Library (PPL interface)
18959 @item  Screen Management Run-Time Library (SMG interface)
18961 @item  Sort Run-Time Library (SOR interface)
18963 @item  String Run-Time Library (STR interface)
18965 @item STARLET System Library
18966 @findex Starlet
18968 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
18970 @item  X Windows Toolkit (XT interface)
18972 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
18973 @end itemize
18975 @noindent
18976 GNAT provides implementations of these DEC bindings in the DECLIB directory.
18978 The X/Motif bindings used to build DECLIB are whatever versions are in the
18979 DEC Ada ADA$PREDEFINED directory with extension .ADC. The build script will
18980 automatically add a pragma Linker_Options to packages Xm, Xt, and X_Lib
18981 causing the default X/Motif shareable image libraries to be linked in. This
18982 is done via options files named xm.opt, xt.opt, and x_lib.opt (also located
18983 in the DECLIB directory).
18985 It may be necessary to edit these options files to update or correct the
18986 library names if, for example, the newer X/Motif bindings from ADA$EXAMPLES
18987 had been (previous to installing GNAT) copied and renamed to superseded the
18988 default ADA$PREDEFINED versions.
18990 @menu
18991 * Shared Libraries and Options Files::
18992 * Interfaces to C::
18993 @end menu
18995 @node Shared Libraries and Options Files
18996 @subsection Shared Libraries and Options Files
18998 @noindent
18999 When using the DEC Ada
19000 predefined X and Motif bindings, the linking with their shareable images is
19001 done automatically by GNAT LINK. When using other X and Motif bindings, it
19002 is necessary to add the corresponding shareable images to the command line for
19003 GNAT LINK. When linking with shared libraries, or with .OPT files, it is
19004 also necessary to add them to the command line for GNAT LINK.
19006 A shared library to be used with GNAT is built in the same way as other
19007 libraries under VMS. The VMS Link command can be used in standard fashion.
19009 @node Interfaces to C
19010 @subsection Interfaces to C
19012 @noindent
19013 DEC Ada
19014 provides the following Ada types and operations:
19016 @itemize @bullet
19017 @item C types package (C_TYPES)
19019 @item C strings (C_TYPES.NULL_TERMINATED)
19021 @item Other_types (SHORT_INT)
19022 @end itemize
19024 @noindent
19025 Interfacing to C with GNAT, one can use the above approach
19026 described for DEC Ada or the facilities of Annex B of
19027 the Ada 95 Reference Manual (packages INTERFACES.C,
19028 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
19029 information, see the section "Interfacing to C" in the
19030 GNAT Reference Manual.
19032 The @option{-gnatF} qualifier forces default and explicit
19033 @code{External_Name} parameters in pragmas Import and Export
19034 to be uppercased for compatibility with the default behavior
19035 of DEC C. The qualifier has no effect on @code{Link_Name} parameters.
19037 @node Main Program Definition
19038 @section Main Program Definition
19040 @noindent
19041 The following section discusses differences in the
19042 definition of main programs on DEC Ada and GNAT.
19043 On DEC Ada, main programs are defined to meet the
19044 following conditions:
19045 @itemize @bullet
19046 @item  Procedure with no formal parameters (returns 0 upon
19047        normal completion)
19049 @item  Procedure with no formal parameters (returns 42 when
19050        unhandled exceptions are raised)
19052 @item  Function with no formal parameters whose returned value
19053        is of a discrete type
19055 @item  Procedure with one OUT formal of a discrete type for
19056        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
19058 @end itemize
19060 @noindent
19061 When declared with the pragma EXPORT_VALUED_PROCEDURE,
19062 a main function or main procedure returns a discrete
19063 value whose size is less than 64 bits (32 on VAX systems),
19064 the value is zero- or sign-extended as appropriate.
19065 On GNAT, main programs are defined as follows:
19066 @itemize @bullet
19067 @item  Must be a non-generic, parameter-less subprogram that
19068 is either a procedure or function returning an Ada
19069 STANDARD.INTEGER (the predefined type)
19071 @item  Cannot be a generic subprogram or an instantiation of a
19072 generic subprogram
19073 @end itemize
19075 @node Implementation-Defined Attributes
19076 @section Implementation-Defined Attributes
19078 @noindent
19079 GNAT provides all DEC Ada implementation-defined
19080 attributes.
19082 @node Compiler and Run-Time Interfacing
19083 @section Compiler and Run-Time Interfacing
19085 @noindent
19086 DEC Ada provides the following ways to pass options to the linker (ACS LINK):
19087 @itemize @bullet
19088 @item  /WAIT and /SUBMIT qualifiers
19090 @item  /COMMAND qualifier
19092 @item  /[NO]MAP qualifier
19094 @item  /OUTPUT=file-spec
19096 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
19097 @end itemize
19099 @noindent
19100 To pass options to the linker, GNAT provides the following
19101 switches:
19103 @itemize @bullet
19104 @item   /EXECUTABLE=exec-name
19106 @item   /VERBOSE qualifier
19108 @item   /[NO]DEBUG and /[NO]TRACEBACK qualifiers
19109 @end itemize
19111 @noindent
19112 For more information on these switches, see the section
19113 "Switches for gnatlink" in the corresponding section of this Guide.
19114 In DEC Ada, the command-line switch /OPTIMIZE is available
19115 to control optimization. DEC Ada also supplies the
19116 following pragmas:
19117 @itemize @bullet
19118 @item  OPTIMIZE
19120 @item  INLINE
19122 @item  INLINE_GENERIC
19124 @item  SUPPRESS_ALL
19126 @item  PASSIVE
19127 @end itemize
19129 @noindent
19130 In GNAT, optimization is controlled strictly by command
19131 line parameters, as described in the corresponding section of this guide.
19132 The DIGITAL pragmas for control of optimization are
19133 recognized but ignored.
19135 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
19136 the default is that optimization is turned on.
19138 @node Program Compilation and Library Management
19139 @section Program Compilation and Library Management
19141 @noindent
19142 DEC Ada and GNAT provide a comparable set of commands to
19143 build programs. DEC Ada also provides a program library,
19144 which is a concept that does not exist on GNAT. Instead,
19145 GNAT provides directories of sources that are compiled as
19146 needed.
19148 The following table summarizes
19149 the DEC Ada commands and provides
19150 equivalent GNAT commands. In this table, some GNAT
19151 equivalents reflect the fact that GNAT does not use the
19152 concept of a program library. Instead, it uses a model
19153 in which collections of source and object files are used
19154 in a manner consistent with other languages like C and
19155 Fortran. Therefore, standard system file commands are used
19156 to manipulate these elements. Those GNAT commands are marked with
19157 an asterisk in the table that follows.
19158 Note that, unlike DEC Ada,  none of the GNAT commands accepts wild cards.
19160 @need 1500
19161 @multitable @columnfractions .31 .30 .39
19163 @item @strong{DEC_Ada_Command}
19164 @tab @strong{GNAT_Equivalent}
19165 @tab @strong{Description}
19167 @item  ADA
19168 @tab     GNAT COMPILE
19169 @tab     Invokes the compiler to compile one or more Ada source files.
19171 @item  ACS ATTACH
19172 @tab     No equivalent
19173 @tab     Switches control of terminal from current process running the program
19174                                                 library manager.
19176 @item   ACS CHECK
19177 @tab      GNAT MAKE /DEPENDENCY_LIST
19178 @tab      Forms the execution closure of one
19179           or more compiled units and checks completeness and currency.
19181 @item   ACS COMPILE
19182 @tab      GNAT MAKE /ACTIONS=COMPILE
19183 @tab      Forms the execution closure of one or
19184           more specified units, checks completeness and currency,
19185           identifies units that have revised source files, compiles same,
19186           and recompiles units that are or will become obsolete.
19187           Also completes incomplete generic instantiations.
19189 @item   ACS COPY FOREIGN
19190 @tab      Copy (*)
19191 @tab      Copies a foreign object file into the program library as a
19192           library unit body.
19194 @item   ACS COPY UNIT
19195 @tab      Copy (*)
19196 @tab      Copies a compiled unit from one program library to another.
19198 @item   ACS CREATE LIBRARY
19199 @tab      Create /directory (*)
19200 @tab      Creates a program library.
19202 @item   ACS CREATE SUBLIBRARY
19203 @tab      Create /directory (*)
19204 @tab      Creates a program sublibrary.
19206 @item   ACS DELETE LIBRARY
19207 @tab
19208 @tab       Deletes a program library and its contents.
19210 @item   ACS DELETE SUBLIBRARY
19211 @tab
19212 @tab      Deletes a program sublibrary and its contents.
19214 @item   ACS DELETE UNIT
19215 @tab      Delete @i{file} (*)
19216 @tab      On OpenVMS systems, deletes one or more compiled units from
19217           the current program library.
19219 @item   ACS DIRECTORY
19220 @tab       Directory (*)
19221 @tab       On OpenVMS systems, lists units contained in the current
19222            program library.
19224 @item   ACS ENTER FOREIGN
19225 @tab      Copy (*)
19226 @tab      Allows the import of a foreign body as an Ada library
19227           specification and enters a reference to a pointer.
19229 @item   ACS ENTER UNIT
19230 @tab      Copy (*)
19231 @tab      Enters a reference (pointer) from the current program library to
19232           a unit compiled into another program library.
19234 @item   ACS EXIT
19235 @tab      No equivalent
19236 @tab      Exits from the program library manager.
19238 @item   ACS EXPORT
19239 @tab      Copy (*)
19240 @tab      Creates an object file that contains system-specific object code
19241           for one or more units. With GNAT, object files can simply be copied
19242           into the desired directory.
19244 @item   ACS EXTRACT SOURCE
19245 @tab      Copy (*)
19246 @tab      Allows access to the copied source file for each Ada compilation unit
19248 @item   ACS HELP
19249 @tab      HELP GNAT
19250 @tab      Provides online help.
19252 @item    ACS LINK
19253 @tab       GNAT LINK
19254 @tab       Links an object file containing Ada units into an executable
19255            file.
19257 @item    ACS LOAD
19258 @tab       Copy (*)
19259 @tab       Loads (partially compiles) Ada units into the program library.
19260            Allows loading a program from a collection of files into a library
19261            without knowing the relationship among units.
19263 @item    ACS MERGE
19264 @tab      Copy (*)
19265 @tab      Merges into the current program library, one or more units from
19266           another library where they were modified.
19268 @item    ACS RECOMPILE
19269 @tab       GNAT MAKE /ACTIONS=COMPILE
19270 @tab       Recompiles from   external or copied source files any obsolete
19271            unit in the closure. Also, completes any incomplete generic
19272            instantiations.
19274 @item    ACS REENTER
19275 @tab       GNAT MAKE
19276 @tab       Reenters current references to units compiled after last entered
19277            with the ACS ENTER UNIT command.
19279 @item    ACS SET LIBRARY
19280 @tab       Set default (*)
19281 @tab       Defines a program library to be the compilation context as well
19282            as the target library for compiler output and commands in general.
19284 @item    ACS SET PRAGMA
19285 @tab       Edit gnat.adc (*)
19286 @tab       Redefines specified  values of the library characteristics
19287             LONG_ FLOAT, MEMORY_SIZE, SYSTEM_NAME, and @code{Float_Representation}.
19289 @item    ACS SET SOURCE
19290 @tab       define @* ADA_INCLUDE_PATH @i{path} (*)
19291 @tab       Defines the source file search list for the ACS COMPILE  command.
19293 @item    ACS SHOW LIBRARY
19294 @tab       Directory (*)
19295 @tab        Lists information about one or more program libraries.
19297 @item    ACS SHOW PROGRAM
19298 @tab       No equivalent
19299 @tab       Lists information about the execution closure of one or
19300            more units in the program library.
19302 @item    ACS SHOW SOURCE
19303 @tab       Show logical @* ADA_INCLUDE_PATH
19304 @tab       Shows the source file search used when compiling units.
19306 @item    ACS SHOW VERSION
19307 @tab       Compile with VERBOSE option
19308 @tab       Displays the version number of the compiler and program library
19309            manager used.
19311 @item    ACS SPAWN
19312 @tab        No equivalent
19313 @tab        Creates a subprocess of the current process (same as DCL SPAWN
19314             command).
19316 @item    ACS VERIFY
19317 @tab       No equivalent
19318 @tab       Performs a series of consistency checks on a program library to
19319            determine whether the library structure and library files are in
19320            valid_form.
19322 @end multitable
19324 @noindent
19326 @node Input-Output
19327 @section Input-Output
19329 @noindent
19330 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
19331 Management Services (RMS) to perform operations on
19332 external files.
19334 @noindent
19335 DEC Ada and GNAT predefine an identical set of input-
19336 output packages. To make the use of the
19337 generic TEXT_IO operations more convenient, DEC Ada
19338 provides predefined library packages that instantiate the
19339 integer and floating-point operations for the predefined
19340 integer and floating-point types as shown in the following table.
19342 @table @code
19344 @item   Package_Name
19345       Instantiation
19347 @item   INTEGER_TEXT_IO
19348       INTEGER_IO(INTEGER)
19350 @item   SHORT_INTEGER_TEXT_IO
19351      INTEGER_IO(SHORT_INTEGER)
19353 @item   SHORT_SHORT_INTEGER_TEXT_IO
19354      INTEGER_IO(SHORT_SHORT_ INTEGER)
19356 @item   FLOAT_TEXT_IO
19357       FLOAT_IO(FLOAT)
19359 @item   LONG_FLOAT_TEXT_IO
19360       FLOAT_IO(LONG_FLOAT)
19361 @end table
19363 @noindent
19364 The DEC Ada predefined packages and their operations
19365 are implemented using OpenVMS Alpha files and input-
19366 output facilities. DEC Ada supports asynchronous input-
19367 output on OpenVMS Alpha. Familiarity with the following is
19368 recommended:
19369 @itemize @bullet
19370 @item  RMS file organizations and access methods
19372 @item  OpenVMS file specifications and directories
19374 @item  OpenVMS File Definition Language (FDL)
19375 @end itemize
19377 @noindent
19378 GNAT provides I/O facilities that are completely
19379 compatible with DEC Ada. The distribution includes the
19380 standard DEC Ada versions of all I/O packages, operating
19381 in a manner compatible with DEC Ada. In particular, the
19382 following packages are by default the DEC Ada (Ada 83)
19383 versions of these packages rather than the renamings
19384 suggested in annex J of the Ada 95 Reference Manual:
19385 @itemize @bullet
19386 @item  TEXT_IO
19388 @item  SEQUENTIAL_IO
19390 @item  DIRECT_IO
19391 @end itemize
19393 @noindent
19394 The use of the standard Ada 95 syntax for child packages (for
19395 example, ADA.TEXT_IO) retrieves the Ada 95 versions of these
19396 packages, as defined in the Ada 95 Reference Manual.
19397 GNAT provides DIGITAL-compatible predefined instantiations
19398 of the TEXT_IO packages, and also
19399 provides the standard predefined instantiations required
19400 by the Ada 95 Reference Manual.
19402 For further information on how GNAT interfaces to the file
19403 system or how I/O is implemented in programs written in
19404 mixed languages, see the chapter "Implementation of the
19405 Standard I/O" in the GNAT Reference Manual.
19406 This chapter covers the following:
19407 @itemize @bullet
19408 @item  Standard I/O packages
19410 @item  FORM strings
19412 @item  DIRECT_IO
19414 @item  SEQUENTIAL_IO
19416 @item  TEXT_IO
19418 @item  Stream pointer positioning
19420 @item  Reading and writing non-regular files
19422 @item  GET_IMMEDIATE
19424 @item  Treating TEXT_IO files as streams
19426 @item  Shared files
19428 @item  Open modes
19429 @end itemize
19431 @node Implementation Limits
19432 @section Implementation Limits
19434 @noindent
19435 The following table lists implementation limits for DEC Ada and GNAT systems.
19436 @multitable @columnfractions .60 .20 .20
19437 @item  Compilation Parameter
19438 @tab   DEC Ada
19439 @tab   GNAT
19441 @item  In a subprogram or entry  declaration, maximum number of
19442        formal parameters that are of an unconstrained record type
19443 @tab   32
19444 @tab   No set limit
19446 @item  Maximum identifier length (number of characters)
19447 @tab   255
19448 @tab   255
19450 @item  Maximum number of characters in a source line
19451 @tab   255
19452 @tab   255
19454 @item  Maximum collection size   (number of bytes)
19455 @tab   2**31-1
19456 @tab   2**31-1
19458 @item  Maximum number of discriminants for a record type
19459 @tab   245
19460 @tab   No set limit
19462 @item  Maximum number of formal parameters in an entry or
19463        subprogram declaration
19464 @tab   246
19465 @tab    No set limit
19467 @item  Maximum number of dimensions in an array type
19468 @tab   255
19469 @tab   No set limit
19471 @item  Maximum number of library  units and subunits in a compilation.
19472 @tab   4095
19473 @tab   No set limit
19475 @item  Maximum number of library units and subunits in an execution.
19476 @tab   16383
19477 @tab   No set limit
19479 @item  Maximum number of objects declared with the pragma COMMON_OBJECT
19480        or PSECT_OBJECT
19481 @tab   32757
19482 @tab   No set limit
19484 @item  Maximum number of enumeration literals in an enumeration type
19485        definition
19486 @tab   65535
19487 @tab   No set limit
19489 @item  Maximum number of lines in a source file
19490 @tab   65534
19491 @tab   No set limit
19493 @item  Maximum number of bits in any object
19494 @tab   2**31-1
19495 @tab   2**31-1
19497 @item  Maximum size of the static portion of a stack frame (approximate)
19498 @tab   2**31-1
19499 @tab   2**31-1
19500 @end multitable
19502 @node  Tools
19503 @section Tools
19505 @end ifset
19507 @node Inline Assembler
19508 @chapter Inline Assembler
19510 @noindent
19511 If you need to write low-level software that interacts directly with the hardware, Ada provides two ways to incorporate assembly language code into your program.  First, you can import and invoke external routines written in assembly language, an Ada feature fully supported by GNAT.  However, for small sections of code it may be simpler or more efficient to include assembly language statements directly in your Ada source program, using the facilities of the implementation-defined package @code{System.Machine_Code}, which incorporates the gcc Inline Assembler.  The Inline Assembler approach offers a number of advantages, including the following:
19513 @itemize @bullet
19514 @item No need to use non-Ada tools
19515 @item Consistent interface over different targets
19516 @item Automatic usage of the proper calling conventions
19517 @item Access to Ada constants and variables
19518 @item Definition of intrinsic routines
19519 @item Possibility of inlining a subprogram comprising assembler code
19520 @item Code optimizer can take Inline Assembler code into account
19521 @end itemize
19523 This chapter presents a series of examples to show you how to use the Inline Assembler.  Although it focuses on the Intel x86, the general approach applies also to other processors.  It is assumed that you are familiar with Ada and with assembly language programming.
19525 @menu
19526 * Basic Assembler Syntax::
19527 * A Simple Example of Inline Assembler::
19528 * Output Variables in Inline Assembler::
19529 * Input Variables in Inline Assembler::
19530 * Inlining Inline Assembler Code::
19531 * Other Asm Functionality::
19532 * A Complete Example::
19533 @end menu
19535 @c ---------------------------------------------------------------------------
19536 @node Basic Assembler Syntax
19537 @section Basic Assembler Syntax
19539 @noindent
19540 The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a
19541 language that descends from the AT&T Unix assembler @emph{as} (and which is often
19542 referred to as ``AT&T syntax'').
19543 The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions.
19544 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
19545 pre-processor) documentation for further information.
19547 @table @asis
19548 @item Register names
19549 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
19551 Intel: No extra punctuation; for example @code{eax}
19553 @item Immediate operand
19554 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
19556 Intel: No extra punctuation; for example @code{4}
19558 @item Address
19559 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
19561 Intel: No extra punctuation; for example @code{loc}
19563 @item Memory contents
19564 gcc / @emph{as}: No extra punctuation; for example @code{loc}
19566 Intel: Square brackets; for example @code{[loc]}
19568 @item Register contents
19569 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
19571 Intel: Square brackets; for example @code{[eax]}
19573 @item Hexadecimal numbers
19574 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
19576 Intel: Trailing ``h''; for example @code{A0h}
19578 @item Operand size
19579 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word
19581 Intel: Implicit, deduced by assembler; for example @code{mov}
19583 @item Instruction repetition
19584 gcc / @emph{as}: Split into two lines; for example
19586 @code{rep}
19588 @code{stosl}
19590 Intel: Keep on one line; for example @code{rep stosl}
19592 @item Order of operands
19593 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
19595 Intel: Destination first; for example @code{mov eax, 4}
19596 @end table
19598 @c ---------------------------------------------------------------------------
19599 @node A Simple Example of Inline Assembler
19600 @section A Simple Example of Inline Assembler
19602 @noindent
19603 The following example will generate a single assembly language statement, @code{nop}, which does nothing.  Despite its lack of run-time effect, the example will be useful in illustrating the basics of the Inline Assembler facility.
19605 @smallexample
19606 @group
19607 with System.Machine_Code; use System.Machine_Code;
19608 procedure Nothing is
19609 begin
19610    Asm ("nop");
19611 end Nothing;
19612 @end group
19613 @end smallexample
19615 @code{Asm} is a procedure declared in package @code{System.Machine_Code}; here it takes one parameter, a @emph{template string} that must be a static expression and that will form the generated instruction.
19616 @code{Asm} may be regarded as a compile-time procedure that parses the template string and additional parameters (none here), from which it generates a sequence of assembly language instructions.
19618 The examples in this chapter will illustrate several of the forms for invoking @code{Asm}; a complete specification of the syntax is found in the @cite{GNAT Reference Manual}.
19620 Under the standard GNAT conventions, the @code{Nothing} procedure should be in a file named @file{nothing.adb}.  You can build the executable in the usual way:
19621 @smallexample
19622 gnatmake nothing
19623 @end smallexample
19624 However, the interesting aspect of this example is not its run-time behavior but rather the
19625 generated assembly code.  To see this output, invoke the compiler as follows:
19626 @smallexample
19627    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
19628 @end smallexample
19629 where the options are:
19631 @table @code
19632 @item -c
19633 compile only (no bind or link)
19634 @item -S
19635 generate assembler listing
19636 @item -fomit-frame-pointer
19637 do not set up separate stack frames
19638 @item -gnatp
19639 do not add runtime checks
19640 @end table
19642 This gives a human-readable assembler version of the code. The resulting
19643 file will have the same name as the Ada source file, but with a @code{.s} extension.
19644 In our example, the file @file{nothing.s} has the following contents:
19646 @smallexample
19647 @group
19648 .file "nothing.adb"
19649 gcc2_compiled.:
19650 ___gnu_compiled_ada:
19651 .text
19652    .align 4
19653 .globl __ada_nothing
19654 __ada_nothing:
19655 #APP
19656    nop
19657 #NO_APP
19658    jmp L1
19659    .align 2,0x90
19661    ret
19662 @end group
19663 @end smallexample
19665 The assembly code you included is clearly indicated by
19666 the compiler, between the @code{#APP} and @code{#NO_APP}
19667 delimiters. The character before the 'APP' and 'NOAPP'
19668 can differ on different targets. For example, Linux uses '#APP' while
19669 on NT you will see '/APP'.
19671 If you make a mistake in your assembler code (such as using the
19672 wrong size modifier, or using a wrong operand for the instruction) GNAT
19673 will report this error in a temporary file, which will be deleted when
19674 the compilation is finished.  Generating an assembler file will help
19675 in such cases, since you can assemble this file separately using the
19676 @emph{as} assembler that comes with gcc.
19678 Assembling the file using the command
19680 @smallexample
19681 as @file{nothing.s}
19682 @end smallexample
19683 @noindent
19684 will give you error messages whose lines correspond to the assembler
19685 input file, so you can easily find and correct any mistakes you made.
19686 If there are no errors, @emph{as} will generate an object file @file{nothing.out}.
19688 @c ---------------------------------------------------------------------------
19689 @node Output Variables in Inline Assembler
19690 @section Output Variables in Inline Assembler
19692 @noindent
19693 The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements.
19695 @smallexample
19696 @group
19697 with Interfaces; use Interfaces;
19698 with Ada.Text_IO; use Ada.Text_IO;
19699 with System.Machine_Code; use System.Machine_Code;
19700 procedure Get_Flags is
19701    Flags : Unsigned_32;
19702    use ASCII;
19703 begin
19704    Asm ("pushfl"          & LF & HT & -- push flags on stack
19705         "popl %%eax"      & LF & HT & -- load eax with flags
19706         "movl %%eax, %0",             -- store flags in variable
19707         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19708    Put_Line ("Flags register:" & Flags'Img);
19709 end Get_Flags;
19710 @end group
19711 @end smallexample
19713 In order to have a nicely aligned assembly listing, we have separated
19714 multiple assembler statements in the Asm template string with linefeed (ASCII.LF)
19715 and horizontal tab (ASCII.HT) characters.  The resulting section of the
19716 assembly output file is:
19718 @smallexample
19719 @group
19720 #APP
19721    pushfl
19722    popl %eax
19723    movl %eax, -40(%ebp)
19724 #NO_APP
19725 @end group
19726 @end smallexample
19728 It would have been legal to write the Asm invocation as:
19730 @smallexample
19731 Asm ("pushfl popl %%eax movl %%eax, %0")
19732 @end smallexample
19734 but in the generated assembler file, this would come out as:
19736 @smallexample
19737 #APP
19738    pushfl popl %eax movl %eax, -40(%ebp)
19739 #NO_APP
19740 @end smallexample
19742 which is not so convenient for the human reader.
19744 We use Ada comments
19745 at the end of each line to explain what the assembler instructions
19746 actually do.  This is a useful convention.
19748 When writing Inline Assembler instructions, you need to precede each register and variable name with a percent sign.  Since the assembler already requires a percent sign at the beginning of a register name, you need two consecutive percent signs for such names in the Asm template string, thus @code{%%eax}.  In the generated assembly code, one of the percent signs will be stripped off.
19750 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output variables: operands you later define using @code{Input} or @code{Output} parameters to @code{Asm}.
19751 An output variable is illustrated in
19752 the third statement in the Asm template string:
19753 @smallexample
19754 movl %%eax, %0
19755 @end smallexample
19756 The intent is to store the contents of the eax register in a variable that can be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not necessarily work, since the compiler might optimize by using a register to hold Flags, and the expansion of the @code{movl} instruction would not be aware of this optimization.  The solution is not to store the result directly but rather to advise the compiler to choose the correct operand form; that is the purpose of the @code{%0} output variable.
19758 Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}:
19759 @smallexample
19760 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19761 @end smallexample
19763 The output is defined by the @code{Asm_Output} attribute of the target type; the general format is
19764 @smallexample
19765 Type'Asm_Output (constraint_string, variable_name)
19766 @end smallexample
19768 The constraint string directs the compiler how
19769 to store/access the associated variable.  In the example
19770 @smallexample
19771 Unsigned_32'Asm_Output ("=m", Flags);
19772 @end smallexample
19773 the @code{"m"} (memory) constraint tells the compiler that the variable
19774 @code{Flags} should be stored in a memory variable, thus preventing
19775 the optimizer from keeping it in a register.  In contrast,
19776 @smallexample
19777 Unsigned_32'Asm_Output ("=r", Flags);
19778 @end smallexample
19779 uses the @code{"r"} (register) constraint, telling the compiler to
19780 store the variable in a register.
19782 If the constraint is preceded by the equal character (@strong{=}), it tells the
19783 compiler that the variable will be used to store data into it.
19785 In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer
19786 to choose whatever it deems best.
19788 There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following:
19790 @table @code
19791 @item =
19792 output constraint
19793 @item g
19794 global (i.e. can be stored anywhere)
19795 @item m
19796 in memory
19797 @item I
19798 a constant
19799 @item a
19800 use eax
19801 @item b
19802 use ebx
19803 @item c
19804 use ecx
19805 @item d
19806 use edx
19807 @item S
19808 use esi
19809 @item D
19810 use edi
19811 @item r
19812 use one of eax, ebx, ecx or edx
19813 @item q
19814 use one of eax, ebx, ecx, edx, esi or edi
19815 @end table
19817 The full set of constraints is described in the gcc and @emph{as} documentation; note that it is possible to combine certain constraints in one constraint string.
19819 You specify the association of an output variable with an assembler operand through the @code{%}@emph{n} notation, where @emph{n} is a non-negative integer.  Thus in
19820 @smallexample
19821 @group
19822 Asm ("pushfl"          & LF & HT & -- push flags on stack
19823      "popl %%eax"      & LF & HT & -- load eax with flags
19824      "movl %%eax, %0",             -- store flags in variable
19825      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19826 @end group
19827 @end smallexample
19828 @noindent
19829 @code{%0} will be replaced in the expanded code by the appropriate operand,
19830 whatever
19831 the compiler decided for the @code{Flags} variable.
19833 In general, you may have any number of output variables:
19834 @itemize @bullet
19835 @item
19836 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
19837 @item
19838 Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes
19839 @end itemize
19841 For example:
19842 @smallexample
19843 @group
19844 Asm ("movl %%eax, %0" & LF & HT &
19845      "movl %%ebx, %1" & LF & HT &
19846      "movl %%ecx, %2",
19847      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
19848                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
19849                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
19850 @end group
19851 @end smallexample
19852 @noindent
19853 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program.
19855 As a variation on the @code{Get_Flags} example, we can use the constraints string to direct the compiler to store the eax register into the @code{Flags} variable, instead of including the store instruction explicitly in the @code{Asm} template string:
19857 @smallexample
19858 @group
19859 with Interfaces; use Interfaces;
19860 with Ada.Text_IO; use Ada.Text_IO;
19861 with System.Machine_Code; use System.Machine_Code;
19862 procedure Get_Flags_2 is
19863    Flags : Unsigned_32;
19864    use ASCII;
19865 begin
19866    Asm ("pushfl"      & LF & HT & -- push flags on stack
19867         "popl %%eax",             -- save flags in eax
19868         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
19869    Put_Line ("Flags register:" & Flags'Img);
19870 end Get_Flags_2;
19871 @end group
19872 @end smallexample
19874 @noindent
19875 The @code{"a"} constraint tells the compiler that the @code{Flags}
19876 variable will come from the eax register. Here is the resulting code:
19878 @smallexample
19879 @group
19880 #APP
19881    pushfl
19882    popl %eax
19883 #NO_APP
19884    movl %eax,-40(%ebp)
19885 @end group
19886 @end smallexample
19888 @noindent
19889 The compiler generated the store of eax into Flags after
19890 expanding the assembler code.
19892 Actually, there was no need to pop the flags into the eax register; more simply, we could just pop the flags directly into the program variable:
19894 @smallexample
19895 @group
19896 with Interfaces; use Interfaces;
19897 with Ada.Text_IO; use Ada.Text_IO;
19898 with System.Machine_Code; use System.Machine_Code;
19899 procedure Get_Flags_3 is
19900    Flags : Unsigned_32;
19901    use ASCII;
19902 begin
19903    Asm ("pushfl"  & LF & HT & -- push flags on stack
19904         "pop %0",             -- save flags in Flags
19905         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19906    Put_Line ("Flags register:" & Flags'Img);
19907 end Get_Flags_3;
19908 @end group
19909 @end smallexample
19911 @c ---------------------------------------------------------------------------
19912 @node Input Variables in Inline Assembler
19913 @section Input Variables in Inline Assembler
19915 @noindent
19916 The example in this section illustrates how to specify the source operands for assembly language statements.  The program simply increments its input value by 1:
19918 @smallexample
19919 @group
19920 with Interfaces; use Interfaces;
19921 with Ada.Text_IO; use Ada.Text_IO;
19922 with System.Machine_Code; use System.Machine_Code;
19923 procedure Increment is
19925    function Incr (Value : Unsigned_32) return Unsigned_32 is
19926       Result : Unsigned_32;
19927    begin
19928       Asm ("incl %0",
19929            Inputs  => Unsigned_32'Asm_Input ("a", Value),
19930            Outputs => Unsigned_32'Asm_Output ("=a", Result));
19931       return Result;
19932    end Incr;
19934    Value : Unsigned_32;
19936 begin
19937    Value := 5;
19938    Put_Line ("Value before is" & Value'Img);
19939    Value := Incr (Value);
19940    Put_Line ("Value after is" & Value'Img);
19941 end Increment;
19942 @end group
19943 @end smallexample
19945 The @code{Outputs} parameter to @code{Asm} specifies
19946 that the result will be in the eax register and that it is to be stored in the @code{Result}
19947 variable.
19949 The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an
19950 @code{Asm_Input} attribute. The
19951 @code{"="} constraint, indicating an output value, is not present.
19953 You can have multiple input variables, in the same way that you can have more
19954 than one output variable.
19956 The parameter count (%0, %1) etc, now starts at the first input
19957 statement, and continues with the output statements.
19958 When both parameters use the same variable, the
19959 compiler will treat them as the same %n operand, which is the case here.
19961 Just as the @code{Outputs} parameter causes the register to be stored into the
19962 target variable after execution of the assembler statements, so does the
19963 @code{Inputs} parameter cause its variable to be loaded into the register before execution
19964 of the
19965 assembler statements.
19967 Thus the effect of the @code{Asm} invocation is:
19968 @enumerate
19969 @item load the 32-bit value of @code{Value} into eax
19970 @item execute the @code{incl %eax} instruction
19971 @item store the contents of eax into the @code{Result} variable
19972 @end enumerate
19974 The resulting assembler file (with @code{-O2} optimization) contains:
19975 @smallexample
19976 @group
19977 _increment__incr.1:
19978    subl $4,%esp
19979    movl 8(%esp),%eax
19980 #APP
19981    incl %eax
19982 #NO_APP
19983    movl %eax,%edx
19984    movl %ecx,(%esp)
19985    addl $4,%esp
19986    ret
19987 @end group
19988 @end smallexample
19990 @c ---------------------------------------------------------------------------
19991 @node Inlining Inline Assembler Code
19992 @section Inlining Inline Assembler Code
19994 @noindent
19995 For a short subprogram such as the @code{Incr} function in the previous section, the overhead of the call and return (creating / deleting the stack frame)
19996 can be significant, compared to the amount of code in the subprogram body.
19997 A solution is to apply Ada's @code{Inline} pragma to the subprogram,
19998 which directs the compiler to expand invocations of the subprogram at the point(s)
19999 of call, instead of setting up a stack frame for out-of-line calls.
20000 Here is the resulting program:
20002 @smallexample
20003 @group
20004 with Interfaces; use Interfaces;
20005 with Ada.Text_IO; use Ada.Text_IO;
20006 with System.Machine_Code; use System.Machine_Code;
20007 procedure Increment_2 is
20009    function Incr (Value : Unsigned_32) return Unsigned_32 is
20010       Result : Unsigned_32;
20011    begin
20012       Asm ("incl %0",
20013            Inputs  => Unsigned_32'Asm_Input ("a", Value),
20014            Outputs => Unsigned_32'Asm_Output ("=a", Result));
20015       return Result;
20016    end Incr;
20017    pragma Inline (Increment);
20019    Value : Unsigned_32;
20021 begin
20022    Value := 5;
20023    Put_Line ("Value before is" & Value'Img);
20024    Value := Increment (Value);
20025    Put_Line ("Value after is" & Value'Img);
20026 end Increment_2;
20027 @end group
20028 @end smallexample
20030 Compile the program with both optimization (@code{-O2}) and inlining
20031 enabled (@option{-gnatpn} instead of @option{-gnatp}).
20033 The @code{Incr} function is still compiled as usual, but at the
20034 point in @code{Increment} where our function used to be called:
20036 @smallexample
20037 @group
20038 pushl %edi
20039 call _increment__incr.1
20040 @end group
20041 @end smallexample
20043 @noindent
20044 the code for the function body directly appears:
20046 @smallexample
20047 @group
20048 movl %esi,%eax
20049 #APP
20050    incl %eax
20051 #NO_APP
20052    movl %eax,%edx
20053 @end group
20054 @end smallexample
20056 @noindent
20057 thus saving the overhead of stack frame setup and an out-of-line call.
20059 @c ---------------------------------------------------------------------------
20060 @node Other Asm Functionality
20061 @section Other @code{Asm} Functionality
20063 @noindent
20064 This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations.
20066 @menu
20067 * The Clobber Parameter::
20068 * The Volatile Parameter::
20069 @end menu
20071 @c ---------------------------------------------------------------------------
20072 @node The Clobber Parameter
20073 @subsection The @code{Clobber} Parameter
20075 @noindent
20076 One of the dangers of intermixing assembly language and a compiled language such as Ada is
20077 that the compiler needs to be aware of which registers are being used by the assembly code.
20078 In some cases, such as the earlier examples, the constraint string is sufficient to
20079 indicate register usage (e.g. "a" for the eax register).  But more generally, the
20080 compiler needs an explicit identification of the registers that are used by the Inline
20081 Assembly statements.
20083 Using a register that the compiler doesn't know about
20084 could be a side effect of an instruction (like @code{mull}
20085 storing its result in both eax and edx).
20086 It can also arise from explicit register usage in your
20087 assembly code; for example:
20088 @smallexample
20089 @group
20090 Asm ("movl %0, %%ebx" & LF & HT &
20091      "movl %%ebx, %1",
20092      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
20093      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
20094 @end group
20095 @end smallexample
20096 @noindent
20097 where the compiler (since it does not analyze the @code{Asm} template string)
20098 does not know you are using the ebx register.
20100 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
20101 to identify the registers that will be used by your assembly code:
20103 @smallexample
20104 @group
20105 Asm ("movl %0, %%ebx" & LF & HT &
20106      "movl %%ebx, %1",
20107      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
20108      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
20109      Clobber => "ebx");
20110 @end group
20111 @end smallexample
20113 The Clobber parameter is a static string expression specifying the
20114 register(s) you are using.  Note that register names are @emph{not} prefixed by a percent sign.
20115 Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"}
20117 The @code{Clobber} parameter has several additional uses:
20118 @enumerate
20119 @item Use the "register" name @code{cc} to indicate that flags might have changed
20120 @item Use the "register" name @code{memory} if you changed a memory location
20121 @end enumerate
20123 @c ---------------------------------------------------------------------------
20124 @node The Volatile Parameter
20125 @subsection The @code{Volatile} Parameter
20126 @cindex Volatile parameter
20128 @noindent
20129 Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects.
20130 For example, when
20131 an @code{Asm} invocation with an input variable is inside a loop, the compiler might move
20132 the loading of the input variable outside the loop, regarding it as a
20133 one-time initialization.
20135 If this effect is not desired, you can disable such optimizations by setting the
20136 @code{Volatile} parameter to @code{True}; for example:
20138 @smallexample
20139 @group
20140 Asm ("movl %0, %%ebx" & LF & HT &
20141      "movl %%ebx, %1",
20142      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
20143      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
20144      Clobber  => "ebx",
20145      Volatile => True);
20146 @end group
20147 @end smallexample
20149 By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs}
20150 parameter.
20152 Although setting @code{Volatile} to @code{True} prevents unwanted optimizations,
20153 it will also disable other optimizations that might be important for efficiency.
20154 In general, you should set @code{Volatile} to @code{True} only if the compiler's
20155 optimizations have created problems.
20157 @c ---------------------------------------------------------------------------
20158 @node A Complete Example
20159 @section A Complete Example
20161 @noindent
20162 This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler
20163 capabilities.  It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}.
20164 The package declares a collection of functions that detect the properties of the 32-bit
20165 x86 processor that is running the program.  The main procedure invokes these functions
20166 and displays the information.
20168 The Intel_CPU package could be enhanced by adding functions to
20169 detect the type of x386 co-processor, the processor caching options and
20170 special operations such as the SIMD extensions.
20172 Although the Intel_CPU package has been written for 32-bit Intel
20173 compatible CPUs, it is OS neutral. It has been tested on DOS,
20174 Windows/NT and Linux.
20176 @menu
20177 * Check_CPU Procedure::
20178 * Intel_CPU Package Specification::
20179 * Intel_CPU Package Body::
20180 @end menu
20182 @c ---------------------------------------------------------------------------
20183 @node Check_CPU Procedure
20184 @subsection @code{Check_CPU} Procedure
20185 @cindex Check_CPU procedure
20187 @smallexample
20188 ---------------------------------------------------------------------
20189 --                                                                 --
20190 --  Uses the Intel_CPU package to identify the CPU the program is  --
20191 --  running on, and some of the features it supports.              --
20192 --                                                                 --
20193 ---------------------------------------------------------------------
20195 with Intel_CPU;                     --  Intel CPU detection functions
20196 with Ada.Text_IO;                   --  Standard text I/O
20197 with Ada.Command_Line;              --  To set the exit status
20199 procedure Check_CPU is
20201    Type_Found : Boolean := False;
20202    --  Flag to indicate that processor was identified
20204    Features   : Intel_CPU.Processor_Features;
20205    --  The processor features
20207    Signature  : Intel_CPU.Processor_Signature;
20208    --  The processor type signature
20210 begin
20212    -----------------------------------
20213    --  Display the program banner.  --
20214    -----------------------------------
20216    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
20217                          ": check Intel CPU version and features, v1.0");
20218    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
20219    Ada.Text_IO.New_Line;
20221    -----------------------------------------------------------------------
20222    --  We can safely start with the assumption that we are on at least  --
20223    --  a x386 processor. If the CPUID instruction is present, then we   --
20224    --  have a later processor type.                                     --
20225    -----------------------------------------------------------------------
20227    if Intel_CPU.Has_CPUID = False then
20229       --  No CPUID instruction, so we assume this is indeed a x386
20230       --  processor. We can still check if it has a FP co-processor.
20231       if Intel_CPU.Has_FPU then
20232          Ada.Text_IO.Put_Line
20233            ("x386-type processor with a FP co-processor");
20234       else
20235          Ada.Text_IO.Put_Line
20236            ("x386-type processor without a FP co-processor");
20237       end if;  --  check for FPU
20239       --  Program done
20240       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
20241       return;
20243    end if;  --  check for CPUID
20245    -----------------------------------------------------------------------
20246    --  If CPUID is supported, check if this is a true Intel processor,  --
20247    --  if it is not, display a warning.                                 --
20248    -----------------------------------------------------------------------
20250    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
20251       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
20252       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
20253    end if;  --  check if Intel
20255    ----------------------------------------------------------------------
20256    --  With the CPUID instruction present, we can assume at least a    --
20257    --  x486 processor. If the CPUID support level is < 1 then we have  --
20258    --  to leave it at that.                                            --
20259    ----------------------------------------------------------------------
20261    if Intel_CPU.CPUID_Level < 1 then
20263       --  Ok, this is a x486 processor. we still can get the Vendor ID
20264       Ada.Text_IO.Put_Line ("x486-type processor");
20265       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
20267       --  We can also check if there is a FPU present
20268       if Intel_CPU.Has_FPU then
20269          Ada.Text_IO.Put_Line ("Floating-Point support");
20270       else
20271          Ada.Text_IO.Put_Line ("No Floating-Point support");
20272       end if;  --  check for FPU
20274       --  Program done
20275       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
20276       return;
20278    end if;  --  check CPUID level
20280    ---------------------------------------------------------------------
20281    --  With a CPUID level of 1 we can use the processor signature to  --
20282    --  determine it's exact type.                                     --
20283    ---------------------------------------------------------------------
20285    Signature := Intel_CPU.Signature;
20287    ----------------------------------------------------------------------
20288    --  Ok, now we go into a lot of messy comparisons to get the        --
20289    --  processor type. For clarity, no attememt to try to optimize the --
20290    --  comparisons has been made. Note that since Intel_CPU does not   --
20291    --  support getting cache info, we cannot distinguish between P5    --
20292    --  and Celeron types yet.                                          --
20293    ----------------------------------------------------------------------
20295    --  x486SL
20296    if Signature.Processor_Type = 2#00#   and
20297      Signature.Family          = 2#0100# and
20298      Signature.Model           = 2#0100# then
20299       Type_Found := True;
20300       Ada.Text_IO.Put_Line ("x486SL processor");
20301    end if;
20303    --  x486DX2 Write-Back
20304    if Signature.Processor_Type = 2#00#   and
20305      Signature.Family          = 2#0100# and
20306      Signature.Model           = 2#0111# then
20307       Type_Found := True;
20308       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
20309    end if;
20311    --  x486DX4
20312    if Signature.Processor_Type = 2#00#   and
20313      Signature.Family          = 2#0100# and
20314      Signature.Model           = 2#1000# then
20315       Type_Found := True;
20316       Ada.Text_IO.Put_Line ("x486DX4 processor");
20317    end if;
20319    --  x486DX4 Overdrive
20320    if Signature.Processor_Type = 2#01#   and
20321      Signature.Family          = 2#0100# and
20322      Signature.Model           = 2#1000# then
20323       Type_Found := True;
20324       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
20325    end if;
20327    --  Pentium (60, 66)
20328    if Signature.Processor_Type = 2#00#   and
20329      Signature.Family          = 2#0101# and
20330      Signature.Model           = 2#0001# then
20331       Type_Found := True;
20332       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
20333    end if;
20335    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
20336    if Signature.Processor_Type = 2#00#   and
20337      Signature.Family          = 2#0101# and
20338      Signature.Model           = 2#0010# then
20339       Type_Found := True;
20340       Ada.Text_IO.Put_Line
20341         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
20342    end if;
20344    --  Pentium OverDrive (60, 66)
20345    if Signature.Processor_Type = 2#01#   and
20346      Signature.Family          = 2#0101# and
20347      Signature.Model           = 2#0001# then
20348       Type_Found := True;
20349       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
20350    end if;
20352    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
20353    if Signature.Processor_Type = 2#01#   and
20354      Signature.Family          = 2#0101# and
20355      Signature.Model           = 2#0010# then
20356       Type_Found := True;
20357       Ada.Text_IO.Put_Line
20358         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
20359    end if;
20361    --  Pentium OverDrive processor for x486 processor-based systems
20362    if Signature.Processor_Type = 2#01#   and
20363      Signature.Family          = 2#0101# and
20364      Signature.Model           = 2#0011# then
20365       Type_Found := True;
20366       Ada.Text_IO.Put_Line
20367         ("Pentium OverDrive processor for x486 processor-based systems");
20368    end if;
20370    --  Pentium processor with MMX technology (166, 200)
20371    if Signature.Processor_Type = 2#00#   and
20372      Signature.Family          = 2#0101# and
20373      Signature.Model           = 2#0100# then
20374       Type_Found := True;
20375       Ada.Text_IO.Put_Line
20376         ("Pentium processor with MMX technology (166, 200)");
20377    end if;
20379    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
20380    if Signature.Processor_Type = 2#01#   and
20381      Signature.Family          = 2#0101# and
20382      Signature.Model           = 2#0100# then
20383       Type_Found := True;
20384       Ada.Text_IO.Put_Line
20385         ("Pentium OverDrive processor with MMX " &
20386          "technology for Pentium processor (75, 90, 100, 120, 133)");
20387    end if;
20389    --  Pentium Pro processor
20390    if Signature.Processor_Type = 2#00#   and
20391      Signature.Family          = 2#0110# and
20392      Signature.Model           = 2#0001# then
20393       Type_Found := True;
20394       Ada.Text_IO.Put_Line ("Pentium Pro processor");
20395    end if;
20397    --  Pentium II processor, model 3
20398    if Signature.Processor_Type = 2#00#   and
20399      Signature.Family          = 2#0110# and
20400      Signature.Model           = 2#0011# then
20401       Type_Found := True;
20402       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
20403    end if;
20405    --  Pentium II processor, model 5 or Celeron processor
20406    if Signature.Processor_Type = 2#00#   and
20407      Signature.Family          = 2#0110# and
20408      Signature.Model           = 2#0101# then
20409       Type_Found := True;
20410       Ada.Text_IO.Put_Line
20411         ("Pentium II processor, model 5 or Celeron processor");
20412    end if;
20414    --  Pentium Pro OverDrive processor
20415    if Signature.Processor_Type = 2#01#   and
20416      Signature.Family          = 2#0110# and
20417      Signature.Model           = 2#0011# then
20418       Type_Found := True;
20419       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
20420    end if;
20422    --  If no type recognized, we have an unknown. Display what
20423    --  we _do_ know
20424    if Type_Found = False then
20425       Ada.Text_IO.Put_Line ("Unknown processor");
20426    end if;
20428    -----------------------------------------
20429    --  Display processor stepping level.  --
20430    -----------------------------------------
20432    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
20434    ---------------------------------
20435    --  Display vendor ID string.  --
20436    ---------------------------------
20438    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
20440    ------------------------------------
20441    --  Get the processors features.  --
20442    ------------------------------------
20444    Features := Intel_CPU.Features;
20446    -----------------------------
20447    --  Check for a FPU unit.  --
20448    -----------------------------
20450    if Features.FPU = True then
20451       Ada.Text_IO.Put_Line ("Floating-Point unit available");
20452    else
20453       Ada.Text_IO.Put_Line ("no Floating-Point unit");
20454    end if;  --  check for FPU
20456    --------------------------------
20457    --  List processor features.  --
20458    --------------------------------
20460    Ada.Text_IO.Put_Line ("Supported features: ");
20462    --  Virtual Mode Extension
20463    if Features.VME = True then
20464       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
20465    end if;
20467    --  Debugging Extension
20468    if Features.DE = True then
20469       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
20470    end if;
20472    --  Page Size Extension
20473    if Features.PSE = True then
20474       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
20475    end if;
20477    --  Time Stamp Counter
20478    if Features.TSC = True then
20479       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
20480    end if;
20482    --  Model Specific Registers
20483    if Features.MSR = True then
20484       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
20485    end if;
20487    --  Physical Address Extension
20488    if Features.PAE = True then
20489       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
20490    end if;
20492    --  Machine Check Extension
20493    if Features.MCE = True then
20494       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
20495    end if;
20497    --  CMPXCHG8 instruction supported
20498    if Features.CX8 = True then
20499       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
20500    end if;
20502    --  on-chip APIC hardware support
20503    if Features.APIC = True then
20504       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
20505    end if;
20507    --  Fast System Call
20508    if Features.SEP = True then
20509       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
20510    end if;
20512    --  Memory Type Range Registers
20513    if Features.MTRR = True then
20514       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
20515    end if;
20517    --  Page Global Enable
20518    if Features.PGE = True then
20519       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
20520    end if;
20522    --  Machine Check Architecture
20523    if Features.MCA = True then
20524       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
20525    end if;
20527    --  Conditional Move Instruction Supported
20528    if Features.CMOV = True then
20529       Ada.Text_IO.Put_Line
20530         ("    CMOV   - Conditional Move Instruction Supported");
20531    end if;
20533    --  Page Attribute Table
20534    if Features.PAT = True then
20535       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
20536    end if;
20538    --  36-bit Page Size Extension
20539    if Features.PSE_36 = True then
20540       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
20541    end if;
20543    --  MMX technology supported
20544    if Features.MMX = True then
20545       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
20546    end if;
20548    --  Fast FP Save and Restore
20549    if Features.FXSR = True then
20550       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
20551    end if;
20553    ---------------------
20554    --  Program done.  --
20555    ---------------------
20557    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
20559 exception
20561    when others =>
20562       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
20563       raise;
20565 end Check_CPU;
20566 @end smallexample
20568 @c ---------------------------------------------------------------------------
20569 @node Intel_CPU Package Specification
20570 @subsection @code{Intel_CPU} Package Specification
20571 @cindex Intel_CPU package specification
20573 @smallexample
20574 -------------------------------------------------------------------------
20575 --                                                                     --
20576 --  file: intel_cpu.ads                                                --
20577 --                                                                     --
20578 --           *********************************************             --
20579 --           * WARNING: for 32-bit Intel processors only *             --
20580 --           *********************************************             --
20581 --                                                                     --
20582 --  This package contains a number of subprograms that are useful in   --
20583 --  determining the Intel x86 CPU (and the features it supports) on    --
20584 --  which the program is running.                                      --
20585 --                                                                     --
20586 --  The package is based upon the information given in the Intel       --
20587 --  Application Note AP-485: "Intel Processor Identification and the   --
20588 --  CPUID Instruction" as of April 1998. This application note can be  --
20589 --  found on www.intel.com.                                            --
20590 --                                                                     --
20591 --  It currently deals with 32-bit processors only, will not detect    --
20592 --  features added after april 1998, and does not guarantee proper     --
20593 --  results on Intel-compatible processors.                            --
20594 --                                                                     --
20595 --  Cache info and x386 fpu type detection are not supported.          --
20596 --                                                                     --
20597 --  This package does not use any privileged instructions, so should   --
20598 --  work on any OS running on a 32-bit Intel processor.                --
20599 --                                                                     --
20600 -------------------------------------------------------------------------
20602 with Interfaces;             use Interfaces;
20603 --  for using unsigned types
20605 with System.Machine_Code;    use System.Machine_Code;
20606 --  for using inline assembler code
20608 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
20609 --  for inserting control characters
20611 package Intel_CPU is
20613    ----------------------
20614    --  Processor bits  --
20615    ----------------------
20617    subtype Num_Bits is Natural range 0 .. 31;
20618    --  the number of processor bits (32)
20620    --------------------------
20621    --  Processor register  --
20622    --------------------------
20624    --  define a processor register type for easy access to
20625    --  the individual bits
20627    type Processor_Register is array (Num_Bits) of Boolean;
20628    pragma Pack (Processor_Register);
20629    for Processor_Register'Size use 32;
20631    -------------------------
20632    --  Unsigned register  --
20633    -------------------------
20635    --  define a processor register type for easy access to
20636    --  the individual bytes
20638    type Unsigned_Register is
20639       record
20640          L1 : Unsigned_8;
20641          H1 : Unsigned_8;
20642          L2 : Unsigned_8;
20643          H2 : Unsigned_8;
20644       end record;
20646    for Unsigned_Register use
20647       record
20648          L1 at 0 range  0 ..  7;
20649          H1 at 0 range  8 .. 15;
20650          L2 at 0 range 16 .. 23;
20651          H2 at 0 range 24 .. 31;
20652       end record;
20654    for Unsigned_Register'Size use 32;
20656    ---------------------------------
20657    --  Intel processor vendor ID  --
20658    ---------------------------------
20660    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
20661    --  indicates an Intel manufactured processor
20663    ------------------------------------
20664    --  Processor signature register  --
20665    ------------------------------------
20667    --  a register type to hold the processor signature
20669    type Processor_Signature is
20670       record
20671          Stepping       : Natural range 0 .. 15;
20672          Model          : Natural range 0 .. 15;
20673          Family         : Natural range 0 .. 15;
20674          Processor_Type : Natural range 0 .. 3;
20675          Reserved       : Natural range 0 .. 262143;
20676       end record;
20678    for Processor_Signature use
20679       record
20680          Stepping       at 0 range  0 ..  3;
20681          Model          at 0 range  4 ..  7;
20682          Family         at 0 range  8 .. 11;
20683          Processor_Type at 0 range 12 .. 13;
20684          Reserved       at 0 range 14 .. 31;
20685       end record;
20687    for Processor_Signature'Size use 32;
20689    -----------------------------------
20690    --  Processor features register  --
20691    -----------------------------------
20693    --  a processor register to hold the processor feature flags
20695    type Processor_Features is
20696       record
20697          FPU    : Boolean;                --  floating point unit on chip
20698          VME    : Boolean;                --  virtual mode extension
20699          DE     : Boolean;                --  debugging extension
20700          PSE    : Boolean;                --  page size extension
20701          TSC    : Boolean;                --  time stamp counter
20702          MSR    : Boolean;                --  model specific registers
20703          PAE    : Boolean;                --  physical address extension
20704          MCE    : Boolean;                --  machine check extension
20705          CX8    : Boolean;                --  cmpxchg8 instruction
20706          APIC   : Boolean;                --  on-chip apic hardware
20707          Res_1  : Boolean;                --  reserved for extensions
20708          SEP    : Boolean;                --  fast system call
20709          MTRR   : Boolean;                --  memory type range registers
20710          PGE    : Boolean;                --  page global enable
20711          MCA    : Boolean;                --  machine check architecture
20712          CMOV   : Boolean;                --  conditional move supported
20713          PAT    : Boolean;                --  page attribute table
20714          PSE_36 : Boolean;                --  36-bit page size extension
20715          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
20716          MMX    : Boolean;                --  MMX technology supported
20717          FXSR   : Boolean;                --  fast FP save and restore
20718          Res_3  : Natural range 0 .. 127; --  reserved for extensions
20719       end record;
20721    for Processor_Features use
20722       record
20723          FPU    at 0 range  0 ..  0;
20724          VME    at 0 range  1 ..  1;
20725          DE     at 0 range  2 ..  2;
20726          PSE    at 0 range  3 ..  3;
20727          TSC    at 0 range  4 ..  4;
20728          MSR    at 0 range  5 ..  5;
20729          PAE    at 0 range  6 ..  6;
20730          MCE    at 0 range  7 ..  7;
20731          CX8    at 0 range  8 ..  8;
20732          APIC   at 0 range  9 ..  9;
20733          Res_1  at 0 range 10 .. 10;
20734          SEP    at 0 range 11 .. 11;
20735          MTRR   at 0 range 12 .. 12;
20736          PGE    at 0 range 13 .. 13;
20737          MCA    at 0 range 14 .. 14;
20738          CMOV   at 0 range 15 .. 15;
20739          PAT    at 0 range 16 .. 16;
20740          PSE_36 at 0 range 17 .. 17;
20741          Res_2  at 0 range 18 .. 22;
20742          MMX    at 0 range 23 .. 23;
20743          FXSR   at 0 range 24 .. 24;
20744          Res_3  at 0 range 25 .. 31;
20745       end record;
20747    for Processor_Features'Size use 32;
20749    -------------------
20750    --  Subprograms  --
20751    -------------------
20753    function Has_FPU return Boolean;
20754    --  return True if a FPU is found
20755    --  use only if CPUID is not supported
20757    function Has_CPUID return Boolean;
20758    --  return True if the processor supports the CPUID instruction
20760    function CPUID_Level return Natural;
20761    --  return the CPUID support level (0, 1 or 2)
20762    --  can only be called if the CPUID instruction is supported
20764    function Vendor_ID return String;
20765    --  return the processor vendor identification string
20766    --  can only be called if the CPUID instruction is supported
20768    function Signature return Processor_Signature;
20769    --  return the processor signature
20770    --  can only be called if the CPUID instruction is supported
20772    function Features return Processor_Features;
20773    --  return the processors features
20774    --  can only be called if the CPUID instruction is supported
20776 private
20778    ------------------------
20779    --  EFLAGS bit names  --
20780    ------------------------
20782    ID_Flag : constant Num_Bits := 21;
20783    --  ID flag bit
20785 end Intel_CPU;
20786 @end smallexample
20788 @c ---------------------------------------------------------------------------
20789 @node Intel_CPU Package Body
20790 @subsection @code{Intel_CPU} Package Body
20791 @cindex Intel_CPU package body
20793 @smallexample
20794 package body Intel_CPU is
20796    ---------------------------
20797    --  Detect FPU presence  --
20798    ---------------------------
20800    --  There is a FPU present if we can set values to the FPU Status
20801    --  and Control Words.
20803    function Has_FPU return Boolean is
20805       Register : Unsigned_16;
20806       --  processor register to store a word
20808    begin
20810       --  check if we can change the status word
20811       Asm (
20813            --  the assembler code
20814            "finit"              & LF & HT &    --  reset status word
20815            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
20816            "fnstsw %0"          & LF & HT &    --  save status word
20817            "movw %%ax, %0",                    --  store status word
20819            --  output stored in Register
20820            --  register must be a memory location
20821            Outputs => Unsigned_16'Asm_output ("=m", Register),
20823            --  tell compiler that we used eax
20824            Clobber => "eax");
20826       --  if the status word is zero, there is no FPU
20827       if Register = 0 then
20828          return False;   --  no status word
20829       end if;  --  check status word value
20831       --  check if we can get the control word
20832       Asm (
20834            --  the assembler code
20835            "fnstcw %0",   --  save the control word
20837            --  output into Register
20838            --  register must be a memory location
20839            Outputs => Unsigned_16'Asm_output ("=m", Register));
20841       --  check the relevant bits
20842       if (Register and 16#103F#) /= 16#003F# then
20843          return False;   --  no control word
20844       end if;  --  check control word value
20846       --  FPU found
20847       return True;
20849    end Has_FPU;
20851    --------------------------------
20852    --  Detect CPUID instruction  --
20853    --------------------------------
20855    --  The processor supports the CPUID instruction if it is possible
20856    --  to change the value of ID flag bit in the EFLAGS register.
20858    function Has_CPUID return Boolean is
20860       Original_Flags, Modified_Flags : Processor_Register;
20861       --  EFLAG contents before and after changing the ID flag
20863    begin
20865       --  try flipping the ID flag in the EFLAGS register
20866       Asm (
20868            --  the assembler code
20869            "pushfl"               & LF & HT &     --  push EFLAGS on stack
20870            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
20871            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
20872            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
20873            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
20874            "popfl"                & LF & HT &     --  load EFLAGS register
20875            "pushfl"               & LF & HT &     --  push EFLAGS on stack
20876            "pop %1",                              --  save EFLAGS content
20878            --  output values, may be anything
20879            --  Original_Flags is %0
20880            --  Modified_Flags is %1
20881            Outputs =>
20882               (Processor_Register'Asm_output ("=g", Original_Flags),
20883                Processor_Register'Asm_output ("=g", Modified_Flags)),
20885            --  tell compiler eax is destroyed
20886            Clobber => "eax");
20888       --  check if CPUID is supported
20889       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
20890          return True;   --  ID flag was modified
20891       else
20892          return False;  --  ID flag unchanged
20893       end if;  --  check for CPUID
20895    end Has_CPUID;
20897    -------------------------------
20898    --  Get CPUID support level  --
20899    -------------------------------
20901    function CPUID_Level return Natural is
20903       Level : Unsigned_32;
20904       --  returned support level
20906    begin
20908       --  execute CPUID, storing the results in the Level register
20909       Asm (
20911            --  the assembler code
20912            "cpuid",    --  execute CPUID
20914            --  zero is stored in eax
20915            --  returning the support level in eax
20916            Inputs => Unsigned_32'Asm_input ("a", 0),
20918            --  eax is stored in Level
20919            Outputs => Unsigned_32'Asm_output ("=a", Level),
20921            --  tell compiler ebx, ecx and edx registers are destroyed
20922            Clobber => "ebx, ecx, edx");
20924       --  return the support level
20925       return Natural (Level);
20927    end CPUID_Level;
20929    --------------------------------
20930    --  Get CPU Vendor ID String  --
20931    --------------------------------
20933    --  The vendor ID string is returned in the ebx, ecx and edx register
20934    --  after executing the CPUID instruction with eax set to zero.
20935    --  In case of a true Intel processor the string returned is
20936    --  "GenuineIntel"
20938    function Vendor_ID return String is
20940       Ebx, Ecx, Edx : Unsigned_Register;
20941       --  registers containing the vendor ID string
20943       Vendor_ID : String (1 .. 12);
20944       -- the vendor ID string
20946    begin
20948       --  execute CPUID, storing the results in the processor registers
20949       Asm (
20951            --  the assembler code
20952            "cpuid",    --  execute CPUID
20954            --  zero stored in eax
20955            --  vendor ID string returned in ebx, ecx and edx
20956            Inputs => Unsigned_32'Asm_input ("a", 0),
20958            --  ebx is stored in Ebx
20959            --  ecx is stored in Ecx
20960            --  edx is stored in Edx
20961            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
20962                        Unsigned_Register'Asm_output ("=c", Ecx),
20963                        Unsigned_Register'Asm_output ("=d", Edx)));
20965       --  now build the vendor ID string
20966       Vendor_ID( 1) := Character'Val (Ebx.L1);
20967       Vendor_ID( 2) := Character'Val (Ebx.H1);
20968       Vendor_ID( 3) := Character'Val (Ebx.L2);
20969       Vendor_ID( 4) := Character'Val (Ebx.H2);
20970       Vendor_ID( 5) := Character'Val (Edx.L1);
20971       Vendor_ID( 6) := Character'Val (Edx.H1);
20972       Vendor_ID( 7) := Character'Val (Edx.L2);
20973       Vendor_ID( 8) := Character'Val (Edx.H2);
20974       Vendor_ID( 9) := Character'Val (Ecx.L1);
20975       Vendor_ID(10) := Character'Val (Ecx.H1);
20976       Vendor_ID(11) := Character'Val (Ecx.L2);
20977       Vendor_ID(12) := Character'Val (Ecx.H2);
20979       --  return string
20980       return Vendor_ID;
20982    end Vendor_ID;
20984    -------------------------------
20985    --  Get processor signature  --
20986    -------------------------------
20988    function Signature return Processor_Signature is
20990       Result : Processor_Signature;
20991       --  processor signature returned
20993    begin
20995       --  execute CPUID, storing the results in the Result variable
20996       Asm (
20998            --  the assembler code
20999            "cpuid",    --  execute CPUID
21001            --  one is stored in eax
21002            --  processor signature returned in eax
21003            Inputs => Unsigned_32'Asm_input ("a", 1),
21005            --  eax is stored in Result
21006            Outputs => Processor_Signature'Asm_output ("=a", Result),
21008            --  tell compiler that ebx, ecx and edx are also destroyed
21009            Clobber => "ebx, ecx, edx");
21011       --  return processor signature
21012       return Result;
21014    end Signature;
21016    ------------------------------
21017    --  Get processor features  --
21018    ------------------------------
21020    function Features return Processor_Features is
21022       Result : Processor_Features;
21023       --  processor features returned
21025    begin
21027       --  execute CPUID, storing the results in the Result variable
21028       Asm (
21030            --  the assembler code
21031            "cpuid",    --  execute CPUID
21033            --  one stored in eax
21034            --  processor features returned in edx
21035            Inputs => Unsigned_32'Asm_input ("a", 1),
21037            --  edx is stored in Result
21038            Outputs => Processor_Features'Asm_output ("=d", Result),
21040            --  tell compiler that ebx and ecx are also destroyed
21041            Clobber => "ebx, ecx");
21043       --  return processor signature
21044       return Result;
21046    end Features;
21048 end Intel_CPU;
21049 @end smallexample
21050 @c END OF INLINE ASSEMBLER CHAPTER
21051 @c ===============================
21053 @ifset wnt
21054 @node Microsoft Windows Topics
21055 @chapter Microsoft Windows Topics
21056 @cindex Windows NT
21057 @cindex Windows 95
21058 @cindex Windows 98
21060 @noindent
21061 This chapter describes topics that are specific to the Microsoft Windows
21062 platforms (NT, 95 and 98).
21064 @menu
21065 * Using GNAT on Windows::
21066 * GNAT Setup Tool::
21067 * CONSOLE and WINDOWS subsystems::
21068 * Temporary Files::
21069 * Mixed-Language Programming on Windows::
21070 * Windows Calling Conventions::
21071 * Introduction to Dynamic Link Libraries (DLLs)::
21072 * Using DLLs with GNAT::
21073 * Building DLLs with GNAT::
21074 * GNAT and Windows Resources::
21075 * Debugging a DLL::
21076 * GNAT and COM/DCOM Objects::
21077 @end menu
21079 @node Using GNAT on Windows
21080 @section Using GNAT on Windows
21082 @noindent
21083 One of the strengths of the GNAT technology is that its tool set
21084 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
21085 @code{gdb} debugger, etc.) is used in the same way regardless of the
21086 platform.
21088 On Windows this tool set is complemented by a number of Microsoft-specific
21089 tools that have been provided to facilitate interoperability with Windows
21090 when this is required. With these tools:
21092 @itemize @bullet
21094 @item
21095 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
21096 subsystems.
21098 @item
21099 You can use any Dynamically Linked Library (DLL) in your Ada code (both
21100 relocatable and non-relocatable DLLs are supported).
21102 @item
21103 You can build Ada DLLs for use in other applications. These applications
21104 can be written in a language other than Ada (e.g., C, C++, etc). Again both
21105 relocatable and non-relocatable Ada DLLs are supported.
21107 @item
21108 You can include Windows resources in your Ada application.
21110 @item
21111 You can use or create COM/DCOM objects.
21112 @end itemize
21114 @noindent
21115 Immediately below are listed all known general GNAT-for-Windows restrictions.
21116 Other restrictions about specific features like Windows Resources and DLLs
21117 are listed in separate sections below.
21119 @itemize @bullet
21121 @item
21122 It is not possible to use @code{GetLastError} and @code{SetLastError}
21123 when tasking, protected records, or exceptions are used. In these
21124 cases, in order to implement Ada semantics, the GNAT run-time system
21125 calls certain Win32 routines that set the last error variable to 0 upon
21126 success. It should be possible to use @code{GetLastError} and
21127 @code{SetLastError} when tasking, protected record, and exception
21128 features are not used, but it is not guaranteed to work.
21129 @end itemize
21131 @node GNAT Setup Tool
21132 @section GNAT Setup Tool
21133 @cindex GNAT Setup Tool
21134 @cindex Setup Tool
21135 @cindex gnatreg
21137 @menu
21138 * Command-line arguments::
21139 * Creating a network installation of GNAT::
21140 * Registering and unregistering additional libraries::
21141 @end menu
21143 @noindent
21144 GNAT installation on Windows is using the Windows registry in order to
21145 locate proper executables and standard libraries. GNAT setup tool, called
21146 @code{gnatreg.exe}, is provided in order to display and modify GNAT-specific
21147 registry entries, allowing to create network GNAT installations, modify the
21148 locations of GNAT components, as well as register and unregister additional
21149 libraries for use with GNAT.
21151 @node Command-line arguments
21152 @subsection Command-line arguments
21154 @noindent
21155 @code{gnatreg [switches] [parameter]}
21157 @noindent
21158 Specifying no arguments causes gnatreg to display current configuration.
21160 @noindent
21161 The switches understood by gnatreg are:
21162 @table @asis
21163 @item  -h
21164        print the help message
21165 @item  -a
21166        add a standard library
21167 @item  -r
21168        remove a standard library
21169 @item  -f
21170        force creation of keys if they don't exist
21171 @item  -q
21172        be quiet/terse
21173 @end table
21175 @node Creating a network installation of GNAT
21176 @subsection Creating a network installation of GNAT
21178 @noindent
21179 Make sure the system on which GNAT is installed is accessible from the
21180 current machine.
21182 Use the command
21184 @code{@ @ @ gnatreg -f \\server\sharename\path}
21186 in order to setup the registry entries on a current machine.
21188 For example, if GNAT is installed in @file{\GNAT} directory of a share location
21189 called @file{c-drive} on a machine @file{LOKI}, the command that can be used on
21190 other machines to allow the remote use of GNAT is,
21192 @code{@ @ @ gnatreg -f \\loki\c-drive\gnat}
21194 Remember to also add @file{\\loki\c-drive\gnat\bin} in front of your PATH variable.
21196 Be aware that every compilation using the network installation results in the
21197 transfer of large amounts of data across the network and may cause serious
21198 performance penalty.
21200 @node Registering and unregistering additional libraries
21201 @subsection Registering and unregistering additional libraries
21203 @noindent
21204 To register a standard library use a command:
21206 @code{@ @ @ gnatreg -a <library_name>=<path>}
21208 For example:
21210 @code{@ @ @ gnatreg -a WIN32ADA=c:\Win32Ada}
21212 The libraries registered in this manner will be treated like standard libraries
21213 by the compiler (i.e. they don't have to be specified in -I and -l switches to
21214 various GNAT tools).
21216 To unregister a library, enter
21217 @code{   gnatreg -r <library_name>}
21219 e.g.,
21220 @code{   gnatreg -r WIN32ADA}
21222 @node CONSOLE and WINDOWS subsystems
21223 @section CONSOLE and WINDOWS subsystems
21224 @cindex CONSOLE Subsystem
21225 @cindex WINDOWS Subsystem
21226 @cindex -mwindows
21228 @noindent
21229 Under Windows there is two main subsystems. The @code{CONSOLE} subsystem
21230 (which is the default subsystem) will always create a console when
21231 launching the application. This is not something desirable when the
21232 application has a Windows GUI. To get rid of this console the
21233 application must be using the @code{WINDOWS} subsystem. To do so
21234 the @code{-mwindows} linker option must be specified.
21236 @smallexample
21237 $ gnatmake winprog -largs -mwindows
21238 @end smallexample
21240 @node Temporary Files
21241 @section Temporary Files
21242 @cindex Temporary files
21244 @noindent
21245 It is possible to control where temporary files gets created by setting
21246 the TMP environment variable. The file will be created:
21248 @itemize
21249 @item Under the directory pointed to by the TMP environment variable if
21250 this directory exists.
21252 @item Under c:\temp, if the TMP environment variable is not set (or not
21253 pointing to a directory) and if this directory exists.
21255 @item Under the current working directory otherwise.
21256 @end itemize
21258 @noindent
21259 This allows you to determine exactly where the temporary
21260 file will be created. This is particularly useful in networked
21261 environments where you may not have write access to some
21262 directories.
21264 @node Mixed-Language Programming on Windows
21265 @section Mixed-Language Programming on Windows
21267 @noindent
21268 Developing pure Ada applications on Windows is no different than on
21269 other GNAT-supported platforms. However, when developing or porting an
21270 application that contains a mix of Ada and C/C++, the choice of your
21271 Windows C/C++ development environment conditions your overall
21272 interoperability strategy.
21274 If you use @code{gcc} to compile the non-Ada part of your application,
21275 there are no Windows-specific restrictions that affect the overall
21276 interoperability with your Ada code. If you plan to use
21277 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
21278 the following limitations:
21280 @itemize @bullet
21281 @item
21282 You cannot link your Ada code with an object or library generated with
21283 Microsoft tools if these use the @code{.tls} section (Thread Local
21284 Storage section) since the GNAT linker does not yet support this section.
21286 @item
21287 You cannot link your Ada code with an object or library generated with
21288 Microsoft tools if these use I/O routines other than those provided in
21289 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
21290 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
21291 libraries can cause a conflict with @code{msvcrt.dll} services. For
21292 instance Visual C++ I/O stream routines conflict with those in
21293 @code{msvcrt.dll}.
21294 @end itemize
21296 @noindent
21297 If you do want to use the Microsoft tools for your non-Ada code and hit one
21298 of the above limitations, you have two choices:
21300 @enumerate
21301 @item
21302 Encapsulate your non Ada code in a DLL to be linked with your Ada
21303 application. In this case, use the Microsoft or whatever environment to
21304 build the DLL and use GNAT to build your executable
21305 (@pxref{Using DLLs with GNAT}).
21307 @item
21308 Or you can encapsulate your Ada code in a DLL to be linked with the
21309 other part of your application. In this case, use GNAT to build the DLL
21310 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
21311 environment to build your executable.
21312 @end enumerate
21314 @node Windows Calling Conventions
21315 @section Windows Calling Conventions
21316 @findex Stdcall
21317 @findex APIENTRY
21319 @menu
21320 * C Calling Convention::
21321 * Stdcall Calling Convention::
21322 * DLL Calling Convention::
21323 @end menu
21325 @noindent
21326 When a subprogram @code{F} (caller) calls a subprogram @code{G}
21327 (callee), there are several ways to push @code{G}'s parameters on the
21328 stack and there are several possible scenarios to clean up the stack
21329 upon @code{G}'s return. A calling convention is an agreed upon software
21330 protocol whereby the responsibilities between the caller (@code{F}) and
21331 the callee (@code{G}) are clearly defined. Several calling conventions
21332 are available for Windows:
21334 @itemize @bullet
21335 @item
21336 @code{C} (Microsoft defined)
21338 @item
21339 @code{Stdcall} (Microsoft defined)
21341 @item
21342 @code{DLL} (GNAT specific)
21343 @end itemize
21345 @node C Calling Convention
21346 @subsection @code{C} Calling Convention
21348 @noindent
21349 This is the default calling convention used when interfacing to C/C++
21350 routines compiled with either @code{gcc} or Microsoft Visual C++.
21352 In the @code{C} calling convention subprogram parameters are pushed on the
21353 stack by the caller from right to left. The caller itself is in charge of
21354 cleaning up the stack after the call. In addition, the name of a routine
21355 with @code{C} calling convention is mangled by adding a leading underscore.
21357 The name to use on the Ada side when importing (or exporting) a routine
21358 with @code{C} calling convention is the name of the routine. For
21359 instance the C function:
21361 @smallexample
21362 int get_val (long);
21363 @end smallexample
21365 @noindent
21366 should be imported from Ada as follows:
21368 @smallexample
21369 @group
21370 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21371 @b{pragma} Import (C, Get_Val, External_Name => "get_val");
21372 @end group
21373 @end smallexample
21375 @noindent
21376 Note that in this particular case the @code{External_Name} parameter could
21377 have been omitted since, when missing, this parameter is taken to be the
21378 name of the Ada entity in lower case. When the @code{Link_Name} parameter
21379 is missing, as in the above example, this parameter is set to be the
21380 @code{External_Name} with a leading underscore.
21382 When importing a variable defined in C, you should always use the @code{C}
21383 calling convention unless the object containing the variable is part of a
21384 DLL (in which case you should use the @code{DLL} calling convention,
21385 @pxref{DLL Calling Convention}).
21387 @node Stdcall Calling Convention
21388 @subsection @code{Stdcall} Calling Convention
21390 @noindent
21391 This convention, which was the calling convention used for Pascal
21392 programs, is used by Microsoft for all the routines in the Win32 API for
21393 efficiency reasons. It must be used to import any routine for which this
21394 convention was specified.
21396 In the @code{Stdcall} calling convention subprogram parameters are pushed
21397 on the stack by the caller from right to left. The callee (and not the
21398 caller) is in charge of cleaning the stack on routine exit. In addition,
21399 the name of a routine with @code{Stdcall} calling convention is mangled by
21400 adding a leading underscore (as for the @code{C} calling convention) and a
21401 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
21402 bytes) of the parameters passed to the routine.
21404 The name to use on the Ada side when importing a C routine with a
21405 @code{Stdcall} calling convention is the name of the C routine. The leading
21406 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
21407 the compiler. For instance the Win32 function:
21409 @smallexample
21410 @b{APIENTRY} int get_val (long);
21411 @end smallexample
21413 @noindent
21414 should be imported from Ada as follows:
21416 @smallexample
21417 @group
21418 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21419 @b{pragma} Import (Stdcall, Get_Val);
21420 --  @i{On the x86 a long is 4 bytes, so the Link_Name is }"_get_val@@4"
21421 @end group
21422 @end smallexample
21424 @noindent
21425 As for the @code{C} calling convention, when the @code{External_Name}
21426 parameter is missing, it is taken to be the name of the Ada entity in lower
21427 case. If instead of writing the above import pragma you write:
21429 @smallexample
21430 @group
21431 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21432 @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val");
21433 @end group
21434 @end smallexample
21436 @noindent
21437 then the imported routine is @code{_retrieve_val@@4}. However, if instead
21438 of specifying the @code{External_Name} parameter you specify the
21439 @code{Link_Name} as in the following example:
21441 @smallexample
21442 @group
21443 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21444 @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
21445 @end group
21446 @end smallexample
21448 @noindent
21449 then the imported routine is @code{retrieve_val@@4}, that is, there is no
21450 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
21451 added at the end of the @code{Link_Name} by the compiler.
21453 @noindent
21454 Note, that in some special cases a DLL's entry point name lacks a trailing
21455 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
21456 The @code{gnatdll} tool, which creates the import library for the DLL, is able
21457 to handle those cases (see the description of the switches in
21458 @pxref{Using gnatdll} section).
21460 @node DLL Calling Convention
21461 @subsection @code{DLL} Calling Convention
21463 @noindent
21464 This convention, which is GNAT-specific, must be used when you want to
21465 import in Ada a variables defined in a DLL. For functions and procedures
21466 this convention is equivalent to the @code{Stdcall} convention. As an
21467 example, if a DLL contains a variable defined as:
21469 @smallexample
21470 int my_var;
21471 @end smallexample
21473 @noindent
21474 then, to access this variable from Ada you should write:
21476 @smallexample
21477 @group
21478 My_Var : Interfaces.C.int;
21479 @b{pragma} Import (DLL, My_Var);
21480 @end group
21481 @end smallexample
21483 The remarks concerning the @code{External_Name} and @code{Link_Name}
21484 parameters given in the previous sections equally apply to the @code{DLL}
21485 calling convention.
21487 @node Introduction to Dynamic Link Libraries (DLLs)
21488 @section Introduction to Dynamic Link Libraries (DLLs)
21489 @findex DLL
21491 @noindent
21492 A Dynamically Linked Library (DLL) is a library that can be shared by
21493 several applications running under Windows. A DLL can contain any number of
21494 routines and variables.
21496 One advantage of DLLs is that you can change and enhance them without
21497 forcing all the applications that depend on them to be relinked or
21498 recompiled. However, you should be aware than all calls to DLL routines are
21499 slower since, as you will understand below, such calls are indirect.
21501 To illustrate the remainder of this section, suppose that an application
21502 wants to use the services of a DLL @file{API.dll}. To use the services
21503 provided by @file{API.dll} you must statically link against an import
21504 library which contains a jump table with an entry for each routine and
21505 variable exported by the DLL. In the Microsoft world this import library is
21506 called @file{API.lib}. When using GNAT this import library is called either
21507 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
21509 After you have statically linked your application with the import library
21510 and you run your application, here is what happens:
21512 @enumerate
21513 @item
21514 Your application is loaded into memory.
21516 @item
21517 The DLL @file{API.dll} is mapped into the address space of your
21518 application. This means that:
21520 @itemize @bullet
21521 @item
21522 The DLL will use the stack of the calling thread.
21524 @item
21525 The DLL will use the virtual address space of the calling process.
21527 @item
21528 The DLL will allocate memory from the virtual address space of the calling
21529 process.
21531 @item
21532 Handles (pointers) can be safely exchanged between routines in the DLL
21533 routines and routines in the application using the DLL.
21534 @end itemize
21536 @item
21537 The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
21538 part of your application are initialized with the addresses of the routines
21539 and variables in @file{API.dll}.
21541 @item
21542 If present in @file{API.dll}, routines @code{DllMain} or
21543 @code{DllMainCRTStartup} are invoked. These routines typically contain
21544 the initialization code needed for the well-being of the routines and
21545 variables exported by the DLL.
21546 @end enumerate
21548 @noindent
21549 There is an additional point which is worth mentioning. In the Windows
21550 world there are two kind of DLLs: relocatable and non-relocatable
21551 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
21552 in the target application address space. If the addresses of two
21553 non-relocatable DLLs overlap and these happen to be used by the same
21554 application, a conflict will occur and the application will run
21555 incorrectly. Hence, when possible, it is always preferable to use and
21556 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
21557 supported by GNAT.
21559 As a side note, an interesting difference between Microsoft DLLs and
21560 Unix shared libraries, is the fact that on most Unix systems all public
21561 routines are exported by default in a Unix shared library, while under
21562 Windows the exported routines must be listed explicitly in a definition
21563 file (@pxref{The Definition File}).
21565 @node Using DLLs with GNAT
21566 @section Using DLLs with GNAT
21568 @menu
21569 * Creating an Ada Spec for the DLL Services::
21570 * Creating an Import Library::
21571 @end menu
21573 @noindent
21574 To use the services of a DLL, say @file{API.dll}, in your Ada application
21575 you must have:
21577 @enumerate
21578 @item
21579 The Ada spec for the routines and/or variables you want to access in
21580 @file{API.dll}. If not available this Ada spec must be built from the C/C++
21581 header files provided with the DLL.
21583 @item
21584 The import library (@file{libAPI.a} or @file{API.lib}). As previously
21585 mentioned an import library is a statically linked library containing the
21586 import table which will be filled at load time to point to the actual
21587 @file{API.dll} routines. Sometimes you don't have an import library for the
21588 DLL you want to use. The following sections will explain how to build one.
21590 @item
21591 The actual DLL, @file{API.dll}.
21592 @end enumerate
21594 @noindent
21595 Once you have all the above, to compile an Ada application that uses the
21596 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
21597 you simply issue the command
21599 @smallexample
21600 $ gnatmake my_ada_app -largs -lAPI
21601 @end smallexample
21603 @noindent
21604 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
21605 tells the GNAT linker to look first for a library named @file{API.lib}
21606 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
21607 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
21608 contains the following pragma
21610 @smallexample
21611 @b{pragma} Linker_Options ("-lAPI");
21612 @end smallexample
21614 @noindent
21615 you do not have to add @code{-largs -lAPI} at the end of the @code{gnatmake}
21616 command.
21618 If any one of the items above is missing you will have to create it
21619 yourself. The following sections explain how to do so using as an
21620 example a fictitious DLL called @file{API.dll}.
21622 @node Creating an Ada Spec for the DLL Services
21623 @subsection Creating an Ada Spec for the DLL Services
21625 @noindent
21626 A DLL typically comes with a C/C++ header file which provides the
21627 definitions of the routines and variables exported by the DLL. The Ada
21628 equivalent of this header file is a package spec that contains definitions
21629 for the imported entities. If the DLL you intend to use does not come with
21630 an Ada spec you have to generate one such spec yourself. For example if
21631 the header file of @file{API.dll} is a file @file{api.h} containing the
21632 following two definitions:
21634 @smallexample
21635 @group
21636 @cartouche
21637 int some_var;
21638 int get (char *);
21639 @end cartouche
21640 @end group
21641 @end smallexample
21643 @noindent
21644 then the equivalent Ada spec could be:
21646 @smallexample
21647 @group
21648 @cartouche
21649 @b{with} Interfaces.C.Strings;
21650 @b{package} API @b{is}
21651    @b{use} Interfaces;
21653    Some_Var : C.int;
21654    @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int;
21656 @b{private}
21657    @b{pragma} Import (C, Get);
21658    @b{pragma} Import (DLL, Some_Var);
21659 @b{end} API;
21660 @end cartouche
21661 @end group
21662 @end smallexample
21664 @noindent
21665 Note that a variable is @strong{always imported with a DLL convention}. A
21666 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
21667 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
21668 (@pxref{Windows Calling Conventions}).
21670 @node Creating an Import Library
21671 @subsection Creating an Import Library
21672 @cindex Import library
21674 @menu
21675 * The Definition File::
21676 * GNAT-Style Import Library::
21677 * Microsoft-Style Import Library::
21678 @end menu
21680 @noindent
21681 If a Microsoft-style import library @file{API.lib} or a GNAT-style
21682 import library @file{libAPI.a} is available with @file{API.dll} you
21683 can skip this section. Otherwise read on.
21685 @node The Definition File
21686 @subsubsection The Definition File
21687 @cindex Definition file
21688 @findex .def
21690 @noindent
21691 As previously mentioned, and unlike Unix systems, the list of symbols
21692 that are exported from a DLL must be provided explicitly in Windows.
21693 The main goal of a definition file is precisely that: list the symbols
21694 exported by a DLL. A definition file (usually a file with a @code{.def}
21695 suffix) has the following structure:
21697 @smallexample
21698 @group
21699 @cartouche
21700 [LIBRARY @i{name}]
21701 [DESCRIPTION @i{string}]
21702 EXPORTS
21703    @i{symbol1}
21704    @i{symbol2}
21705    ...
21706 @end cartouche
21707 @end group
21708 @end smallexample
21710 @table @code
21711 @item LIBRARY @i{name}
21712 This section, which is optional, gives the name of the DLL.
21714 @item DESCRIPTION @i{string}
21715 This section, which is optional, gives a description string that will be
21716 embedded in the import library.
21718 @item EXPORTS
21719 This section gives the list of exported symbols (procedures, functions or
21720 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
21721 section of @file{API.def} looks like:
21723 @smallexample
21724 @group
21725 @cartouche
21726 EXPORTS
21727    some_var
21728    get
21729 @end cartouche
21730 @end group
21731 @end smallexample
21732 @end table
21734 @noindent
21735 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
21736 (@pxref{Windows Calling Conventions}) for a Stdcall
21737 calling convention function in the exported symbols list.
21739 @noindent
21740 There can actually be other sections in a definition file, but these
21741 sections are not relevant to the discussion at hand.
21743 @node GNAT-Style Import Library
21744 @subsubsection GNAT-Style Import Library
21746 @noindent
21747 To create a static import library from @file{API.dll} with the GNAT tools
21748 you should proceed as follows:
21750 @enumerate
21751 @item
21752 Create the definition file @file{API.def} (@pxref{The Definition File}).
21753 For that use the @code{dll2def} tool as follows:
21755 @smallexample
21756 $ dll2def API.dll > API.def
21757 @end smallexample
21759 @noindent
21760 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
21761 to standard output the list of entry points in the DLL. Note that if
21762 some routines in the DLL have the @code{Stdcall} convention
21763 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
21764 suffix then you'll have to edit @file{api.def} to add it.
21766 @noindent
21767 Here are some hints to find the right @code{@@}@i{nn} suffix.
21769 @enumerate
21770 @item
21771 If you have the Microsoft import library (.lib), it is possible to get
21772 the right symbols by using Microsoft @code{dumpbin} tool (see the
21773 corresponding Microsoft documentation for further details).
21775 @smallexample
21776 $ dumpbin /exports api.lib
21777 @end smallexample
21779 @item
21780 If you have a message about a missing symbol at link time the compiler
21781 tells you what symbol is expected. You just have to go back to the
21782 definition file and add the right suffix.
21783 @end enumerate
21785 @item
21786 Build the import library @code{libAPI.a}, using @code{gnatdll}
21787 (@pxref{Using gnatdll}) as follows:
21789 @smallexample
21790 $ gnatdll -e API.def -d API.dll
21791 @end smallexample
21793 @noindent
21794 @code{gnatdll} takes as input a definition file @file{API.def} and the
21795 name of the DLL containing the services listed in the definition file
21796 @file{API.dll}. The name of the static import library generated is
21797 computed from the name of the definition file as follows: if the
21798 definition file name is @i{xyz}@code{.def}, the import library name will
21799 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
21800 @code{-e} could have been removed because the name of the definition
21801 file (before the "@code{.def}" suffix) is the same as the name of the
21802 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
21803 @end enumerate
21805 @node Microsoft-Style Import Library
21806 @subsubsection Microsoft-Style Import Library
21808 @noindent
21809 With GNAT you can either use a GNAT-style or Microsoft-style import
21810 library. A Microsoft import library is needed only if you plan to make an
21811 Ada DLL available to applications developed with Microsoft
21812 tools (@pxref{Mixed-Language Programming on Windows}).
21814 To create a Microsoft-style import library for @file{API.dll} you
21815 should proceed as follows:
21817 @enumerate
21818 @item
21819 Create the definition file @file{API.def} from the DLL. For this use either
21820 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
21821 tool (see the corresponding Microsoft documentation for further details).
21823 @item
21824 Build the actual import library using Microsoft's @code{lib} utility:
21826 @smallexample
21827 $ lib -machine:IX86 -def:API.def -out:API.lib
21828 @end smallexample
21830 @noindent
21831 If you use the above command the definition file @file{API.def} must
21832 contain a line giving the name of the DLL:
21834 @smallexample
21835 LIBRARY      "API"
21836 @end smallexample
21838 @noindent
21839 See the Microsoft documentation for further details about the usage of
21840 @code{lib}.
21841 @end enumerate
21843 @node Building DLLs with GNAT
21844 @section Building DLLs with GNAT
21845 @cindex DLLs, building
21847 @menu
21848 * Limitations When Using Ada DLLs from Ada::
21849 * Exporting Ada Entities::
21850 * Ada DLLs and Elaboration::
21851 * Ada DLLs and Finalization::
21852 * Creating a Spec for Ada DLLs::
21853 * Creating the Definition File::
21854 * Using gnatdll::
21855 @end menu
21857 @noindent
21858 This section explains how to build DLLs containing Ada code. These DLLs
21859 will be referred to as Ada DLLs in the remainder of this section.
21861 The steps required to build an Ada DLL that is to be used by Ada as well as
21862 non-Ada applications are as follows:
21864 @enumerate
21865 @item
21866 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
21867 @code{Stdcall} calling convention to avoid any Ada name mangling for the
21868 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
21869 skip this step if you plan to use the Ada DLL only from Ada applications.
21871 @item
21872 Your Ada code must export an initialization routine which calls the routine
21873 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
21874 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
21875 routine exported by the Ada DLL must be invoked by the clients of the DLL
21876 to initialize the DLL.
21878 @item
21879 When useful, the DLL should also export a finalization routine which calls
21880 routine @code{adafinal} generated by @code{gnatbind} to perform the
21881 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
21882 The finalization routine exported by the Ada DLL must be invoked by the
21883 clients of the DLL when the DLL services are no further needed.
21885 @item
21886 You must provide a spec for the services exported by the Ada DLL in each
21887 of the programming languages to which you plan to make the DLL available.
21889 @item
21890 You must provide a definition file listing the exported entities
21891 (@pxref{The Definition File}).
21893 @item
21894 Finally you must use @code{gnatdll} to produce the DLL and the import
21895 library (@pxref{Using gnatdll}).
21896 @end enumerate
21898 @node Limitations When Using Ada DLLs from Ada
21899 @subsection Limitations When Using Ada DLLs from Ada
21901 @noindent
21902 When using Ada DLLs from Ada applications there is a limitation users
21903 should be aware of. Because on Windows the GNAT run time is not in a DLL of
21904 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
21905 each Ada DLL includes the services of the GNAT run time that are necessary
21906 to the Ada code inside the DLL. As a result, when an Ada program uses an
21907 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
21908 one in the main program.
21910 It is therefore not possible to exchange GNAT run-time objects between the
21911 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
21912 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
21913 types, etc.
21915 It is completely safe to exchange plain elementary, array or record types,
21916 Windows object handles, etc.
21918 @node Exporting Ada Entities
21919 @subsection Exporting Ada Entities
21920 @cindex Export table
21922 @noindent
21923 Building a DLL is a way to encapsulate a set of services usable from any
21924 application. As a result, the Ada entities exported by a DLL should be
21925 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
21926 any Ada name mangling. Please note that the @code{Stdcall} convention
21927 should only be used for subprograms, not for variables. As an example here
21928 is an Ada package @code{API}, spec and body, exporting two procedures, a
21929 function, and a variable:
21931 @smallexample
21932 @group
21933 @cartouche
21934 @b{with} Interfaces.C; @b{use} Interfaces;
21935 @b{package} API @b{is}
21936    Count : C.int := 0;
21937    @b{function} Factorial (Val : C.int) @b{return} C.int;
21939    @b{procedure} Initialize_API;
21940    @b{procedure} Finalize_API;
21941    --  @i{Initialization & Finalization routines. More in the next section.}
21942 @b{private}
21943    @b{pragma} Export (C, Initialize_API);
21944    @b{pragma} Export (C, Finalize_API);
21945    @b{pragma} Export (C, Count);
21946    @b{pragma} Export (C, Factorial);
21947 @b{end} API;
21948 @end cartouche
21949 @end group
21950 @end smallexample
21952 @smallexample
21953 @group
21954 @cartouche
21955 @b{package body} API @b{is}
21956    @b{function} Factorial (Val : C.int) @b{return} C.int @b{is}
21957       Fact : C.int := 1;
21958    @b{begin}
21959       Count := Count + 1;
21960       @b{for} K @b{in} 1 .. Val @b{loop}
21961          Fact := Fact * K;
21962       @b{end loop};
21963       @b{return} Fact;
21964    @b{end} Factorial;
21966    @b{procedure} Initialize_API @b{is}
21967       @b{procedure} Adainit;
21968       @b{pragma} Import (C, Adainit);
21969    @b{begin}
21970       Adainit;
21971    @b{end} Initialize_API;
21973    @b{procedure} Finalize_API @b{is}
21974       @b{procedure} Adafinal;
21975       @b{pragma} Import (C, Adafinal);
21976    @b{begin}
21977       Adafinal;
21978    @b{end} Finalize_API;
21979 @b{end} API;
21980 @end cartouche
21981 @end group
21982 @end smallexample
21984 @noindent
21985 If the Ada DLL you are building will only be used by Ada applications
21986 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
21987 convention. As an example, the previous package could be written as
21988 follows:
21990 @smallexample
21991 @group
21992 @cartouche
21993 @b{package} API @b{is}
21994    Count : Integer := 0;
21995    @b{function} Factorial (Val : Integer) @b{return} Integer;
21997    @b{procedure} Initialize_API;
21998    @b{procedure} Finalize_API;
21999    --  @i{Initialization and Finalization routines.}
22000 @b{end} API;
22001 @end cartouche
22002 @end group
22003 @end smallexample
22005 @smallexample
22006 @group
22007 @cartouche
22008 @b{package body} API @b{is}
22009    @b{function} Factorial (Val : Integer) @b{return} Integer @b{is}
22010       Fact : Integer := 1;
22011    @b{begin}
22012       Count := Count + 1;
22013       @b{for} K @b{in} 1 .. Val @b{loop}
22014          Fact := Fact * K;
22015       @b{end loop};
22016       @b{return} Fact;
22017       @b{end} Factorial;
22019    ...
22020    --  @i{The remainder of this package body is unchanged.}
22021 @b{end} API;
22022 @end cartouche
22023 @end group
22024 @end smallexample
22026 @noindent
22027 Note that if you do not export the Ada entities with a @code{C} or
22028 @code{Stdcall} convention you will have to provide the mangled Ada names
22029 in the definition file of the Ada DLL
22030 (@pxref{Creating the Definition File}).
22032 @node Ada DLLs and Elaboration
22033 @subsection Ada DLLs and Elaboration
22034 @cindex DLLs and elaboration
22036 @noindent
22037 The DLL that you are building contains your Ada code as well as all the
22038 routines in the Ada library that are needed by it. The first thing a
22039 user of your DLL must do is elaborate the Ada code
22040 (@pxref{Elaboration Order Handling in GNAT}).
22042 To achieve this you must export an initialization routine
22043 (@code{Initialize_API} in the previous example), which must be invoked
22044 before using any of the DLL services. This elaboration routine must call
22045 the Ada elaboration routine @code{adainit} generated by the GNAT binder
22046 (@pxref{Binding with Non-Ada Main Programs}). See the body of
22047 @code{Initialize_Api} for an example. Note that the GNAT binder is
22048 automatically invoked during the DLL build process by the @code{gnatdll}
22049 tool (@pxref{Using gnatdll}).
22051 When a DLL is loaded, Windows systematically invokes a routine called
22052 @code{DllMain}. It would therefore be possible to call @code{adainit}
22053 directly from @code{DllMain} without having to provide an explicit
22054 initialization routine. Unfortunately, it is not possible to call
22055 @code{adainit} from the @code{DllMain} if your program has library level
22056 tasks because access to the @code{DllMain} entry point is serialized by
22057 the system (that is, only a single thread can execute "through" it at a
22058 time), which means that the GNAT run time will deadlock waiting for the
22059 newly created task to complete its initialization.
22061 @node Ada DLLs and Finalization
22062 @subsection Ada DLLs and Finalization
22063 @cindex DLLs and finalization
22065 @noindent
22066 When the services of an Ada DLL are no longer needed, the client code should
22067 invoke the DLL finalization routine, if available. The DLL finalization
22068 routine is in charge of releasing all resources acquired by the DLL. In the
22069 case of the Ada code contained in the DLL, this is achieved by calling
22070 routine @code{adafinal} generated by the GNAT binder
22071 (@pxref{Binding with Non-Ada Main Programs}).
22072 See the body of @code{Finalize_Api} for an
22073 example. As already pointed out the GNAT binder is automatically invoked
22074 during the DLL build process by the @code{gnatdll} tool
22075 (@pxref{Using gnatdll}).
22077 @code{-g}
22078 @cindex @code{-g} (@code{gnatdll})
22080 Generate debugging information. This information is stored in the object
22081 file and copied from there to the final DLL file by the linker,
22082 where it can be read by the debugger. You must use the
22083 @code{-g} switch if you plan on using the debugger or the symbolic
22084 stack traceback.
22086 @node Creating a Spec for Ada DLLs
22087 @subsection Creating a Spec for Ada DLLs
22089 @noindent
22090 To use the services exported by the Ada DLL from another programming
22091 language (e.g. C), you have to translate the specs of the exported Ada
22092 entities in that language. For instance in the case of @code{API.dll},
22093 the corresponding C header file could look like:
22095 @smallexample
22096 @group
22097 @cartouche
22098 extern int *__imp__count;
22099 #define count (*__imp__count)
22100 int factorial (int);
22101 @end cartouche
22102 @end group
22103 @end smallexample
22105 @noindent
22106 It is important to understand that when building an Ada DLL to be used by
22107 other Ada applications, you need two different specs for the packages
22108 contained in the DLL: one for building the DLL and the other for using
22109 the DLL. This is because the @code{DLL} calling convention is needed to
22110 use a variable defined in a DLL, but when building the DLL, the variable
22111 must have either the @code{Ada} or @code{C} calling convention. As an
22112 example consider a DLL comprising the following package @code{API}:
22114 @smallexample
22115 @group
22116 @cartouche
22117 @b{package} API @b{is}
22118    Count : Integer := 0;
22119    ...
22120    --  @i{Remainder of the package omitted.}
22121 @b{end} API;
22122 @end cartouche
22123 @end group
22124 @end smallexample
22126 @noindent
22127 After producing a DLL containing package @code{API}, the spec that
22128 must be used to import @code{API.Count} from Ada code outside of the
22129 DLL is:
22131 @smallexample
22132 @group
22133 @cartouche
22134 @b{package} API @b{is}
22135    Count : Integer;
22136    @b{pragma} Import (DLL, Count);
22137 @b{end} API;
22138 @end cartouche
22139 @end group
22140 @end smallexample
22142 @node Creating the Definition File
22143 @subsection Creating the Definition File
22145 @noindent
22146 The definition file is the last file needed to build the DLL. It lists
22147 the exported symbols. As an example, the definition file for a DLL
22148 containing only package @code{API} (where all the entities are exported
22149 with a @code{C} calling convention) is:
22151 @smallexample
22152 @group
22153 @cartouche
22154 EXPORTS
22155     count
22156     factorial
22157     finalize_api
22158     initialize_api
22159 @end cartouche
22160 @end group
22161 @end smallexample
22163 @noindent
22164 If the @code{C} calling convention is missing from package @code{API},
22165 then the definition file contains the mangled Ada names of the above
22166 entities, which in this case are:
22168 @smallexample
22169 @group
22170 @cartouche
22171 EXPORTS
22172     api__count
22173     api__factorial
22174     api__finalize_api
22175     api__initialize_api
22176 @end cartouche
22177 @end group
22178 @end smallexample
22180 @node Using gnatdll
22181 @subsection Using @code{gnatdll}
22182 @findex gnatdll
22184 @menu
22185 * gnatdll Example::
22186 * gnatdll behind the Scenes::
22187 * Using dlltool::
22188 @end menu
22190 @noindent
22191 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
22192 and non-Ada sources that make up your DLL have been compiled.
22193 @code{gnatdll} is actually in charge of two distinct tasks: build the
22194 static import library for the DLL and the actual DLL. The form of the
22195 @code{gnatdll} command is
22197 @smallexample
22198 @cartouche
22199 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
22200 @end cartouche
22201 @end smallexample
22203 @noindent
22204 where @i{list-of-files} is a list of ALI and object files. The object
22205 file list must be the exact list of objects corresponding to the non-Ada
22206 sources whose services are to be included in the DLL. The ALI file list
22207 must be the exact list of ALI files for the corresponding Ada sources
22208 whose services are to be included in the DLL. If @i{list-of-files} is
22209 missing, only the static import library is generated.
22211 @noindent
22212 You may specify any of the following switches to @code{gnatdll}:
22214 @table @code
22215 @item -a[@var{address}]
22216 @cindex @code{-a} (@code{gnatdll})
22217 Build a non-relocatable DLL at @var{address}. If @var{address} is not
22218 specified the default address @var{0x11000000} will be used. By default,
22219 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
22220 advise the reader to build relocatable DLL.
22222 @item -b @var{address}
22223 @cindex @code{-b} (@code{gnatdll})
22224 Set the relocatable DLL base address. By default the address is
22225 @var{0x11000000}.
22227 @item -d @var{dllfile}
22228 @cindex @code{-d} (@code{gnatdll})
22229 @var{dllfile} is the name of the DLL. This switch must be present for
22230 @code{gnatdll} to do anything. The name of the generated import library is
22231 obtained algorithmically from @var{dllfile} as shown in the following
22232 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
22233 @code{libxyz.a}. The name of the definition file to use (if not specified
22234 by option @code{-e}) is obtained algorithmically from @var{dllfile} as shown in
22235 the following example: if @var{dllfile} is @code{xyz.dll}, the definition
22236 file used is @code{xyz.def}.
22238 @item -e @var{deffile}
22239 @cindex @code{-e} (@code{gnatdll})
22240 @var{deffile} is the name of the definition file.
22242 @item -h
22243 @cindex @code{-h} (@code{gnatdll})
22244 Help mode. Displays @code{gnatdll} switch usage information.
22246 @item -Idir
22247 Direct @code{gnatdll} to search the @var{dir} directory for source and
22248 object files needed to build the DLL.
22249 (@pxref{Search Paths and the Run-Time Library (RTL)}).
22251 @item -k
22252 Removes the @code{@@}@i{nn} suffix from the import library's exported
22253 names. You must specified this option if you want to use a
22254 @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix
22255 has been removed. This is the case for most of the Windows NT DLL for
22256 example. This option has no effect when @code{-n} option is specified.
22258 @item -l @var{file}
22259 @cindex @code{-l} (@code{gnatdll})
22260 The list of ALI and object files used to build the DLL are listed in
22261 @var{file}, instead of being given in the command line. Each line in
22262 @var{file} contains the name of an ALI or object file.
22264 @item -n
22265 @cindex @code{-n} (@code{gnatdll})
22266 No Import. Do not create the import library.
22268 @item -q
22269 @cindex @code{-q} (@code{gnatdll})
22270 Quiet mode. Do not display unnecessary messages.
22272 @item -v
22273 @cindex @code{-v} (@code{gnatdll})
22274 Verbose mode. Display extra information.
22276 @item -largs @var{opts}
22277 @cindex @code{-largs} (@code{gnatdll})
22278 Linker options. Pass @var{opts} to the linker.
22279 @end table
22281 @node gnatdll Example
22282 @subsubsection @code{gnatdll} Example
22284 @noindent
22285 As an example the command to build a relocatable DLL from @file{api.adb}
22286 once @file{api.adb} has been compiled and @file{api.def} created is
22288 @smallexample
22289 $ gnatdll -d api.dll api.ali
22290 @end smallexample
22292 @noindent
22293 The above command creates two files: @file{libapi.a} (the import
22294 library) and @file{api.dll} (the actual DLL). If you want to create
22295 only the DLL, just type:
22297 @smallexample
22298 $ gnatdll -d api.dll -n api.ali
22299 @end smallexample
22301 @noindent
22302 Alternatively if you want to create just the import library, type:
22304 @smallexample
22305 $ gnatdll -d api.dll
22306 @end smallexample
22308 @node gnatdll behind the Scenes
22309 @subsubsection @code{gnatdll} behind the Scenes
22311 @noindent
22312 This section details the steps involved in creating a DLL. @code{gnatdll}
22313 does these steps for you. Unless you are interested in understanding what
22314 goes on behind the scenes, you should skip this section.
22316 We use the previous example of a DLL containing the Ada package @code{API},
22317 to illustrate the steps necessary to build a DLL. The starting point is a
22318 set of objects that will make up the DLL and the corresponding ALI
22319 files. In the case of this example this means that @file{api.o} and
22320 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
22321 the following:
22323 @enumerate
22324 @item
22325 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
22326 the information necessary to generate relocation information for the
22327 DLL.
22329 @smallexample
22330 @group
22331 $ gnatbind -n api
22332 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
22333 @end group
22334 @end smallexample
22336 @noindent
22337 In addition to the base file, the @code{gnatlink} command generates an
22338 output file @file{api.jnk} which can be discarded. The @code{-mdll} switch
22339 asks @code{gnatlink} to generate the routines @code{DllMain} and
22340 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
22341 is loaded into memory.
22343 @item
22344 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
22345 export table (@file{api.exp}). The export table contains the relocation
22346 information in a form which can be used during the final link to ensure
22347 that the Windows loader is able to place the DLL anywhere in memory.
22349 @smallexample
22350 @group
22351 $ dlltool --dllname api.dll --def api.def --base-file api.base \
22352           --output-exp api.exp
22353 @end group
22354 @end smallexample
22356 @item
22357 @code{gnatdll} builds the base file using the new export table. Note that
22358 @code{gnatbind} must be called once again since the binder generated file
22359 has been deleted during the previous call to @code{gnatlink}.
22361 @smallexample
22362 @group
22363 $ gnatbind -n api
22364 $ gnatlink api -o api.jnk api.exp -mdll
22365       -Wl,--base-file,api.base
22366 @end group
22367 @end smallexample
22369 @item
22370 @code{gnatdll} builds the new export table using the new base file and
22371 generates the DLL import library @file{libAPI.a}.
22373 @smallexample
22374 @group
22375 $ dlltool --dllname api.dll --def api.def --base-file api.base \
22376           --output-exp api.exp --output-lib libAPI.a
22377 @end group
22378 @end smallexample
22380 @item
22381 Finally @code{gnatdll} builds the relocatable DLL using the final export
22382 table.
22384 @smallexample
22385 @group
22386 $ gnatbind -n api
22387 $ gnatlink api api.exp -o api.dll -mdll
22388 @end group
22389 @end smallexample
22390 @end enumerate
22392 @node Using dlltool
22393 @subsubsection Using @code{dlltool}
22395 @noindent
22396 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
22397 DLLs and static import libraries. This section summarizes the most
22398 common @code{dlltool} switches. The form of the @code{dlltool} command
22401 @smallexample
22402 $ dlltool [@var{switches}]
22403 @end smallexample
22405 @noindent
22406 @code{dlltool} switches include:
22408 @table @code
22409 @item --base-file @var{basefile}
22410 Read the base file @var{basefile} generated by the linker. This switch
22411 is used to create a relocatable DLL.
22413 @item --def @var{deffile}
22414 Read the definition file.
22416 @item --dllname @var{name}
22417 Gives the name of the DLL. This switch is used to embed the name of the
22418 DLL in the static import library generated by @code{dlltool} with switch
22419 @code{--output-lib}.
22421 @item -k
22422 Kill @code{@@}@i{nn} from exported names
22423 (@pxref{Windows Calling Conventions}
22424 for a discussion about @code{Stdcall}-style symbols.
22426 @item --help
22427 Prints the @code{dlltool} switches with a concise description.
22429 @item --output-exp @var{exportfile}
22430 Generate an export file @var{exportfile}. The export file contains the
22431 export table (list of symbols in the DLL) and is used to create the DLL.
22433 @item --output-lib @i{libfile}
22434 Generate a static import library @var{libfile}.
22436 @item -v
22437 Verbose mode.
22439 @item --as @i{assembler-name}
22440 Use @i{assembler-name} as the assembler. The default is @code{as}.
22441 @end table
22443 @node GNAT and Windows Resources
22444 @section GNAT and Windows Resources
22445 @cindex Resources, windows
22447 @menu
22448 * Building Resources::
22449 * Compiling Resources::
22450 * Using Resources::
22451 * Limitations::
22452 @end menu
22454 @noindent
22455 Resources are an easy way to add Windows specific objects to your
22456 application. The objects that can be added as resources include:
22458 @itemize @bullet
22459 @item
22460 menus
22462 @item
22463 accelerators
22465 @item
22466 dialog boxes
22468 @item
22469 string tables
22471 @item
22472 bitmaps
22474 @item
22475 cursors
22477 @item
22478 icons
22480 @item
22481 fonts
22482 @end itemize
22484 @noindent
22485 This section explains how to build, compile and use resources.
22487 @node Building Resources
22488 @subsection Building Resources
22489 @cindex Resources, building
22491 @noindent
22492 A resource file is an ASCII file. By convention resource files have an
22493 @file{.rc} extension.
22494 The easiest way to build a resource file is to use Microsoft tools
22495 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
22496 @code{dlgedit.exe} to build dialogs.
22497 It is always possible to build an @file{.rc} file yourself by writing a
22498 resource script.
22500 It is not our objective to explain how to write a resource file. A
22501 complete description of the resource script language can be found in the
22502 Microsoft documentation.
22504 @node Compiling Resources
22505 @subsection Compiling Resources
22506 @findex rc
22507 @findex rcl
22508 @findex res2coff
22509 @cindex Resources, compiling
22511 @noindent
22512 This section describes how to build a GNAT-compatible (COFF) object file
22513 containing the resources. This is done using the Resource Compiler
22514 @code{rcl} as follows:
22516 @smallexample
22517 $ rcl -i myres.rc -o myres.o
22518 @end smallexample
22520 @noindent
22521 By default @code{rcl} will run @code{gcc} to preprocess the @file{.rc}
22522 file. You can specify an alternate preprocessor (usually named
22523 @file{cpp.exe}) using the @code{rcl} @code{-cpp} parameter. A list of
22524 all possible options may be obtained by entering the command @code{rcl}
22525 with no parameters.
22527 It is also possible to use the Microsoft resource compiler @code{rc.exe}
22528 to produce a @file{.res} file (binary resource file). See the
22529 corresponding Microsoft documentation for further details. In this case
22530 you need to use @code{res2coff} to translate the @file{.res} file to a
22531 GNAT-compatible object file as follows:
22533 @smallexample
22534 $ res2coff -i myres.res -o myres.o
22535 @end smallexample
22537 @node Using Resources
22538 @subsection Using Resources
22539 @cindex Resources, using
22541 @noindent
22542 To include the resource file in your program just add the
22543 GNAT-compatible object file for the resource(s) to the linker
22544 arguments. With @code{gnatmake} this is done by using the @code{-largs}
22545 option:
22547 @smallexample
22548 $ gnatmake myprog -largs myres.o
22549 @end smallexample
22551 @node Limitations
22552 @subsection Limitations
22553 @cindex Resources, limitations
22555 @noindent
22556 In this section we describe the current limitations together with
22557 suggestions for workarounds.
22559 @itemize @bullet
22560 @item
22561 @code{rcl} does not handle the @code{RCINCLUDE} directive.
22563 Workaround: replace @code{RCINCLUDE} by an @code{#include} directive.
22565 @item
22566 @code{rcl} does not handle the brackets as block delimiters.
22568 Workaround: replace character '@{' by @code{BEGIN} and '@}' by
22569 @code{END}. Note that Microsoft's @code{rc} handles both forms of block
22570 delimiters.
22572 @item
22573 @code{rcl} does not handle @code{TypeLib} resources. This type of
22574 resource is used to build COM, DCOM or ActiveX objects.
22576 Workaround: use @code{rc}, the Microsoft resource compiler.
22578 @item
22579 It is not possible to use @code{strip} to remove the debugging symbols
22580 from a program with resources.
22582 Workaround: use linker option @code{-s} to strip debugging symbols from
22583 the final executable.
22584 @end itemize
22586 @node Debugging a DLL
22587 @section Debugging a DLL
22588 @cindex DLL debugging
22590 @menu
22591 * The Program and the DLL Are Built with GCC/GNAT::
22592 * The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT::
22593 @end menu
22595 @noindent
22596 Debugging a DLL is similar to debugging a standard program. But
22597 we have to deal with two different executable parts: the DLL and the
22598 program that uses it. We have the following four possibilities:
22600 @enumerate 1
22601 @item
22602 The program and the DLL are built with @code{GCC/GNAT}.
22603 @item
22604 The program is built with foreign tools and the DLL is built with
22605 @code{GCC/GNAT}.
22606 @item
22607 The program is built with @code{GCC/GNAT} and the DLL is built with
22608 foreign tools.
22609 @item
22610 @end enumerate
22612 @noindent
22613 In this section we address only cases one and two above.
22614 There is no point in trying to debug
22615 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
22616 information in it. To do so you must use a debugger compatible with the
22617 tools suite used to build the DLL.
22619 @node The Program and the DLL Are Built with GCC/GNAT
22620 @subsection The Program and the DLL Are Built with GCC/GNAT
22622 @noindent
22623 This is the simplest case. Both the DLL and the program have @code{GDB}
22624 compatible debugging information. It is then possible to break anywhere in
22625 the process. Let's suppose here that the main procedure is named
22626 @code{ada_main} and that in the DLL there is an entry point named
22627 @code{ada_dll}.
22629 @noindent
22630 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
22631 program must have been built with the debugging information (see GNAT -g
22632 switch). Here are the step-by-step instructions for debugging it:
22634 @enumerate 1
22635 @item Launch @code{GDB} on the main program.
22637 @smallexample
22638 $ gdb -nw ada_main
22639 @end smallexample
22641 @item Break on the main procedure and run the program.
22643 @smallexample
22644 (gdb) break ada_main
22645 (gdb) run
22646 @end smallexample
22648 @noindent
22649 This step is required to be able to set a breakpoint inside the DLL. As long
22650 as the program is not run, the DLL is not loaded. This has the
22651 consequence that the DLL debugging information is also not loaded, so it is not
22652 possible to set a breakpoint in the DLL.
22654 @item Set a breakpoint inside the DLL
22656 @smallexample
22657 (gdb) break ada_dll
22658 (gdb) run
22659 @end smallexample
22661 @end enumerate
22663 @noindent
22664 At this stage a breakpoint is set inside the DLL. From there on
22665 you can use the standard approach to debug the whole program
22666 (@pxref{Running and Debugging Ada Programs}).
22668 @node The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
22669 @subsection The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
22671 @menu
22672 * Debugging the DLL Directly::
22673 * Attaching to a Running Process::
22674 @end menu
22676 @noindent
22677 In this case things are slightly more complex because it is not possible to
22678 start the main program and then break at the beginning to load the DLL and the
22679 associated DLL debugging information. It is not possible to break at the
22680 beginning of the program because there is no @code{GDB} debugging information,
22681 and therefore there is no direct way of getting initial control. This
22682 section addresses this issue by describing some methods that can be used
22683 to break somewhere in the DLL to debug it.
22685 @noindent
22686 First suppose that the main procedure is named @code{main} (this is for
22687 example some C code built with Microsoft Visual C) and that there is a
22688 DLL named @code{test.dll} containing an Ada entry point named
22689 @code{ada_dll}.
22691 @noindent
22692 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
22693 been built with debugging information (see GNAT -g option).
22695 @node Debugging the DLL Directly
22696 @subsubsection Debugging the DLL Directly
22698 @enumerate 1
22699 @item
22700 Launch the debugger on the DLL.
22702 @smallexample
22703 $ gdb -nw test.dll
22704 @end smallexample
22706 @item Set a breakpoint on a DLL subroutine.
22708 @smallexample
22709 (gdb) break ada_dll
22710 @end smallexample
22712 @item
22713 Specify the executable file to @code{GDB}.
22715 @smallexample
22716 (gdb) exec-file main.exe
22717 @end smallexample
22719 @item
22720 Run the program.
22722 @smallexample
22723 (gdb) run
22724 @end smallexample
22726 @noindent
22727 This will run the program until it reaches the breakpoint that has been
22728 set. From that point you can use the standard way to debug a program
22729 as described in (@pxref{Running and Debugging Ada Programs}).
22731 @end enumerate
22733 @noindent
22734 It is also possible to debug the DLL by attaching to a running process.
22736 @node Attaching to a Running Process
22737 @subsubsection Attaching to a Running Process
22738 @cindex DLL debugging, attach to process
22740 @noindent
22741 With @code{GDB} it is always possible to debug a running process by
22742 attaching to it. It is possible to debug a DLL this way. The limitation
22743 of this approach is that the DLL must run long enough to perform the
22744 attach operation. It may be useful for instance to insert a time wasting
22745 loop in the code of the DLL to meet this criterion.
22747 @enumerate 1
22749 @item Launch the main program @file{main.exe}.
22751 @smallexample
22752 $ main
22753 @end smallexample
22755 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
22756 that the process PID for @file{main.exe} is 208.
22758 @item Launch gdb.
22760 @smallexample
22761 $ gdb -nw
22762 @end smallexample
22764 @item Attach to the running process to be debugged.
22766 @smallexample
22767 (gdb) attach 208
22768 @end smallexample
22770 @item Load the process debugging information.
22772 @smallexample
22773 (gdb) symbol-file main.exe
22774 @end smallexample
22776 @item Break somewhere in the DLL.
22778 @smallexample
22779 (gdb) break ada_dll
22780 @end smallexample
22782 @item Continue process execution.
22784 @smallexample
22785 (gdb) continue
22786 @end smallexample
22788 @end enumerate
22790 @noindent
22791 This last step will resume the process execution, and stop at
22792 the breakpoint we have set. From there you can use the standard
22793 approach to debug a program as described in
22794 (@pxref{Running and Debugging Ada Programs}).
22796 @node GNAT and COM/DCOM Objects
22797 @section GNAT and COM/DCOM Objects
22798 @findex COM
22799 @findex DCOM
22801 @noindent
22802 This section is temporarily left blank.
22804 @ignore
22805 @reread
22806 ???????????? WE NEED TO DECIDE WHETHER TO DISTRIBUTE IT ??????????????????????
22808 @node gnatreg : Registry Tool for NT
22809 @section @code{gnatreg} : Registry Tool for NT
22810 @findex gnatreg
22811 @cindex Registry
22813 @menu
22814 * Changing the GNAT compiler to Use::
22815 * Adding/Changing a Library Path::
22816 * Removing a Library Path::
22817 * List Current Configuration::
22818 @end menu
22820 @noindent
22821 This tool can be used to switch from one compiler to another and to manage
22822 the list of directories where GNAT must look to find packages. It is
22823 also a convenient way to do network installation of GNAT.
22825 The form of the @code{gnatreg} command is
22827 @smallexample
22828 $ gnatreg [@var{-hqcarf}] parameter
22829 @end smallexample
22831 @noindent
22832 Commons options are
22834 @table @code
22836 @item -h
22837 print a usage message.
22839 @item -q
22840 quiet/terse - display nothing, just do the job.
22842 @item -f
22843 force mode - create the registry keys if they do not
22844 exist. @code{gnatreg} will exit with an error if this option is omitted
22845 and some registry keys are not setup correctly.
22847 @end table
22849 @subsection Changing the GNAT compiler to use
22851 @smallexample
22852 $ gnatreg c:\gnatpro
22853 @end smallexample
22855 @noindent
22856 This will setup the registry to use the GNAT compiler that has been
22857 installed under c:\gnatpro. @code{gnatreg} check that this directory contain
22858 effectively a GNAT compiler. If you want to setup a network installation
22859 and if GNAT has never been installed on this computer you'll have to use
22860 the -f option.
22862 @subsection Adding/Changing a library path
22864 @smallexample
22865 $ gnatreg -a COMPNT=c:\ada\components
22866 @end smallexample
22868 @noindent
22869 Add the directory c:\ada\components to the list of standards libraries. When
22870 running gnatmake the option -Ic:\ada\components is added automatically to the
22871 command line.
22873 The directory c:\ada\components is associated with the name COMPNT. This
22874 name will be used to remove the library path.
22876 @subsection Removing a library path
22878 @smallexample
22879 $ gnatreg -r COMPNT
22880 @end smallexample
22882 @noindent
22883 Remove the library path named COMPNT.
22885 @subsection List current configuration
22887 @smallexample
22888 $ gnatreg -c
22889 @end smallexample
22891 @noindent
22892 @code{gnatreg} will display the GNAT and AdaGIDE path used and
22893 all the standards libraries and their associated names that have been set.
22895 @end ignore
22896 @end ifset
22898 @ifset vxworks
22899 @node VxWorks Topics
22900 @chapter VxWorks Topics
22902 @noindent
22903 This chapter describes topics that are specific to the GNAT for VxWorks
22904 configurations.
22906 @menu
22907 * Kernel Configuration for VxWorks::
22908 * Kernel Compilation Issues for VxWorks::
22909 * Handling Relocation Issues for PowerPc Targets::
22910 * Support for Software Floating Point on PowerPC Processors::
22911 * Interrupt Handling for VxWorks::
22912 * Simulating Command Line Arguments for VxWorks::
22913 * Debugging Issues for VxWorks::
22914 * Using GNAT from the Tornado 2 Project Facility::
22915 * Frequently Asked Questions for VxWorks::
22916 @end menu
22918 @node Kernel Configuration for VxWorks
22919 @section Kernel Configuration for VxWorks
22921 @noindent
22922 When configuring your VxWorks kernel we recommend including the target
22923 shell. If you omit it from the configuration, you may get undefined
22924 symbols at load time, e.g.
22926 @smallexample
22927 -> ld < hello.exe
22928 Loading hello.exe
22929 Undefined symbols:
22930 mkdir
22931 @end smallexample
22933 @noindent
22934 Generally, such undefined symbols are harmless since these are used by
22935 optional parts of the GNAT run time. However if running your application
22936 generates a VxWorks exception or illegal instruction, you should reconfigure
22937 your kernel to resolve these symbols.
22939 @node Kernel Compilation Issues for VxWorks
22940 @section Kernel Compilation Issues for VxWorks
22942 @noindent
22943 If you plan to link an Ada module with a Tornado 2 Kernel, follow these steps.
22944 (Note that these recommendations apply to @file{cygnus-2.7.2-960126},
22945 shipped with Tornado 2 as the C compiler toolchain.)
22947 @itemize @bullet
22948 @item
22949 Compile your Ada module without linking it with the VxWorks Library:
22950 @smallexample
22951 gnatmake foo.adb -largs -nostdlib
22952 @end smallexample
22954 @item
22955 Edit your makefile and add on the @code{LIBS} line the exact path and name
22956 of the GCC library file provided with GNAT.
22957 @smallexample
22958 LIBS             = $(WIND_BASE)/target/lib/libPPC604gnuvx.a \
22959 /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a
22960 @end smallexample
22962 @noindent
22963 To know the exact name and location of this file, type
22964 @code{<arch>-gcc -print-libgcc-file-name} in a console. Note that this version of GCC is the
22965 one provided with GNAT.
22966 @smallexample
22967 ~ >powerpc-wrs-vxworks-gcc -print-libgcc-file-name
22968 /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a
22969 @end smallexample
22970 @end itemize
22973 @node Handling Relocation Issues for PowerPc Targets
22974 @section Handling Relocation Issues for PowerPc Targets
22975 @cindex Relocation issues for PowerPc VxWorks targets
22976 @cindex PowerPc VxWorks, relocation issues
22977 @cindex VxWorks PowerPc, relocation issues
22979 @noindent
22980 Under certain circumstances, loading a program onto a PowerPC
22981 board will fail with the message
22982 @emph{Relocation value does not fit in 24 bits}.
22984 For some background on this issue, please refer to WRS' SPRs
22985 6040, 20257, and 22767.
22986 In summary,
22987 VxWorks on the PowerPC follows the variation of the SVR4 ABI known
22988 as the Embedded ABI (@emph{EABI}).
22989 @cindex Embedded ABI (for VxWorks on PowerPc)
22990 @cindex EABI (for VxWorks on PowerPc)
22991 In order to save space and time in
22992 embedded applications, the EABI specifies that the default for
22993 subprogram calls should be the branch instruction with relative
22994 addressing using an immediate operand.  The immediate operand
22995 to this instruction (relative address) is 24 bits wide.  It
22996 is sign extended and 2#00# is appended for the last 2 bits (all
22997 instructions must be on a 4 byte boundary).
22998 The resulting
22999 26 bit offset means that the target of the branch must be within
23000 +/- 32 Mbytes of the relative branch instruction.  When VxWorks
23001 is loading a program it completes the linking phase by
23002 resolving all of the unresolved references in the object being
23003 loaded.  When one of those references is a relative address in
23004 a branch instruction, and the linker determines that the target
23005 is more than 32 Mbytes away from the branch, the error occurs.
23007 This only happens when the BSP is configured to use
23008 more than 32 MBytes of memory.  The VxWorks kernel is loaded into
23009 low memory addresses, and the error usually occurs when the target
23010 loader is used (because it loads objects into high memory, and thus
23011 calls from the program to the VxWorks kernel can be too far).
23012 @cindex VxWorks kernel (relocation issues on PowerPc)
23014 One way to solve this problem is to use the Tornado
23015 host loader; this will place programs in low memory, close to the kernel.
23017 Another approach is to make use of the @code{-mlongcall} option to the
23018 compiler;
23019 @cindex @code{-mlongcall} (gcc)
23020 GNAT has incorporated WRS'
23021 gcc modification that implements this option.
23022 If a subprogram call is
23023 compiled with the @code{-mlongcall} option, then the generated code
23024 constructs an absolute address in a register and uses a branch
23025 instruction with absolute addressing mode.
23027 Starting with release 3.15, the GNAT runtime libraries that are
23028 distributed are compiled with the @code{-mlongcall} option.  In many
23029 cases the use of these libraries is sufficient to avoid the
23030 relocation problem, since it is the runtime library that contains
23031 calls to the VxWorks kernel that need to span the address space gap.
23032 If you are using an earlier GNAT release or a manually-built runtime,
23033 you should recompile the GNAT runtime library with @code{-mlongcall};
23034 you can use the
23035 @file{Makefile.adalib} file from the @file{adalib} directory.
23037 Application code may need to be compiled with @code{-mlongcall} if there
23038 are calls directly to the kernel, the application is very large,
23039 or in some specialized linking/loading scenarios.
23041 You can compile individual files with @code{-mlongcall} by placing this
23042 option on the @code{gcc} command line (for brevity we are omitting the
23043 @code{powerpc-wrs-vxworks-} prefix on the commands shown in this
23044 paragraph).
23045 If you provide @code{-mlongcall} as an option for @code{gnatmake}, it will be
23046 passed to all invocations of @code{gcc} that @code{gnatmake} directly performs.
23047 Note that one other compilation is made by @code{gnatlink}, on the file created
23048 by @code{gnatbind} for the elaboration package body
23049 (see @ref{Binding Using gnatbind}).
23050 Passing @code{-mlongcall} to @code{gnatlink}, either directly
23051 on the @code{gnatlink} command line or by including @code{-mlongcall} in the
23052 @code{-largs} list of @code{gnatmake}, will direct @code{gnatlink} to compile the
23053 binder file with the @code{-mlongcall} option.
23055 To see the effect of @code{-mlongcall}, consider the following small example:
23057 @smallexample
23058    procedure Proc is
23059       procedure Imported_Proc;
23060       pragma Import (Ada, Imported_Proc);
23061    begin
23062       Imported_Proc;
23063    end;
23064 @end smallexample
23066 @noindent
23067 If you compile @code{Proc} with the default options (no @code{-mlongcall}), the following code is generated:
23069 @smallexample
23070    _ada_proc:
23071            ...
23072            bl imported_proc
23073            ...
23074 @end smallexample
23076 @noindent
23077 In contrast, here is the result with the @code{-mlongcall} option:
23079 @smallexample
23080    _ada_proc:
23081            ...
23082            addis 9,0,imported_proc@@ha
23083            addi 0,9,imported_proc@@l
23084            mtlr 0
23085            blrl
23086            ...
23087 @end smallexample
23090 @node Support for Software Floating Point on PowerPC Processors
23091 @section Support for Software Floating Point on PowerPC Processors
23093 @noindent
23094 The PowerPC 860 processor does not have hardware floating-point support.
23095 In order to build and run GNAT modules properly, you need to install and
23096 invoke software-emulated floating-point support as follows:
23098 @itemize @bullet
23099 @item
23100 At installation time:
23101 @itemize @bullet
23102 @item
23103 Create a file @file{ada_object_path} under the directory
23104 @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1}
23105 (by default @file{BASE}=@file{c:\gnatpro})
23106 containing the following line:
23107 @smallexample
23108 rts-soft-float\adalib
23109 @end smallexample
23111 @item
23112 Create a file @file{ada_source_path} under the directory
23113 @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1}
23114 (by default @file{BASE}=@file{c:\gnatpro})
23115 containing the following line:
23116 @smallexample
23117 rts-soft-float\adainclude
23118 @end smallexample
23119 @end itemize
23121 @item
23122 When using the compiler, specify @option{-msoft-float}
23123 as a compiler and a linker option, e.g.:
23124 @smallexample
23125 $powerpc-wrs-vxworks-gnatmake -msoft-float module -largs -msoft-float
23126 @end smallexample
23127 @end itemize
23130 @node Interrupt Handling for VxWorks
23131 @section Interrupt Handling for VxWorks
23133 @noindent
23134 GNAT offers a range of options for hardware interrupt handling. In rough
23135 order of latency and lack of restrictions:
23137 @itemize @bullet
23138 @item Directly vectored interrupt procedure handlers
23139 @item Directly vectored interrupt procedures that signal a task using
23140 a suspension object
23141 @item Ada 95 protected procedure handlers for interrupts
23142 @item Ada 83 style interrupt entry handlers for interrupts
23143 @end itemize
23145 @noindent
23146 In general, the range of possible solutions trades off latency versus
23147 restrictions in the handler code.  Restrictions in direct vectored
23148 interrupt handlers  are documented in the @cite{VxWorks Programmer's Guide}.
23149 Protected procedure handlers have only the
23150 restriction that no potentially blocking operations are performed within
23151 the handler.  Interrupt entries have no restrictions.  We recommend the
23152 use of the protected procedure mechanism as providing the best balance
23153 of these considerations for most applications.
23155 All handler types must explicitly perform any required hardware cleanups,
23156 such as issuing an end-of-interrupt if necessary.
23158 For VxWorks/AE, applications that handle interrupts must be loaded into
23159 the kernel protection domain.
23161 @itemize @bullet
23162 @item Direct Vectored Interrupt Routines
23164 @noindent
23165 This approach provides the lowest interrupt latency, but has the most
23166 restrictions on what VxWorks and Ada runtime calls can be made, as well
23167 as on what Ada entities are accessible to the handler code.  Such handlers
23168 are most useful when there are stringent latency requirements, and very
23169 little processing is to be performed in the handler.   Access to the
23170 necessary VxWorks routines for setting up such handlers is provided in
23171 the package @code{Interfaces.VxWorks}.
23173 VxWorks restrictions are described in the @cite{VxWorks Programmer's Manual}.
23174 Note in particular that floating point context is not automatically saved and
23175 restored when interrupts are vectored to the handler.  If the handler is
23176 to execute floating point instructions, the statements involved must be
23177 bracketed by a pair of calls to @code{fppSave} and @code{fppRestore} defined
23178 in @code{Interfaces.VxWorks}.
23180 In general, it is a good idea to save and restore the handler that was
23181 installed prior to application startup.  The routines @code{intVecGet}
23182 and @code{intVecSet} are used for this purpose.  The Ada handler code
23183 is installed into the vector table using routine @code{intConnect},
23184 which generates wrapper code to save and restore registers.
23186 Example:
23188 @smallexample
23189 with Interfaces.VxWorks; use Interfaces.VxWorks;
23190 with System;
23192 package P is
23194    Count : Natural := 0;
23195    pragma Atomic (Count);
23197    --  Interrupt level used by this example
23198    Level : constant := 1;
23200    --  Be sure to use a reasonable interrupt number for the target
23201    --  board!  Refer to the BSP for details.
23202    Interrupt : constant := 16#14#;
23204    procedure Handler (Parameter : System.Address);
23206 end P;
23208 package body P is
23210    procedure Handler (parameter : System.Address) is
23211       S : Status;
23212    begin
23213       Count := Count + 1;
23214       --  Acknowledge interrupt.  Not necessary for all interrupts.
23215       S := sysBusIntAck (intLevel => Level);
23216    end Handler;
23217 end P;
23219 with Interfaces.VxWorks; use Interfaces.VxWorks;
23220 with Ada.Text_IO; use Ada.Text_IO;
23222 with P; use P;
23223 procedure Useint is
23224    task T;
23226    S : Status;
23228    task body T is
23229    begin
23230       for I in 1 .. 10 loop
23231          Put_Line ("Generating an interrupt...");
23232          delay 1.0;
23234          --  Generate interrupt, using interrupt number
23235          S := sysBusIntGen (Level, Interrupt);
23236       end loop;
23237    end T;
23239    --  Save old handler
23240    Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt));
23241 begin
23242    S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access);
23243    S := sysIntEnable (intLevel => Level);
23245    for I in 1 .. 10 loop
23246       delay 2.0;
23247       Put_Line ("value of count:" & P.Count'Img);
23248    end loop;
23250    --  Restore previous handler
23251    S := sysIntDisable (intLevel => Level);
23252    intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler);
23253 end Useint;
23254 @end smallexample
23256 @item Direct Vectored Interrupt Routines
23258 @noindent
23259 A variation on the direct vectored routine that allows for less restrictive
23260 handler code is to separate the interrupt processing into two levels.
23262 The first level is the same as in the previous section.  Here we perform
23263 simple hardware actions and signal a task pending on a Suspension_Object
23264 (defined in @code{Ada.Synchronous_Task_Control}) to perform the more complex
23265 and time-consuming operations.  The routine @code{Set_True} signals a task
23266 whose body loops and pends on the suspension object using @code{Suspend_Until_True}.
23267 The suspension object is declared in a scope global to both the handler and
23268 the task. This approach can be thought of as a slightly higher-level
23269 application of the @code{C} example using a binary semaphore given in the
23270 VxWorks Programmer's Manual.  In fact, the implementation of
23271 @code{Ada.Synchronous_Task_Control} is a very thin wrapper around a VxWorks
23272 binary semaphore.
23274 This approach has a latency between the direct vectored approach and the
23275 protected procedure approach.  There are no restrictions in the Ada task
23276 code, while the handler code has the same restrictions as any other
23277 direct interrupt handler.
23279 Example:
23281 @smallexample
23282 with System;
23283 package Sem_Handler is
23285    Count : Natural := 0;
23286    pragma Atomic (Count);
23288    --  Interrupt level used by this example
23289    Level : constant := 1;
23290    Interrupt : constant := 16#14#;
23292    --  Interrupt handler providing "immediate" handling
23293    procedure Handler (Param : System.Address);
23295    --  Task whose body provides "deferred" handling
23296    task Receiver is
23297        pragma Interrupt_Priority
23298           (System.Interrupt_Priority'First + Level + 1);
23299     end Receiver;
23301 end Sem_Handler;
23303 with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control;
23304 with Interfaces.VxWorks; use Interfaces.VxWorks;
23305 package body Sema_Handler is
23307    SO : Suspension_Object;
23309    task body Receiver is
23310    begin
23311       loop
23312          --  Wait for notification from immediate handler
23313          Suspend_Until_True (SO);
23315          --  Interrupt processing
23316          Count := Count + 1;
23317       end loop;
23318    end Receiver;
23320    procedure Handler (Param : System.Address) is
23321       S : STATUS;
23322    begin
23323       --  Hardware cleanup, if necessary
23324       S := sysBusIntAck (Level);
23326       --  Signal the task
23327       Set_True (SO);
23328    end Handler;
23330 end Sem_Handler;
23332 with Interfaces.VxWorks; use Interfaces.VxWorks;
23333 with Ada.Text_IO; use Ada.Text_IO;
23334 with Sem_Handler; use Sem_Handler;
23335 procedure Useint is
23337    S : STATUS;
23339    task T;
23341    task body T is
23342    begin
23343       for I in 1 .. 10 loop
23344          Put_Line ("Generating an interrupt...");
23345          delay 1.0;
23347          --  Generate interrupt, using interrupt number
23348          S := sysBusIntGen (Level, Interrupt);
23349       end loop;
23350    end T;
23352    --  Save old handler
23353    Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt));
23354 begin
23355    S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access);
23356    S := sysIntEnable (intLevel => Level);
23358    for I in 1 .. 10 loop
23359       delay 2.0;
23360       Put_Line ("value of Count:" & Sem_Handler.Count'Img);
23361    end loop;
23363    --  Restore handler
23364    S := sysIntDisable (intLevel => Level);
23365    intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler);
23366    abort Receiver;
23367 end Useint;
23368 @end smallexample
23370 @item Protected Procedure Handlers for Interrupts
23372 @noindent
23373 This is the recommended default mechanism for interrupt handling.
23374 It essentially wraps the hybrid handler / task mechanism in a higher-level
23375 abstraction, and provides a good balance between latency and capability.
23377 Vectored interrupts are designated by their interrupt number, starting from
23378 0 and ranging to the number of entries in the interrupt vector table - 1.
23380 In the GNAT VxWorks implementation, the following priority mappings are used:
23381 @itemize @bullet
23382 @item Normal task priorities are in the range 0 .. 245.
23383 @item Interrupt priority 246 is used by the GNAT @code{Interrupt_Manager}
23384 task.
23385 @item Interrupt priority 247 is used for vectored interrupts
23386 that do not correspond to those generated via an interrupt controller.
23387 @item Interrupt priorities 248 .. 255 correspond to PIC interrupt levels
23388 0 .. 7.
23389 @item Priority 256 is reserved to the VxWorks kernel.
23390 @end itemize
23392 Except for reserved priorities, the above are recommendations for setting the
23393 ceiling priority of a protected object that handles interrupts, or the
23394 priority of a task with interrupt entries.  It's a very good idea to follow
23395 these recommendations for vectored interrupts that come in through the PIC
23396 as it will determine the priority of execution of the code in the protected
23397 procedure or interrupt entry.
23399 No vectored interrupt numbers are reserved in this implementation, because
23400 dedicated interrupts are determined by the board support package. Obviously,
23401 careful consideration of the hardware is necessary when handling interrupts.
23402 The VxWorks BSP for the board is the definitive reference for interrupt
23403 assignments.
23405 Example:
23407 @smallexample
23408 package PO_Handler is
23410    --  Interrupt level used by this example
23411    Level : constant := 1;
23413    Interrupt : constant := 16#14#;
23415    protected Protected_Handler is
23416       procedure Handler;
23417       pragma Attach_Handler (Handler, Interrupt);
23419       function Count return Natural;
23421       pragma Interrupt_Priority (248);
23422    private
23423       The_Count : Natural := 0;
23424    end Protected_Handler;
23426 end PO_Handler;
23428 with Interfaces.VxWorks; use Interfaces.VxWorks;
23429 package body PO_Handler is
23431    protected body Protected_Handler is
23433       procedure Handler is
23434          S : Status;
23435       begin
23436          --  Hardware cleanup if necessary
23437          S := sysBusIntAck (Level);
23439          --  Interrupt processing
23440          The_Count := The_Count + 1;
23441       end Handler;
23443       function Count return Natural is
23444       begin
23445          return The_Count;
23446       end Count;
23447    end Protected_Handler;
23449 end PO_Handler;
23451 with Interfaces.VxWorks; use Interfaces.VxWorks;
23452 with Ada.Text_IO; use Ada.Text_IO;
23454 with PO_Handler; use PO_Handler;
23455 procedure Useint is
23457    task T;
23459    S : STATUS;
23461    task body T is
23462    begin
23463       for I in 1 .. 10 loop
23464          Put_Line ("Generating an interrupt...");
23465          delay 1.0;
23467          --  Generate interrupt, using interrupt number
23468          S := sysBusIntGen (Level, Interrupt);
23469       end loop;
23470    end T;
23472 begin
23473    S := sysIntEnable (intLevel => Level);
23475    for I in 1 .. 10 loop
23476       delay 2.0;
23477       Put_Line ("value of count:" & Protected_Handler.Count'Img);
23478    end loop;
23480    S := sysIntDisable (intLevel => Level);
23481 end Useint;
23482 @end smallexample
23484 @noindent
23485 This is obviously significantly higher-level and easier to write than the
23486 previous examples.
23488 @item Ada 83 Style Interrupt Entries
23490 GNAT provides a full implementation of the Ada 83 interrupt entry mechanism
23491 for vectored interrupts.  However, due to latency issues,
23492 we only recommend using these for backward compatibility.  The comments in
23493 the previous section regarding interrupt priorities and reserved interrupts
23494 apply here.
23496 In order to associate an interrupt with an entry, GNAT provides the
23497 standard Ada convenience routine @code{Ada.Interrupts.Reference}.  It is used
23498 as follows:
23500 @smallexample
23501 Interrupt_Address : constant System.Address :=
23502    Ada.Interrupts.Reference (Int_Num);
23504 task Handler_Task is
23505    pragma Interrupt_Priority (248);  -- For instance
23506    entry Handler;
23507    for Handler'Address use Interrupt_Address;
23508 end Handler_Task;
23509 @end smallexample
23511 @noindent
23512 Since there is no restriction within an interrupt entry on blocking operations,
23513 be sure to perform any hardware interrupt controller related operations before
23514 executing a call that could block within the entry's accept statements.  It
23515 is assumed that interrupt entries are always open alternatives when they
23516 appear within a selective wait statement.  The presence of a guard gives
23517 undefined behavior.
23519 Example:
23521 @smallexample
23522 with Ada.Interrupts;
23523 with System;
23524 package Task_Handler is
23526    --  Interrupt level used by this example
23527    Level : constant := 1;
23529    Interrupt : constant := 16#14#;
23531    Interrupt_Address : constant System.Address :=
23532       Ada.Interrupts.Reference (Int_Num);
23534    task Handler_Task is
23535       pragma Interrupt_Priority (248);  -- For instance
23536       entry Handler;
23537       for Handler'Address use Interrupt_Address;
23539       entry Count (Value : out Natural);
23540    end Handler_Task;
23541 end Task_Handler;
23543 with Interfaces.VxWorks; use Interfaces.VxWorks;
23544 package body Task_Handler is
23546    task body Handler_Task is
23547       The_Count : Natural := 0;
23548       S : STATUS;
23549    begin
23550       loop
23551          select
23552             accept Handler do
23553                --  Hardware cleanup if necessary
23554                S := sysBusIntAck (Level);
23556                --  Interrupt processing
23557                The_Count := The_Count + 1;
23558             end Handler;
23559          or
23560             accept Count (Value : out Natural) do
23561                Value := The_Count;
23562             end Count;
23563          end select;
23564       end loop;
23565    end Handler_Task;
23567 end Handler_Task;
23569 with Interfaces.VxWorks; use Interfaces.VxWorks;
23570 with Ada.Text_IO; use Ada.Text_IO;
23572 with Handler_Task; use Handler_Task;
23573 procedure Useint is
23575    task T;
23577    S : STATUS;
23578    Current_Count : Natural := 0;
23580    task body T is
23581    begin
23582       for I in 1 .. 10 loop
23583          Put_Line ("Generating an interrupt...");
23584          delay 1.0;
23586          --  Generate interrupt, using interrupt number
23587          S := sysBusIntGen (Level, Interrupt);
23588       end loop;
23589    end T;
23591 begin
23592    S := sysIntEnable (intLevel => Level);
23594    for I in 1 .. 10 loop
23595       delay 2.0;
23596       Handler_Task.Count (Current_Count);
23597       Put_Line ("value of count:" & Current_Count'Img);
23598    end loop;
23600    S := sysIntDisable (intLevel => Level);
23601    abort Handler_Task;
23602 end Useint;
23603 @end smallexample
23604 @end itemize
23607 @node Simulating Command Line Arguments for VxWorks
23608 @section Simulating Command Line Arguments for VxWorks
23610 @noindent
23611 The GNAT implementation of @code{Ada.Command_Line} relies on the standard C
23612 symbols @code{argv} and @code{argc}.  The model for invoking "programs" under
23613 VxWorks does not provide these symbols.  The typical method for invoking a
23614 program under VxWorks is to call the @code{sp} function in order to spawn a
23615 thread in which to execute a designated function (in GNAT, this is the implicit
23616 main generated by gnatbind. @code{sp} provides the capability to push a variable
23617 number of arguments onto the stack when the function is invoked.  But this does
23618 not work for the implicit Ada main, because it has no way of knowing how many
23619 arguments might be required.  This eliminates the possibility to use
23620 @code{Ada.Command_Line}.
23622 One way to solve this problem is to define symbols in the VxWorks environment,
23623 then import them into the Ada application.  For example, we could define the
23624 following package that imports two symbols, one an int and the other a string:
23626 @smallexample
23627 with Interfaces.C.Strings;
23628 use Interfaces.C.Strings;
23629 package Args is
23630    --  Define and import a variable for each argument
23631    Int_Arg : Interfaces.C.Int;
23632    String_Arg : Chars_Ptr;
23633 private
23634    pragma Import (C, Int_Arg, "intarg");
23635    pragma Import (C, String_Arg, "stringarg");
23636 end Args;
23637 @end smallexample
23639 @noindent
23640 An Ada unit could then use the two imported variables @code{Int_Arg} and
23641 @code{String_Arg} as follows:
23643 @smallexample
23644 with Args; use Args;
23645 with Interfaces.C.Strings;
23646 use Interfaces.C, Interfaces.C.Strings;
23647 with Ada.Text_IO; use Ada.Text_IO;
23648 procedure Argtest is
23649 begin
23650    Put_Line (Int'Image (Int_Arg));
23651    Put_Line (Value (String_Arg));
23652 end Argtest;
23653 @end smallexample
23655 @noindent
23656 When invoking the application from the shell, one will then set the values
23657 to be imported, and spawn the application, as follows:
23659 @smallexample
23660 -> intarg=10
23661 -> stringarg="Hello"
23662 -> sp (argtest)
23663 @end smallexample
23666 @node Debugging Issues for VxWorks
23667 @section Debugging Issues for VxWorks
23669 @noindent
23670 The debugger can be launched directly from the Tornado environment or from @code{glide}
23671 through its graphical interface: @code{gvd}. It can also be used
23672 directly in text mode as shown below:
23673 @noindent
23674 The command to run @code{GDB} in text mode is
23676 @smallexample
23677 $ @i{target}-gdb
23678 @end smallexample
23680 @noindent
23681 where @i{target} is the name of target of the cross GNAT
23682 compiler. In contrast with native @code{gdb}, it is not useful to give the name of
23683 the program to debug on the command line. Before starting a debugging
23684 session, one needs to connect to the VxWorks-configured board and load
23685 the relocatable object produced by @code{gnatlink}. This can be achieved
23686 by the following commands:
23688 @smallexample
23689 (vxgdb) target wtx myboard
23690 (vxgdb) load program
23691 @end smallexample
23693 @noindent
23694 where @code{myboard} is the host name or IP number of the target board, and
23695 @code{wtx} is the name of debugging protocol used to communicate
23696 with the VxWorks board. Early versions of VxWorks, up tp 5.2, only
23697 support the @code{<vxworks>} protocol whereas starting with VxWorks 5.3
23698 and Tornado, another protocol called  @code{<wtx>} was made available. The
23699 choice of the protocol can be made when configuring the VxWorks
23700 kernel itself. When available, the @code{<wtx>} is greatly preferable
23701 and actually the only supported protocol with GNAT. When the debugger
23702 is  launched directly from Tornado, the proper @code{target} command
23703 is automatically generated by the environment.
23705 The GNAT debugger can be used for debugging multitasking programs in two
23706 different modes and some minimal understanding of these modes is
23707 necessary in order to use the debugger effectively. The two modes are:
23709 @itemize @bullet
23710 @item Monotask mode: attach to, and debug, a single task.
23711 This mode is equivalent to the capabilities offered by CrossWind. The
23712 debugger interacts with a single task, while not affecting other tasks
23713 (insofar as possible). This is the DEFAULT mode.
23715 @item Multitask mode:
23716 The debugger has control over all Ada tasks in an application. It is
23717 possible to gather information about all application tasks, and to
23718 switch from one to another within a single debugging session.
23719 @end itemize
23721 @noindent
23722 It is not advised to switch between the two modes within a debugging
23723 session. A third mode called System mode is also available and can be
23724 used in place of the Multitask mode. Consult the Tornado documentation
23725 for this.
23727 Among the criteria for selecting the appropriate mode is the effect of
23728 task synchronization on the application's behavior. Debugging a
23729 tasking application affects the timing of the application; minimizing
23730 such effects may be critical in certain situations. The two modes have
23731 different effects: monotask mode only affects the attached task:
23732 others will run normally (if possible). Multitask mode stops all tasks
23733 at each breakpoint and restarts them on single-step, next, finish or
23734 continue; this may help avoid deadlocks in the presence of task
23735 synchronization despite the inherent latency of stopping and
23736 restarting the tasks.
23738 @subsection Using the debugger in monotask mode
23740 @noindent
23741 There are two ways to begin your debugging session:
23743 @itemize @bullet
23744 @item The program is already running on the board.
23746 @noindent
23747 The sequence of commands to use this mode is:
23748 @itemize @bullet
23749 @item Launch GVD (possibly from the Tornado menu)
23751 @noindent
23752 Verify that the debugger has access to the debug information of both
23753 your program and the kernel. The Console window should have a message
23754 "Looking for all loaded modules:" followed by the names of the modules
23755 on the board and "ok". If you have some error messages here instead of
23756 "ok", the debugging session may not work as expected.
23758 @item Attach to the desired task using
23759 @smallexample
23760         File --> Attach...
23761 @end smallexample
23762 @noindent
23763 This task is stopped by the debugger. Other tasks continue to operate
23764 normally (unless they are blocked by synchronization with the stopped
23765 task). The source window should display the code on which the task has
23766 been stopped, and if the stack display is enabled, it should reflect
23767 the stack of the task.
23768 @end itemize
23770 @item The program hasn't been loaded yet on the board
23771 @itemize @bullet
23772 @item Launch GVD (possibly from the Tornado menu)
23773 @item Load your program to the board:
23774 @smallexample
23775 File --> Open Program...
23776 @end smallexample
23778 @noindent
23779 GVD should display:
23780 @smallexample
23781 Downloading your_program ...done.
23782 Reading symbols from your_program...expanding to full symbols...done.
23783 @end smallexample
23785 @item Set breakpoints in your program.
23787 @noindent
23788 WARNING: they must be set in the main task (if your program runs
23789 several tasks)
23791 @item Run your program using one of the three methods below:
23792 @itemize @bullet
23793 @item
23794 Click on button <run> or <start>
23796 @item Menu
23797 @smallexample
23798 Program --> Run/Start
23799 @end smallexample
23801 @item
23802 Type in GVD's Console window
23803 @smallexample
23804 (gdb) run your_program
23805 @end smallexample
23806 @end itemize
23807 @end itemize
23809 @item Whichever method you chose to start your debugging session,
23810 you can use the following commands at this point:
23811 @itemize @bullet
23812 @item  Browse sources and set breakpoints
23813 @item  Examine the call stack (Data --> call stack)
23814 @item  Go "up" and "down" in the call stack ("up" & "down" buttons)
23815 @item  Examine data
23816 (Data --> Display local variables, or any of the other methods for viewing data in GVD)
23817 @item Continue/finish
23818 @end itemize
23820 Next/step/finish will only work if the top frame in the call stack has
23821 debug information.  This is almost never the case when first attaching
23822 to the task since the task is usually stopped by the attach operation
23823 in the GNAT runtime. You can verify which frames of the call stack
23824 have debug information by:
23825 @smallexample
23826 Data --> call stack
23827 <right Button> (contextual menu inside the call stack window)
23828  add "file location"
23829 @end smallexample
23831 @noindent
23832 If the current frame does not have a "file location", then there is no
23833 debug information for the frame.  We strongly recommended that you set
23834 breakpoints in the source where debug information can be found and
23835 "continue" until a breakpoint is reached before using
23836 "next/step". Another convenient possibility is to use the "continue
23837 until" capability available from the contextual menu of the Source
23838 window.
23840 You can also examine the state of other tasks using
23841 @smallexample
23842 Data -> tasks
23843 @end smallexample
23845 @noindent
23846 but you can't "switch" to another task by clicking on the
23847 elements of the task list. If you try to, you will get an error
23848 message in GVD's console:
23849 @smallexample
23850 "Task switching is not allowed when multi-tasks mode is not active"
23851 @end smallexample
23853 @noindent
23854 Once you have completed your debugging session on the attached
23855 task, you can detach from the task:
23856 @smallexample
23857 File --> detach
23858 @end smallexample
23860 @noindent
23861 The task resumes normal execution at this stage.  WARNING: when you
23862 detach from a task, be sure that you are in a frame where there is
23863 debug information. Otherwise, the task won't resume properly. You can
23864 then start another attach/detach cycle if you wish.
23866 Note that it is possible to launch several GVD sessions and
23867 simultaneously attach each to a distinct task in monotask mode:
23868 @smallexample
23869 File --> New Debugger...  (uncheck the box: Replace Current Debugger)
23870 File --> Attach...     (in the new window)
23871 File --> detach
23872 @end smallexample
23873 @end itemize
23876 @subsection Using the debugger in Multitask mode
23878 @noindent
23879 The steps are as follows
23881 @itemize @bullet
23882 @item
23883 Launch GVD (possibly from the Tornado menu)
23885 @noindent
23886 There are two possibilities:
23887 @itemize @bullet
23888 @item
23889 If the program is already loaded on the target board, you need only verify
23890 that debug information has been found by the debugger as described
23891 above.
23893 @item
23894 Otherwise, load the program on the board using
23895 @smallexample
23896 File --> Open program
23897 @end smallexample
23898 @end itemize
23900 @item Set breakpoints in the desired parts of the program
23902 @item Start the program
23904 @noindent
23905 The simplest way to start the debugger in multitask mode is to use the
23906 menu
23907 @smallexample
23908 Program --> Run/Start
23909 @end smallexample
23911 @noindent
23912 and check the box "enable vxWorks multi-tasks mode".
23913 You can also use the following gdb commands in the console window
23914 @smallexample
23915         (gdb) set multi-tasks-mode on
23916         (gdb) run your_program
23917 @end smallexample
23919 @item Debug the stopped program
23921 @noindent
23922 Once stopped at a breakpoint
23923 (or if you pressed the "stop" button), you can use all the standard
23924 commands listed for monotask mode + task switching (using Data -->
23925 tasks). Using next/step under this mode is possible with the same
23926 restrictions as for monotask mode, but is not recommended because all
23927 tasks are restarted, leading to the possibility that a different task
23928 hits a breakpoint before the stepping operation has completed.  Such
23929 an occurrence can result in a confusing state for both the user and
23930 the debugger. So we strongly suggest the use of only breakpoints and
23931 "continue" in this mode.
23932 @end itemize
23934 A final reminder: whatever the mode, whether you are debugging or not,
23935 the program has to be reloaded before each new execution, so that data
23936 initialized by the loader is set correctly. For instance, if you wish
23937 to restart the same execution of the same program, you can use the
23938 following sequence of gdb commands in the console window:
23939 @smallexample
23940 (gdb) detach
23941 (gdb) unload your_program(.exe)
23942 (gdb) load your_program(.exe)
23943 (gdb) run your_program
23944 @end smallexample
23947 @node Using GNAT from the Tornado 2 Project Facility
23948 @section Using GNAT from the Tornado 2 Project Facility
23949 @cindex Tornado II Project
23951 @menu
23952 * The GNAT Toolchain as Used from the Tornado 2 Project Facility::
23953 * Building a Simple Application::
23954 * Mixing C and Ada Code in a Tornado 2 Project::
23955 * Compilation Switches::
23956 * Autoscale and Minimal Kernel Configuration::
23957 * Adapting BSPs to GNAT::
23958 * Using GNAT Project Files in a Tornado 2 Project::
23959 @end menu
23961 @noindent
23962 This section describes how to add an Ada module in a Tornado project
23963 using the Tornado 2 Project facility described in
23964 @cite{Tornado User's Guide}, Chapter 4.
23965 All recommendations apply for both 'Downloadable Modules' and 'Kernel'
23966 project types.
23969 @node The GNAT Toolchain as Used from the Tornado 2 Project Facility
23970 @subsection The GNAT Toolchain as Used from the Tornado 2 Project Facility
23972 @noindent
23973 Tornado 2 allows you to integrate third-party C toolchains.
23974 (@cite{Tornado 2 API Programmer's Guide}, Chapter 7).
23975 Thus the GNAT toolchain will be seen as a new C toolchain when used from
23976 the Tornado 2 Project Facility. For each processor you can compile for,
23977 you will find a <proc>gnat toolchain, e.g. PPC604gnat. These toolchains will
23978 allow you to include Ada modules into your projects, and simply build them.
23980 The name of the so-called C compiler is @emph{cc_gnat_<arch>}, the name
23981 of the 'linker' is @emph{ld_gnat_<arch>}, where <arch> is an architecture; e.g.,
23982 PPC. These scripts will call the correct executables during the compilation or
23983 link processes, thus the C compiler, the C linker, or the GNAT toolchain,
23984 depending on the context.
23987 @node  Building a Simple Application
23988 @subsection  Building a Simple Application
23990 @noindent
23991 First, create a new project, using one of the gnat toolchains.
23993 To add an Ada source file to the current project, just click on
23994 @code{Project -> Add/Include}, browse to the relevant file, and include it.
23995 The Ada source file included should be the Ada entry point. Only
23996 one Ada entry point is allowed in a project. Any other required Ada source
23997 files will be automatically compiled and linked by the underlying tools.
23999 You can now compile the project, @code{Build->Rebuild all}.
24000 A log of the compilation process can be found in the build directory, in
24001 @file{gnatbuild.log}. It contains all the calls executed by the scripts, and
24002 associated information.
24005 @node Mixing C and Ada Code in a Tornado 2 Project
24006 @subsection Mixing C and Ada Code in a Tornado 2 Project
24008 @noindent
24009 You can mix C and Ada code in your projects. Your source files and the build
24010 options should comply with the recommendations from the section
24011 @cite{Interfacing to C}.
24012 This means that you can have several or no C source files, and one or no Ada entry
24013 point in your Tornado 2 Project.
24016 @node Compilation Switches
24017 @subsection Compilation Switches
24018 @noindent
24019 Once you have included all your source files, you may modify some compilation
24020 and linking options.
24021 To pass specific options to the GNAT toolchain, go to the Project's build
24022 settings, on the @code{C/C++ Compiler} tab, and add your arguments in the
24023 input window.
24025 You must comply with several rules to pass arguments to GNAT.
24026 Arguments to be passed should be
24028 @itemize @bullet
24030 @item after any arguments passed to the C toolchain.
24032 @item prefixed depending on the tool that uses them, with the following syntax
24034 @itemize @bullet
24035 @item @code{-cargs @emph{gnatmake-options}} to pass arguments to gnatmake
24036 @item @code{-bargs @emph{gnatbind-options}} to pass arguments to gnatbind
24037 @item @code{-largs @emph{gnatlink-options}} to pass arguments to gnatlink
24038 @end itemize
24039 @end itemize
24041 @noindent
24042 You will find more information on the compilation process of Ada source files
24043 in the section @cite{The GNAT Compilation Model}.
24044 For a list of all available switches, refer to the sections describing
24045 @code{gnatmake}, @code{gnatbind} and @code{gnatlink}.
24047 Here is an example that passes the option @code{-v} to the GNAT compiler :
24048 @smallexample
24049 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
24050 -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
24051 -cargs -v
24052 @end smallexample
24054 @noindent
24055 Here is an example that passes the option @code{-v} to the GNAT compiler, binder and linker,
24056 and @code{-v} and @code{-g} to the compiler :
24057 @smallexample
24058 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
24059 -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
24060 -cargs -v -g -O2 -bargs -v -largs -v
24061 @end smallexample
24063 @noindent
24064 In both examples, the following arguments have been automatically added by the Project
24065 Facility, and will be used by the C compiler.
24066 @smallexample
24067 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
24068 -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
24069 @end smallexample
24071 @noindent
24072 Note: The @code{-prjtype $(PRJ_TYPE)} option present in a few input
24073 boxes is used by the GNAT toolchain. It is required for the compilation
24074 process. You should not remove it from any input box.
24077 @node Autoscale and Minimal Kernel Configuration
24078 @subsection Autoscale and Minimal Kernel Configuration
24080 @noindent
24081 The Autoscale feature, present in the Project Facility  can be used on your
24082 VxWorks Kernel projects to determine the minimum set of components required
24083 for your kernel to work.
24084 (Please refer to the @cite{Tornado II User's Guide} Section 4.4 for more details.)
24085 This feature is also available for projects involving Ada code. Just click on
24086 @code{Project->Autoscale} to launch a check and determine the minimal kernel
24087 configuration.
24090 @node Adapting BSPs to GNAT
24091 @subsection Adapting BSPs to GNAT
24093 @noindent
24094 To use your Board Support Packages with the GNAT toolchain, you will have to adapt them,
24095 either manually or using the @code{adaptbsp4gnat} script.
24096 This procedure is described in the @cite{Tornado API Programmer's Guide},
24097 Chapter 7.
24098 Here is a summary of this setup, depending on the context.
24100 @itemize @bullet
24101 @item To do the adaptation manually:
24103 @itemize @bullet
24105 @item Copy your BSP directory contents into a new directory
24107 @item Go to this directory
24109 @item Edit the file @file{Makefile},
24111 @itemize @bullet
24112 @item Set tool to gnat, @code{TOOL=gnat}
24114 @item Reverse the order of the following lines
24115 @itemize @bullet
24116 @item @code{include $(TGT_DIR)/h/make/make.$(CPU)$(TOOL)}
24117 @item @code{include $(TGT_DIR)/h/make/defs.$(WIND_HOST_TYPE)}
24118 @end itemize
24120 @end itemize
24122 @end itemize
24124 @item To do the adaptation automatically, you may use the @code{adaptbsp4gnat}
24125 script. Its syntax is @code{adaptbsp4gnat <path_to_bsp>}.
24127 @noindent
24128 This script follows the different steps described above to perform the
24129 adaptation.
24130 The name of the new bsp is given after the modification.  By default, if
24131 @file{<bsp>} is the name of your BSP, @file{<bsp>-gnat}, will be the name of
24132 the BSP created.
24133 @end itemize
24136 @node Using GNAT Project Files in a Tornado 2 Project
24137 @subsection Using GNAT Project Files in a Tornado 2 Project
24139 @noindent
24140 You can use GNAT Project files to compile your Ada files.
24141 To do so, you need to use the @option{-Pproject_file.gpr} option from @command{gnatmake}.
24142 The path to the project file can be either absolute, or relative to the build
24143 directory, i.e. where the executable will be placed (e.g. @file{~/myproject/PPC604gnat}).
24144 Your project file should set the @code{Object_Dir} variable to a specific
24145 value.
24146 @smallexample
24147 project Sample is
24149    Target := external ("TARGET_DIR");
24150    for Object_Dir use Target;
24152 end Sample;
24153 @end smallexample
24156 @node Frequently Asked Questions for VxWorks
24157 @section Frequently Asked Questions for VxWorks
24159 @itemize @bullet
24161 @item
24162 When I run my program twice on the board, it does not work, why?
24164 @noindent
24165 Usually, Ada programs require elaboration and finalization, so the
24166 compiler creates a wrapper procedure whose name is the same as the Ada
24167 name of the main subprogram, which takes care of calling the elaboration
24168 and finalization routines before and after your program. But the static
24169 part of the elaboration is taken care of while loading the program
24170 itself and thus if you launch it twice this part of the elaboration will
24171 not be performed. This affects the proper elaboration of the
24172 GNAT runtime and thus it is mandatory to reload your program before
24173 relaunching it.
24175 @item
24176 Can I load a collection of subprograms rather than a standalone program?
24178 @noindent
24179 It is possible to write Ada programs with multiple entry points which
24180 can be called from the VxWorks shell; you just need to consider your
24181 main program as the VxWorks shell itself and generate an Ada subsystem
24182 callable from outside @xref{Binding with Non-Ada Main Programs}. If you
24183 use this method, you need to call @code{adainit} manually before calling
24184 any Ada entry point.
24186 @item
24187 When I use the @code{break exception} command, I get the message
24188 @code{"exception" is not a function}, why?
24190 You are not in the proper language mode. Issue the command:
24191 @smallexample
24192 (vxgdb) set language ada
24193 @end smallexample
24195 @item
24196 When I load a large application from the VxWorks shell using the "ld"
24197 command, the load hangs and never finishes. How can I load large
24198 executables?
24200 This is a classic VxWorks problem when using the default "rsh" communication
24201 method. Using NFS instead should work. Use the @code{nfsShowMount} command to
24202 verify that your program is in a NFS mounted directory.
24204 @item
24205 When I load a large application from the debugger using the wtx target
24206 connection, the load never finishes, why?
24208 Make sure that the memory cache size parameter of the target server is
24209 large enough. (@code{target -m big_enough_size}, or Memory cache size box in GUI.)
24210 See @cite{Tornado 1.01 API Programming Guide}, Section 3.6.2.
24212 @item
24213 When I spawn my program under the VxWorks shell, interactive input does
24214 not work, why?
24216 Only programs directly launched from the shell can have interactive
24217 input. For a program spawned with the @code{sp} or @code{taskSpawn}
24218 command, you need to have file redirection for input:
24219 @smallexample
24220 ->    # here you can have interactive input
24221 -> main
24222 ->    # here you cannot
24223 -> sp main
24224 ->    # neither here
24225 -> taskSpawn("ess",100,0,8000000,main)
24226 ->    # but you can input from a file:
24227 -> taskSpawn("Bae",100,0,8000000,main) < input_file
24228 @end smallexample
24229 @end itemize
24232 @node LynxOS Topics
24233 @chapter LynxOS Topics
24234 @noindent
24235 This chapter describes topics that are specific to the GNAT for LynxOS
24236 cross configurations.
24238 @menu
24239 * Getting Started with GNAT on LynxOS::
24240 * Kernel Configuration for LynxOS::
24241 * Patch Level Issues for LynxOS::
24242 * Debugging Issues for LynxOS::
24243 * An Example Debugging Session for LynxOS::
24244 @end menu
24246 @node Getting Started with GNAT on LynxOS
24247 @section Getting Started with GNAT on LynxOS
24249 @noindent
24250 This section is a starting point for using GNAT to develop and
24251 execute Ada 95 programs for LynuxWorks' LynxOS target environment from a
24252 Unix host environment.
24253 We assume that you know how to use GNAT in a native environment
24254 and how to start a telnet or other login session to connect to your LynxOS board.
24256 To compile code for a LynxOS system running on a PowerPC
24257 board, the basic compiler command is
24258 @command{powerpc-xcoff-lynxos-gcc}.
24260 With GNAT, the easiest way to build the basic @code{Hello World} program is
24261 with @code{gnatmake}. For the LynxOS PowerPC target this would look
24262 like:
24264 @smallexample
24265 $ powerpc-xcoff-lynxos-gnatmake hello
24266 @i{powerpc-xcoff-lynxos-gcc -c hello.adb
24267 powerpc-xcoff-lynxos-gnatbind -x hello.ali
24268 powerpc-xcoff-lynxos-gnatlink hello.ali}
24269 @end smallexample
24271 @noindent
24272 (The first line is the command entered by the user -- the subseqent three
24273 are the programs run by @code{gnatmake}.)
24275 This creates the executable @command{hello}" which you then need to load on the
24276 board (using ftp or an NFS directory for example) to run it.
24279 @node Kernel Configuration for LynxOS
24280 @section Kernel Configuration for LynxOS
24282 @noindent
24283 The appropriate configuration for your LynxOS kernel depends
24284 on the target system and the requirements of your application. GNAT itself
24285 adds no additional demands; however in some situations it may be appropriate
24286 to increase the conservative
24287 resource assumptions made by the default configuration.
24289 Kernel parameters limiting the maximum number of file descriptors,
24290 kernel and user threads, synchronization objects, etc., may be set in the
24291 file @file{uparam.h}. You may also wish to modify the file
24292 @file{/etc/starttab}, which places limits on data, stack, and core file
24293 size. See the documentation provided by LynuxWorks for more information.
24296 @node Patch Level Issues for LynxOS
24297 @section Patch Level Issues for LynxOS
24299 @noindent
24300 The GNAT runtime requires that your system run at patch level 040 or
24301 later. Please see the file @file{PatchCompatibility.txt} from the
24302 distribution for more information.
24305 @node Debugging Issues for LynxOS
24306 @section Debugging Issues for LynxOS
24308 @noindent
24309 GNAT's debugger is based on the same GNU gdb technology as the debugger
24310 provided by LynxOS, though with a great number of extensions and
24311 enhancements to support the Ada language and GNAT. The LynxOS
24312 documentation is relevant to understanding how to get the debugger
24313 started if you run into difficulties.
24315 To demonstrate a debugging session, we will use a slightly more complex
24316 program called @file{demo1.adb}, which can be found in the @file{examples}
24317 directory of the GNAT distribution. This program is compiled with
24318 debugging information as follows:
24320 @smallexample
24321 $ powerpc-xcoff-lynxos-gnatmake -g demo1
24322 powerpc-xcoff-lynxos-gcc -c -g demo1.adb
24323 powerpc-xcoff-lynxos-gcc -c -g gen_list.adb
24324 powerpc-xcoff-lynxos-gcc -c -g instr.adb
24325 powerpc-xcoff-lynxos-gnatbind -x demo1.ali
24326 powerpc-xcoff-lynxos-gnatlink -g demo1.ali
24327 @end smallexample
24329 @noindent
24330 Once the executable is created, copy it to your working directory on the
24331 board. In this directory, you will have to launch the gdb server and
24332 choose a free port number on your TCP/IP socket. Presuming the Internet
24333 hostname of the board is @file{myboard} and the port chosen is 2345,
24334 issue the following command:
24336 @smallexample
24337 myboard> gdbserver myboard:2345 demo1
24338 @end smallexample
24340 @noindent
24341 Then return to your host environment.
24343 The graphical debugger interface, @command{gvd}, supports both native
24344 and cross environments at the same time. @command{gvd} can be launched from
24345 @command{Glide} (see @file{README.Glide} for more information on customizing
24346 @command{Glide} for LynxOS) or it can be launched from the command line as
24347 follows:
24349 @smallexample
24350 $ gvd --debugger powerpc-xcoff-lynxos-gdb
24351 @end smallexample
24353 @noindent
24354 Then to attach to the target, enter in @command{gvd}'s command line window:
24356 @smallexample
24357 (gdb) target remote myboard:2345
24358 @end smallexample
24360 @noindent
24361 For more information see the GVD documentation.
24363 The comments below concern debugging directly from the command line but
24364 they also apply to @command{gvd}, though in most cases an equivalent
24365 graphical command is also available.
24367 To run the cross debugger from the command line without the visual
24368 interface use the command @code{powerpc-xcoff-lynxos-gdb}.
24370 You will see something like:
24372 @smallexample
24373 GNU gdb 4.17.gnat.3.14a1
24374 Copyright 1998 Free Software Foundation, Inc.
24375 GDB is free software, covered by the GNU General Public License, and you are
24376 welcome to change it and/or distribute copies of it under certain conditions.
24377 Type "show copying" to see the conditions.
24378 There is absolutely no warranty for GDB.  Type "show warranty" for details.
24379 This GDB was configured as "--host=sparc-sun-solaris2.5.1 --target=powerpc-xc
24380 off-lynxos".
24381 (gdb)
24382 @end smallexample
24384 @noindent
24385 Where @command{(gdb)} is the debugger's prompt. The first thing to do at the
24386 prompt from within @command{gdb} is to load the symbol table from the
24387 executable:
24389 @smallexample
24390 (gdb) file demo1
24391 Reading symbols from demo1...done.
24392 (gdb)
24393 @end smallexample
24395 @noindent
24396 You then have to attach to the server running on the board. Issue the command:
24398 @smallexample
24399 (gdb) target remote myboard:2345
24400 @end smallexample
24402 @noindent
24403 After the server has been started and attached from the host, the program is
24404 running on the target but has halted execution at the very beginning.
24405 The following commands set a breakpoint and continue execution:
24407 @smallexample
24408 (gdb) break demo1.adb:37
24409 Breakpoint 1 at 0x100064d0: file demo1.adb, line 37.
24410 (gdb) cont
24411 Continuing.
24413 Breakpoint 1, demo1 () at demo1.adb:37
24414 37         Set_Name (Fuel, "Fuel");
24415 (gdb)
24416 @end smallexample
24418 @noindent
24419 Here the execution has stopped at the breakpoint set above. Now
24420 you can use the standard @code{gdb} commands to examine the stack and
24421 program variables.
24423 Note that once execution has completed, the server on the board must be
24424 restarted before a new debugging session may begin.
24426 @node An Example Debugging Session for LynxOS
24427 @section An Example Debugging Session for LynxOS
24429 @noindent
24430 Carrying on a little further with the debugging session, the following
24431 example illustrates some of the usual debugging commands for moving
24432 around and seeing where you are:
24434 @smallexample
24435 (gdb) next
24436 38         Set_Name (Water, "Water");
24437 (gdb) bt
24438 #0  demo1 () at demo1.adb:38
24439 #1  0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at
24440 b~demo1.adb:118
24441 #2  0x10017538 in runmainthread ()
24442 #3  0x10001048 in __start ()
24443 (gdb) up
24444 #1  0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at
24445 b~demo1.adb:118
24446 118       Ada_Main_Program;
24447 (gdb) down
24448 #0  demo1 () at demo1.adb:38
24449 38         Set_Name (Water, "Water");
24450 (gdb)
24451 @end smallexample
24453 @noindent
24454 To examine and modify variables (of a tagged type here):
24456 @smallexample
24457 (gdb) print speed
24458 $1 = (name => "Speed         ", value => -286331154)
24459 (gdb) ptype speed
24460 type = new instr.instrument with record
24461     value: instr.speed;
24462 end record
24463 (gdb) speed.value := 3
24464 $2 = 3
24465 (gdb) print speed
24466 $3 = (name => "Speed         ", value => 3)
24467 (gdb) info local
24468 speed = (name => "Speed         ", value => 3)
24469 fuel = (name => "Fuel          ", value => -286331154)
24470 oil = (name => ' ' <repeats 14 times>, value => -286331154, size => 20,
24471   fill => 42 '*', empty => 46 '.')
24472 water = (name => ' ' <repeats 14 times>, value => -286331154, size => 20,
24473   fill => 42 '*', empty => 46 '.')
24474 time = (name => ' ' <repeats 14 times>, seconds => 0, minutes => 0, hours =>
24476 chrono = (name => ' ' <repeats 14 times>, seconds => 0, minutes => 0,
24477   hours => 0)
24478 db = (access demo1.dash_board.internal) 0x0
24479 (gdb)
24480 @end smallexample
24482 @noindent
24483 And finally letting the program it run to completion:
24485 @smallexample
24486 (gdb) c
24487 Continuing.
24489 Program exited normally.
24490 (gdb)
24491 @end smallexample
24492 @end ifset
24495 @node Performance Considerations
24496 @chapter Performance Considerations
24497 @cindex Performance
24499 @noindent
24500 The GNAT system provides a number of options that allow a trade-off
24501 between
24503 @itemize @bullet
24504 @item
24505 performance of the generated code
24507 @item
24508 speed of compilation
24510 @item
24511 minimization of dependences and recompilation
24513 @item
24514 the degree of run-time checking.
24515 @end itemize
24517 @noindent
24518 The defaults (if no options are selected) aim at improving the speed
24519 of compilation and minimizing dependences, at the expense of performance
24520 of the generated code:
24522 @itemize @bullet
24523 @item
24524 no optimization
24526 @item
24527 no inlining of subprogram calls
24529 @item
24530 all run-time checks enabled except overflow and elaboration checks
24531 @end itemize
24533 @noindent
24534 These options are suitable for most program development purposes. This
24535 chapter describes how you can modify these choices, and also provides
24536 some guidelines on debugging optimized code.
24538 @menu
24539 * Controlling Run-Time Checks::
24540 * Optimization Levels::
24541 * Debugging Optimized Code::
24542 * Inlining of Subprograms::
24543 @ifset vms
24544 * Coverage Analysis::
24545 @end ifset
24546 @end menu
24548 @node Controlling Run-Time Checks
24549 @section Controlling Run-Time Checks
24551 @noindent
24552 By default, GNAT generates all run-time checks, except arithmetic overflow
24553 checking for integer operations and checks for access before elaboration on
24554 subprogram calls. The latter are not required in default mode, because all
24555 necessary checking is done at compile time.
24556 @cindex @option{-gnatp} (@code{gcc})
24557 @cindex @option{-gnato} (@code{gcc})
24558 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
24559 be modified. @xref{Run-Time Checks}.
24561 Our experience is that the default is suitable for most development
24562 purposes.
24564 We treat integer overflow specially because these
24565 are quite expensive and in our experience are not as important as other
24566 run-time checks in the development process. Note that division by zero
24567 is not considered an overflow check, and divide by zero checks are
24568 generated where required by default.
24570 Elaboration checks are off by default, and also not needed by default, since
24571 GNAT uses a static elaboration analysis approach that avoids the need for
24572 run-time checking. This manual contains a full chapter discussing the issue
24573 of elaboration checks, and if the default is not satisfactory for your use,
24574 you should read this chapter.
24576 For validity checks, the minimal checks required by the Ada Reference
24577 Manual (for case statements and assignments to array elements) are on
24578 by default. These can be suppressed by use of the @option{-gnatVn} switch.
24579 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
24580 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
24581 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
24582 are also suppressed entirely if @option{-gnatp} is used.
24584 @cindex Overflow checks
24585 @cindex Checks, overflow
24586 @findex Suppress
24587 @findex Unsuppress
24588 @cindex pragma Suppress
24589 @cindex pragma Unsuppress
24590 Note that the setting of the switches controls the default setting of
24591 the checks. They may be modified using either @code{pragma Suppress} (to
24592 remove checks) or @code{pragma Unsuppress} (to add back suppressed
24593 checks) in the program source.
24595 @node Optimization Levels
24596 @section Optimization Levels
24597 @cindex @code{^-O^/OPTIMIZE^} (@code{gcc})
24599 @noindent
24600 The default is optimization off. This results in the fastest compile
24601 times, but GNAT makes absolutely no attempt to optimize, and the
24602 generated programs are considerably larger and slower than when
24603 optimization is enabled. You can use the
24604 @ifclear vms
24605 @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
24606 @end ifclear
24607 @ifset vms
24608 @code{^-O^/OPTIMIZE^}
24609 @end ifset
24610 on the @code{gcc} command line to control the optimization level:
24612 @table @code
24613 @item -O0
24614 no optimization (the default)
24616 @item -O1
24617 medium level optimization
24619 @item -O2
24620 full optimization
24622 @item -O3
24623 full optimization, and also attempt automatic inlining of small
24624 subprograms within a unit (@pxref{Inlining of Subprograms}).
24625 @end table
24627 Higher optimization levels perform more global transformations on the
24628 program and apply more expensive analysis algorithms in order to generate
24629 faster and more compact code. The price in compilation time, and the
24630 resulting improvement in execution time,
24631 both depend on the particular application and the hardware environment.
24632 You should experiment to find the best level for your application.
24634 Note: Unlike some other compilation systems, @code{gcc} has
24635 been tested extensively at all optimization levels. There are some bugs
24636 which appear only with optimization turned on, but there have also been
24637 bugs which show up only in @emph{unoptimized} code. Selecting a lower
24638 level of optimization does not improve the reliability of the code
24639 generator, which in practice is highly reliable at all optimization
24640 levels.
24642 Note regarding the use of @code{-O3}: The use of this optimization level
24643 is generally discouraged with GNAT, since it often results in larger
24644 executables which run more slowly. See further discussion of this point
24645 in @pxref{Inlining of Subprograms}.
24647 @node Debugging Optimized Code
24648 @section Debugging Optimized Code
24650 @noindent
24651 Since the compiler generates debugging tables for a compilation unit before
24652 it performs optimizations, the optimizing transformations may invalidate some
24653 of the debugging data.  You therefore need to anticipate certain
24654 anomalous situations that may arise while debugging optimized code.  This
24655 section describes the most common cases.
24657 @enumerate
24658 @item
24659 @i{The "hopping Program Counter":}  Repeated 'step' or 'next' commands show the PC
24660 bouncing back and forth in the code.  This may result from any of the following
24661 optimizations:
24663 @itemize @bullet
24664 @item
24665 @i{Common subexpression elimination:} using a single instance of code for a
24666 quantity that the source computes several times.  As a result you
24667 may not be able to stop on what looks like a statement.
24669 @item
24670 @i{Invariant code motion:} moving an expression that does not change within a
24671 loop, to the beginning of the loop.
24673 @item
24674 @i{Instruction scheduling:} moving instructions so as to
24675 overlap loads and stores (typically) with other code, or in
24676 general to move computations of values closer to their uses. Often
24677 this causes you to pass an assignment statement without the assignment
24678 happening and then later bounce back to the statement when the
24679 value is actually needed.  Placing a breakpoint on a line of code
24680 and then stepping over it may, therefore, not always cause all the
24681 expected side-effects.
24682 @end itemize
24684 @item
24685 @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two
24686 identical pieces of code are merged and the program counter suddenly
24687 jumps to a statement that is not supposed to be executed, simply because
24688 it (and the code following) translates to the same thing as the code
24689 that @emph{was} supposed to be executed.  This effect is typically seen in
24690 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
24691 a @code{break} in a C @code{switch} statement.
24693 @item
24694 @i{The "roving variable":} The symptom is an unexpected value in a variable.
24695 There are various reasons for this effect:
24697 @itemize @bullet
24698 @item
24699 In a subprogram prologue, a parameter may not yet have been moved to its
24700 "home".
24702 @item
24703 A variable may be dead, and its register re-used.  This is
24704 probably the most common cause.
24706 @item
24707 As mentioned above, the assignment of a value to a variable may
24708 have been moved.
24710 @item
24711 A variable may be eliminated entirely by value propagation or
24712 other means.  In this case, GCC may incorrectly generate debugging
24713 information for the variable
24714 @end itemize
24716 @noindent
24717 In general, when an unexpected value appears for a local variable or parameter
24718 you should first ascertain if that value was actually computed by
24719 your program, as opposed to being incorrectly reported by the debugger.
24720 Record fields or
24721 array elements in an object designated by an access value
24722 are generally less of a problem, once you have ascertained that the access value
24723 is sensible.
24724 Typically, this means checking variables in the preceding code and in the
24725 calling subprogram to verify that the value observed is explainable from other
24726 values (one must apply the procedure recursively to those
24727 other values); or re-running the code and stopping a little earlier
24728 (perhaps before the call) and stepping to better see how the variable obtained
24729 the value in question; or continuing to step @emph{from} the point of the
24730 strange value to see if code motion had simply moved the variable's
24731 assignments later.
24732 @end enumerate
24734 @node Inlining of Subprograms
24735 @section Inlining of Subprograms
24737 @noindent
24738 A call to a subprogram in the current unit is inlined if all the
24739 following conditions are met:
24741 @itemize @bullet
24742 @item
24743 The optimization level is at least @code{-O1}.
24745 @item
24746 The called subprogram is suitable for inlining: It must be small enough
24747 and not contain nested subprograms or anything else that @code{gcc}
24748 cannot support in inlined subprograms.
24750 @item
24751 The call occurs after the definition of the body of the subprogram.
24753 @item
24754 @cindex pragma Inline
24755 @findex Inline
24756 Either @code{pragma Inline} applies to the subprogram or it is
24757 small and automatic inlining (optimization level @code{-O3}) is
24758 specified.
24759 @end itemize
24761 @noindent
24762 Calls to subprograms in @code{with}'ed units are normally not inlined.
24763 To achieve this level of inlining, the following conditions must all be
24764 true:
24766 @itemize @bullet
24767 @item
24768 The optimization level is at least @code{-O1}.
24770 @item
24771 The called subprogram is suitable for inlining: It must be small enough
24772 and not contain nested subprograms or anything else @code{gcc} cannot
24773 support in inlined subprograms.
24775 @item
24776 The call appears in a body (not in a package spec).
24778 @item
24779 There is a @code{pragma Inline} for the subprogram.
24781 @item
24782 @cindex @option{-gnatn} (@code{gcc})
24783 The @code{^-gnatn^/INLINE^} switch
24784 is used in the @code{gcc} command line
24785 @end itemize
24787 Note that specifying the @option{-gnatn} switch causes additional
24788 compilation dependencies. Consider the following:
24790 @smallexample
24791 @group
24792 @cartouche
24793 @b{package} R @b{is}
24794    @b{procedure} Q;
24795    @b{pragma} Inline (Q);
24796 @b{end} R;
24797 @b{package body} R @b{is}
24798    ...
24799 @b{end} R;
24801 @b{with} R;
24802 @b{procedure} Main @b{is}
24803 @b{begin}
24804    ...
24805    R.Q;
24806 @b{end} Main;
24807 @end cartouche
24808 @end group
24809 @end smallexample
24811 @noindent
24812 With the default behavior (no @option{-gnatn} switch specified), the
24813 compilation of the @code{Main} procedure depends only on its own source,
24814 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
24815 means that editing the body of @code{R} does not require recompiling
24816 @code{Main}.
24818 On the other hand, the call @code{R.Q} is not inlined under these
24819 circumstances. If the @option{-gnatn} switch is present when @code{Main}
24820 is compiled, the call will be inlined if the body of @code{Q} is small
24821 enough, but now @code{Main} depends on the body of @code{R} in
24822 @file{r.adb} as well as on the spec. This means that if this body is edited,
24823 the main program must be recompiled. Note that this extra dependency
24824 occurs whether or not the call is in fact inlined by @code{gcc}.
24826 The use of front end inlining with @option{-gnatN} generates similar
24827 additional dependencies.
24829 @cindex @code{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
24830 Note: The @code{^-fno-inline^/INLINE=SUPPRESS^} switch
24831 can be used to prevent
24832 all inlining. This switch overrides all other conditions and ensures
24833 that no inlining occurs. The extra dependences resulting from
24834 @option{-gnatn} will still be active, even if
24835 this switch is used to suppress the resulting inlining actions.
24837 Note regarding the use of @code{-O3}: There is no difference in inlining
24838 behavior between @code{-O2} and @code{-O3} for subprograms with an explicit
24839 pragma @code{Inline} assuming the use of @option{-gnatn}
24840 or @option{-gnatN} (the switches that activate inlining). If you have used
24841 pragma @code{Inline} in appropriate cases, then it is usually much better
24842 to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which
24843 in this case only has the effect of inlining subprograms you did not
24844 think should be inlined. We often find that the use of @code{-O3} slows
24845 down code by performing excessive inlining, leading to increased instruction
24846 cache pressure from the increased code size. So the bottom line here is
24847 that you should not automatically assume that @code{-O3} is better than
24848 @code{-O2}, and indeed you should use @code{-O3} only if tests show that
24849 it actually improves performance.
24851 @ifset vms
24852 @node Coverage Analysis
24853 @section Coverage Analysis
24855 @noindent
24856 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
24857 the user to determine the distribution of execution time across a program,
24858 @pxref{Profiling} for details of usage.
24859 @end ifset
24861 @include fdl.texi
24862 @c GNU Free Documentation License
24864 @node Index,,GNU Free Documentation License, Top
24865 @unnumbered Index
24867 @printindex cp
24869 @contents
24871 @bye