2003-12-26 Guilhem Lavaux <guilhem@kaffe.org>
[official-gcc.git] / gcc / ada / gnat_ug.texi
blob946da53421107fd8ee9b4f7e3a79ea71c58db07c
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-2003, 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}^(@var{option},@var{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}^[@var{OBJ_DIR}]^ contains the objects and ALI files for
8201 of your Ada compilation units,
8202 whereas ^@var{include-dir}^[@var{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 $ GNAT LIBRARY /[CREATE | SET | DELETE]=directory [/CONFIG=file]
14531 @end smallexample
14533 @node Switches for gnatlbr
14534 @section Switches for @code{gnatlbr}
14536 @noindent
14537 @code{gnatlbr} recognizes the following switches:
14539 @table @code
14540 @item /CREATE=directory
14541 @cindex @code{/CREATE=directory} (@code{gnatlbr})
14542      Create the new run-time library in the specified directory.
14544 @item /SET=directory
14545 @cindex @code{/SET=directory} (@code{gnatlbr})
14546      Make the library in the specified directory the current run-time
14547      library.
14549 @item /DELETE=directory
14550 @cindex @code{/DELETE=directory} (@code{gnatlbr})
14551      Delete the run-time library in the specified directory.
14553 @item /CONFIG=file
14554 @cindex @code{/CONFIG=file} (@code{gnatlbr})
14555      With /CREATE:
14556      Use the configuration pragmas in the specified file when building
14557      the library.
14559      With /SET:
14560      Use the configuration pragmas in the specified file when compiling.
14562 @end table
14564 @node Examples of gnatlbr Usage
14565 @section Example of @code{gnatlbr} Usage
14567 @smallexample
14568 Contents of VAXFLOAT.ADC:
14569 pragma Float_Representation (VAX_Float);
14571 $ GNAT LIBRARY /CREATE=[.VAXFLOAT] /CONFIG=VAXFLOAT.ADC
14573 GNAT LIBRARY rebuilds the run-time library in directory [.VAXFLOAT]
14575 @end smallexample
14576 @end ifset
14578 @node The GNAT Library Browser gnatls
14579 @chapter The GNAT Library Browser @code{gnatls}
14580 @findex gnatls
14581 @cindex Library browser
14583 @noindent
14584 @code{gnatls} is a tool that outputs information about compiled
14585 units. It gives the relationship between objects, unit names and source
14586 files. It can also be used to check the source dependencies of a unit
14587 as well as various characteristics.
14589 @menu
14590 * Running gnatls::
14591 * Switches for gnatls::
14592 * Examples of gnatls Usage::
14593 @end menu
14595 @node Running gnatls
14596 @section Running @code{gnatls}
14598 @noindent
14599 The @code{gnatls} command has the form
14601 @smallexample
14602 $ gnatls switches @var{object_or_ali_file}
14603 @end smallexample
14605 @noindent
14606 The main argument is the list of object or @file{ali} files
14607 (@pxref{The Ada Library Information Files})
14608 for which information is requested.
14610 In normal mode, without additional option, @code{gnatls} produces a
14611 four-column listing. Each line represents information for a specific
14612 object. The first column gives the full path of the object, the second
14613 column gives the name of the principal unit in this object, the third
14614 column gives the status of the source and the fourth column gives the
14615 full path of the source representing this unit.
14616 Here is a simple example of use:
14618 @smallexample
14619 $ gnatls *.o
14620 ^./^[]^demo1.o            demo1            DIF demo1.adb
14621 ^./^[]^demo2.o            demo2             OK demo2.adb
14622 ^./^[]^hello.o            h1                OK hello.adb
14623 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
14624 ^./^[]^instr.o            instr             OK instr.adb
14625 ^./^[]^tef.o              tef              DIF tef.adb
14626 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
14627 ^./^[]^tgef.o             tgef             DIF tgef.adb
14628 @end smallexample
14630 @noindent
14631 The first line can be interpreted as follows: the main unit which is
14632 contained in
14633 object file @file{demo1.o} is demo1, whose main source is in
14634 @file{demo1.adb}. Furthermore, the version of the source used for the
14635 compilation of demo1 has been modified (DIF). Each source file has a status
14636 qualifier which can be:
14638 @table @code
14639 @item OK (unchanged)
14640 The version of the source file used for the compilation of the
14641 specified unit corresponds exactly to the actual source file.
14643 @item MOK (slightly modified)
14644 The version of the source file used for the compilation of the
14645 specified unit differs from the actual source file but not enough to
14646 require recompilation. If you use gnatmake with the qualifier
14647 @code{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
14648 MOK will not be recompiled.
14650 @item DIF (modified)
14651 No version of the source found on the path corresponds to the source
14652 used to build this object.
14654 @item ??? (file not found)
14655 No source file was found for this unit.
14657 @item HID (hidden,  unchanged version not first on PATH)
14658 The version of the source that corresponds exactly to the source used
14659 for compilation has been found on the path but it is hidden by another
14660 version of the same source that has been modified.
14662 @end table
14664 @node Switches for gnatls
14665 @section Switches for @code{gnatls}
14667 @noindent
14668 @code{gnatls} recognizes the following switches:
14670 @table @code
14671 @item ^-a^/ALL_UNITS^
14672 @cindex @code{^-a^/ALL_UNITS^} (@code{gnatls})
14673 Consider all units, including those of the predefined Ada library.
14674 Especially useful with @code{^-d^/DEPENDENCIES^}.
14676 @item ^-d^/DEPENDENCIES^
14677 @cindex @code{^-d^/DEPENDENCIES^} (@code{gnatls})
14678 List sources from which specified units depend on.
14680 @item ^-h^/OUTPUT=OPTIONS^
14681 @cindex @code{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
14682 Output the list of options.
14684 @item ^-o^/OUTPUT=OBJECTS^
14685 @cindex @code{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
14686 Only output information about object files.
14688 @item ^-s^/OUTPUT=SOURCES^
14689 @cindex @code{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
14690 Only output information about source files.
14692 @item ^-u^/OUTPUT=UNITS^
14693 @cindex @code{^-u^/OUTPUT=UNITS^} (@code{gnatls})
14694 Only output information about compilation units.
14696 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
14697 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
14698 @itemx ^-I^/SEARCH=^@var{dir}
14699 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
14700 @itemx -nostdinc
14701 Source path manipulation. Same meaning as the equivalent @code{gnatmake} flags
14702 (see @ref{Switches for gnatmake}).
14704 @item --RTS=@var{rts-path}
14705 @cindex @code{--RTS} (@code{gnatls})
14706 Specifies the default location of the runtime library. Same meaning as the
14707 equivalent @code{gnatmake} flag (see @ref{Switches for gnatmake}).
14709 @item ^-v^/OUTPUT=VERBOSE^
14710 @cindex @code{^-s^/OUTPUT=VERBOSE^} (@code{gnatls})
14711 Verbose mode. Output the complete source and object paths. Do not use
14712 the default column layout but instead use long format giving as much as
14713 information possible on each requested units, including special
14714 characteristics such as:
14716 @table @code
14717 @item  Preelaborable
14718 The unit is preelaborable in the Ada 95 sense.
14720 @item No_Elab_Code
14721 No elaboration code has been produced by the compiler for this unit.
14723 @item Pure
14724 The unit is pure in the Ada 95 sense.
14726 @item Elaborate_Body
14727 The unit contains a pragma Elaborate_Body.
14729 @item Remote_Types
14730 The unit contains a pragma Remote_Types.
14732 @item Shared_Passive
14733 The unit contains a pragma Shared_Passive.
14735 @item Predefined
14736 This unit is part of the predefined environment and cannot be modified
14737 by the user.
14739 @item Remote_Call_Interface
14740 The unit contains a pragma Remote_Call_Interface.
14742 @end table
14744 @end table
14746 @node Examples of gnatls Usage
14747 @section Example of @code{gnatls} Usage
14748 @ifclear vms
14750 @noindent
14751 Example of using the verbose switch. Note how the source and
14752 object paths are affected by the -I switch.
14754 @smallexample
14755 $ gnatls -v -I.. demo1.o
14757 GNATLS 3.10w (970212) Copyright 1999 Free Software Foundation, Inc.
14759 Source Search Path:
14760    <Current_Directory>
14761    ../
14762    /home/comar/local/adainclude/
14764 Object Search Path:
14765    <Current_Directory>
14766    ../
14767    /home/comar/local/lib/gcc-lib/mips-sni-sysv4/2.7.2/adalib/
14769 ./demo1.o
14770    Unit =>
14771      Name   => demo1
14772      Kind   => subprogram body
14773      Flags  => No_Elab_Code
14774      Source => demo1.adb    modified
14775 @end smallexample
14777 @noindent
14778 The following is an example of use of the dependency list.
14779 Note the use of the -s switch
14780 which gives a straight list of source files. This can be useful for
14781 building specialized scripts.
14783 @smallexample
14784 $ gnatls -d demo2.o
14785 ./demo2.o   demo2        OK demo2.adb
14786                          OK gen_list.ads
14787                          OK gen_list.adb
14788                          OK instr.ads
14789                          OK instr-child.ads
14791 $ gnatls -d -s -a demo1.o
14792 demo1.adb
14793 /home/comar/local/adainclude/ada.ads
14794 /home/comar/local/adainclude/a-finali.ads
14795 /home/comar/local/adainclude/a-filico.ads
14796 /home/comar/local/adainclude/a-stream.ads
14797 /home/comar/local/adainclude/a-tags.ads
14798 gen_list.ads
14799 gen_list.adb
14800 /home/comar/local/adainclude/gnat.ads
14801 /home/comar/local/adainclude/g-io.ads
14802 instr.ads
14803 /home/comar/local/adainclude/system.ads
14804 /home/comar/local/adainclude/s-exctab.ads
14805 /home/comar/local/adainclude/s-finimp.ads
14806 /home/comar/local/adainclude/s-finroo.ads
14807 /home/comar/local/adainclude/s-secsta.ads
14808 /home/comar/local/adainclude/s-stalib.ads
14809 /home/comar/local/adainclude/s-stoele.ads
14810 /home/comar/local/adainclude/s-stratt.ads
14811 /home/comar/local/adainclude/s-tasoli.ads
14812 /home/comar/local/adainclude/s-unstyp.ads
14813 /home/comar/local/adainclude/unchconv.ads
14814 @end smallexample
14815 @end ifclear
14817 @ifset vms
14818 @smallexample
14819 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
14821 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
14822 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
14823 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
14824 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
14825 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
14826 demo1.adb
14827 gen_list.ads
14828 gen_list.adb
14829 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
14830 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
14831 instr.ads
14832 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
14833 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
14834 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
14835 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
14836 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
14837 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
14838 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
14839 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
14840 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
14841 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
14842 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
14843 @end smallexample
14844 @end ifset
14846 @ifclear vms
14847 @node GNAT and Libraries
14848 @chapter GNAT and Libraries
14849 @cindex Library, building, installing
14851 @noindent
14852 This chapter addresses some of the issues related to building and using
14853 a library with GNAT. It also shows how the GNAT run-time library can be
14854 recompiled.
14856 @menu
14857 * Creating an Ada Library::
14858 * Installing an Ada Library::
14859 * Using an Ada Library::
14860 * Creating an Ada Library to be Used in a Non-Ada Context::
14861 * Rebuilding the GNAT Run-Time Library::
14862 @end menu
14864 @node Creating an Ada Library
14865 @section Creating an Ada Library
14867 @noindent
14868 In the GNAT environment, a library has two components:
14869 @itemize @bullet
14870 @item
14871 Source files.
14872 @item
14873 Compiled code and Ali files. See @ref{The Ada Library Information Files}.
14874 @end itemize
14876 @noindent
14877 In order to use other packages @ref{The GNAT Compilation Model}
14878 requires a certain number of sources to be available to the compiler.
14879 The minimal set of
14880 sources required includes the specs of all the packages that make up the
14881 visible part of the library as well as all the sources upon which they
14882 depend. The bodies of all visible generic units must also be provided.
14883 @noindent
14884 Although it is not strictly mandatory, it is recommended that all sources
14885 needed to recompile the library be provided, so that the user can make
14886 full use of inter-unit inlining and source-level debugging. This can also
14887 make the situation easier for users that need to upgrade their compilation
14888 toolchain and thus need to recompile the library from sources.
14890 @noindent
14891 The compiled code can be provided in different ways. The simplest way is
14892 to provide directly the set of objects produced by the compiler during
14893 the compilation of the library. It is also possible to group the objects
14894 into an archive using whatever commands are provided by the operating
14895 system. Finally, it is also possible to create a shared library (see
14896 option -shared in the GCC manual).
14898 @noindent
14899 There are various possibilities for compiling the units that make up the
14900 library: for example with a Makefile @ref{Using the GNU make Utility},
14901 or with a conventional script.
14902 For simple libraries, it is also possible to create a
14903 dummy main program which depends upon all the packages that comprise the
14904 interface of the library. This dummy main program can then be given to
14905 gnatmake, in order to build all the necessary objects. Here is an example
14906 of such a dummy program and the generic commands used to build an
14907 archive or a shared library.
14909 @smallexample
14910 @iftex
14911 @leftskip=.7cm
14912 @end iftex
14913 @b{with} My_Lib.Service1;
14914 @b{with} My_Lib.Service2;
14915 @b{with} My_Lib.Service3;
14916 @b{procedure} My_Lib_Dummy @b{is}
14917 @b{begin}
14918    @b{null};
14919 @b{end};
14921 # compiling the library
14922 $ gnatmake -c my_lib_dummy.adb
14924 # we don't need the dummy object itself
14925 $ rm my_lib_dummy.o my_lib_dummy.ali
14927 # create an archive with the remaining objects
14928 $ ar rc libmy_lib.a *.o
14929 # some systems may require "ranlib" to be run as well
14931 # or create a shared library
14932 $ gcc -shared -o libmy_lib.so *.o
14933 # some systems may require the code to have been compiled with -fPIC
14934 @end smallexample
14936 @noindent
14937 When the objects are grouped in an archive or a shared library, the user
14938 needs to specify the desired library at link time, unless a pragma
14939 linker_options has been used in one of the sources:
14940 @smallexample
14941 @b{pragma} Linker_Options ("-lmy_lib");
14942 @end smallexample
14944 @node Installing an Ada Library
14945 @section Installing an Ada Library
14947 @noindent
14948 In the GNAT model, installing a library consists in copying into a specific
14949 location the files that make up this library. It is possible to install
14950 the sources in a different directory from the other files (ALI, objects,
14951 archives) since the source path and the object path can easily be
14952 specified separately.
14954 @noindent
14955 For general purpose libraries, it is possible for the system
14956 administrator to put those libraries in the default compiler paths. To
14957 achieve this, he must specify their location in the configuration files
14958 "ada_source_path" and "ada_object_path" that must be located in the GNAT
14959 installation tree at the same place as the gcc spec file. The location of
14960 the gcc spec file can be determined as follows:
14961 @smallexample
14962 $ gcc -v
14963 @end smallexample
14965 @noindent
14966 The configuration files mentioned above have simple format: each line in them
14967 must contain one unique
14968 directory name. Those names are added to the corresponding path
14969 in their order of appearance in the file. The names can be either absolute
14970 or relative, in the latter case, they are relative to where theses files
14971 are located.
14973 @noindent
14974 "ada_source_path" and "ada_object_path" might actually not be present in a
14975 GNAT installation, in which case, GNAT will look for its run-time library in
14976 the directories "adainclude" for the sources and "adalib" for the
14977 objects and ALI files. When the files exist, the compiler does not
14978 look in "adainclude" and "adalib" at all, and thus the "ada_source_path" file
14979 must contain the location for the GNAT run-time sources (which can simply
14980 be "adainclude"). In the same way, the "ada_object_path" file must contain
14981 the location for the GNAT run-time objects (which can simply
14982 be "adalib").
14984 @noindent
14985 You can also specify a new default path to the runtime library at compilation
14986 time with the switch "--RTS=@var{rts-path}". You can easily choose and change
14987 the runtime you want your program to be compiled with. This switch is
14988 recognized by gcc, gnatmake, gnatbind, gnatls, gnatfind and gnatxref.
14990 @noindent
14991 It is possible to install a library before or after the standard GNAT
14992 library, by reordering the lines in the configuration files. In general, a
14993 library must be installed before the GNAT library if it redefines any part of it.
14995 @node Using an Ada Library
14996 @section Using an Ada Library
14998 @noindent
14999 In order to use a Ada library, you need to make sure that this
15000 library is on both your source and object path
15001 @ref{Search Paths and the Run-Time Library (RTL)}
15002 and @ref{Search Paths for gnatbind}. For
15003 instance, you can use the library "mylib" installed in "/dir/my_lib_src"
15004 and "/dir/my_lib_obj" with the following commands:
15006 @smallexample
15007 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
15008   -largs -lmy_lib
15009 @end smallexample
15011 @noindent
15012 This can be simplified down to the following:
15013 @smallexample
15014 $ gnatmake my_appl
15015 @end smallexample
15016 when the following conditions are met:
15017 @itemize @bullet
15018 @item
15019 "/dir/my_lib_src" has been added by the user to the environment
15020 variable "ADA_INCLUDE_PATH", or by the administrator to the file
15021 "ada_source_path"
15022 @item
15023 "/dir/my_lib_obj" has been added by the user to the environment
15024 variable "ADA_OBJECTS_PATH", or by the administrator to the file
15025 "ada_object_path"
15026 @item
15027 a pragma linker_options, as mentioned in @ref{Creating an Ada Library}
15028 as been added to the sources.
15029 @end itemize
15030 @noindent
15032 @node Creating an Ada Library to be Used in a Non-Ada Context
15033 @section Creating an Ada Library to be Used in a Non-Ada Context
15035 @noindent
15036 The previous sections detailed how to create and install a library that
15037 was usable from an Ada main program. Using this library in a non-Ada
15038 context is not possible, because the elaboration of the library is
15039 automatically done as part of the main program elaboration.
15041 GNAT also provides the ability to build libraries that can be used both
15042 in an Ada and non-Ada context.  This section describes how to build such
15043 a library, and then how to use it from a C program. The method for
15044 interfacing with the library from other languages such as Fortran for
15045 instance remains the same.
15047 @subsection Creating the Library
15049 @itemize @bullet
15050 @item Identify the units representing the interface of the library.
15052 Here is an example of simple library interface:
15054 @smallexample
15055 package Interface is
15057    procedure Do_Something;
15059    procedure Do_Something_Else;
15061 end Interface;
15062 @end smallexample
15064 @item Use @code{pragma Export} or @code{pragma Convention} for the
15065 exported entities.
15067 Our package @code{Interface} is then updated as follow:
15068 @smallexample
15069 package Interface is
15071    procedure Do_Something;
15072    pragma Export (C, Do_Something, "do_something");
15074    procedure Do_Something_Else;
15075    pragma Export (C, Do_Something_Else, "do_something_else");
15077 end Interface;
15078 @end smallexample
15080 @item Compile all the units composing the library.
15082 @item Bind the library objects.
15084 This step is performed by invoking gnatbind with the @code{-L<prefix>}
15085 switch. @code{gnatbind} will then generate the library elaboration
15086 procedure (named @code{<prefix>init}) and the run-time finalization
15087 procedure (named @code{<prefix>final}).
15089 @smallexample
15090 # generate the binder file in Ada
15091 $ gnatbind -Lmylib interface
15093 # generate the binder file in C
15094 $ gnatbind -C -Lmylib interface
15095 @end smallexample
15097 @item Compile the files generated by the binder
15099 @smallexample
15100 $ gcc -c b~interface.adb
15101 @end smallexample
15103 @item Create the library;
15105 The procedure is identical to the procedure explained in
15106 @ref{Creating an Ada Library},
15107 except that @file{b~interface.o} needs to be added to
15108 the list of objects.
15110 @smallexample
15111 # create an archive file
15112 $ ar cr libmylib.a b~interface.o <other object files>
15114 # create a shared library
15115 $ gcc -shared -o libmylib.so b~interface.o <other object files>
15116 @end smallexample
15118 @item Provide a "foreign" view of the library interface;
15120 The example below shows the content of @code{mylib_interface.h} (note
15121 that there is no rule for the naming of this file, any name can be used)
15122 @smallexample
15123 /* the library elaboration procedure */
15124 extern void mylibinit (void);
15126 /* the library finalization procedure */
15127 extern void mylibfinal (void);
15129 /* the interface exported by the library */
15130 extern void do_something (void);
15131 extern void do_something_else (void);
15132 @end smallexample
15133 @end itemize
15135 @subsection Using the Library
15137 @noindent
15138 Libraries built as explained above can be used from any program, provided
15139 that the elaboration procedures (named @code{mylibinit} in the previous
15140 example) are called before the library services are used. Any number of
15141 libraries can be used simultaneously, as long as the elaboration
15142 procedure of each library is called.
15144 Below is an example of C program that uses our @code{mylib} library.
15146 @smallexample
15147 #include "mylib_interface.h"
15150 main (void)
15152    /* First, elaborate the library before using it */
15153    mylibinit ();
15155    /* Main program, using the library exported entities */
15156    do_something ();
15157    do_something_else ();
15159    /* Library finalization at the end of the program */
15160    mylibfinal ();
15161    return 0;
15163 @end smallexample
15165 @noindent
15166 Note that this same library can be used from an equivalent Ada main
15167 program. In addition, if the libraries are installed as detailed in
15168 @ref{Installing an Ada Library}, it is not necessary to invoke the
15169 library elaboration and finalization routines. The binder will ensure
15170 that this is done as part of the main program elaboration and
15171 finalization phases.
15173 @subsection The Finalization Phase
15175 @noindent
15176 Invoking any library finalization procedure generated by @code{gnatbind}
15177 shuts down the Ada run time permanently. Consequently, the finalization
15178 of all Ada libraries must be performed at the end of the program. No
15179 call to these libraries nor the Ada run time should be made past the
15180 finalization phase.
15182 @subsection Restrictions in Libraries
15184 @noindent
15185 The pragmas listed below should be used with caution inside libraries,
15186 as they can create incompatibilities with other Ada libraries:
15187 @itemize @bullet
15188 @item pragma @code{Locking_Policy}
15189 @item pragma @code{Queuing_Policy}
15190 @item pragma @code{Task_Dispatching_Policy}
15191 @item pragma @code{Unreserve_All_Interrupts}
15192 @end itemize
15193 When using a library that contains such pragmas, the user must make sure
15194 that all libraries use the same pragmas with the same values. Otherwise,
15195 a @code{Program_Error} will
15196 be raised during the elaboration of the conflicting
15197 libraries. The usage of these pragmas and its consequences for the user
15198 should therefore be well documented.
15200 Similarly, the traceback in exception occurrences mechanism should be
15201 enabled or disabled in a consistent manner across all libraries.
15202 Otherwise, a Program_Error will be raised during the elaboration of the
15203 conflicting libraries.
15205 If the @code{'Version} and @code{'Body_Version}
15206 attributes are used inside a library, then it is necessary to
15207 perform a @code{gnatbind} step that mentions all ali files in all
15208 libraries, so that version identifiers can be properly computed.
15209 In practice these attributes are rarely used, so this is unlikely
15210 to be a consideration.
15212 @node  Rebuilding the GNAT Run-Time Library
15213 @section Rebuilding the GNAT Run-Time Library
15215 @noindent
15216 It may be useful to recompile the GNAT library in various contexts, the
15217 most important one being the use of partition-wide configuration pragmas
15218 such as Normalize_Scalar. A special Makefile called
15219 @code{Makefile.adalib} is provided to that effect and can be found in
15220 the directory containing the GNAT library. The location of this
15221 directory depends on the way the GNAT environment has been installed and can
15222 be determined by means of the command:
15224 @smallexample
15225 $ gnatls -v
15226 @end smallexample
15228 @noindent
15229 The last entry in the object search path usually contains the
15230 gnat library. This Makefile contains its own documentation and in
15231 particular the set of instructions needed to rebuild a new library and
15232 to use it.
15234 @node Using the GNU make Utility
15235 @chapter Using the GNU @code{make} Utility
15236 @findex make
15238 @noindent
15239 This chapter offers some examples of makefiles that solve specific
15240 problems. It does not explain how to write a makefile (see the GNU make
15241 documentation), nor does it try to replace the @code{gnatmake} utility
15242 (@pxref{The GNAT Make Program gnatmake}).
15244 All the examples in this section are specific to the GNU version of
15245 make. Although @code{make} is a standard utility, and the basic language
15246 is the same, these examples use some advanced features found only in
15247 @code{GNU make}.
15249 @menu
15250 * Using gnatmake in a Makefile::
15251 * Automatically Creating a List of Directories::
15252 * Generating the Command Line Switches::
15253 * Overcoming Command Line Length Limits::
15254 @end menu
15256 @node Using gnatmake in a Makefile
15257 @section Using gnatmake in a Makefile
15258 @findex makefile
15259 @cindex GNU make
15261 @noindent
15262 Complex project organizations can be handled in a very powerful way by
15263 using GNU make combined with gnatmake. For instance, here is a Makefile
15264 which allows you to build each subsystem of a big project into a separate
15265 shared library. Such a makefile allows you to significantly reduce the link
15266 time of very big applications while maintaining full coherence at
15267 each step of the build process.
15269 The list of dependencies are handled automatically by
15270 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
15271 the appropriate directories.
15273 Note that you should also read the example on how to automatically
15274 create the list of directories (@pxref{Automatically Creating a List of Directories})
15275 which might help you in case your project has a lot of
15276 subdirectories.
15278 @smallexample
15279 @iftex
15280 @leftskip=0cm
15281 @font@heightrm=cmr8
15282 @heightrm
15283 @end iftex
15284 ## This Makefile is intended to be used with the following directory
15285 ## configuration:
15286 ##  - The sources are split into a series of csc (computer software components)
15287 ##    Each of these csc is put in its own directory.
15288 ##    Their name are referenced by the directory names.
15289 ##    They will be compiled into shared library (although this would also work
15290 ##    with static libraries
15291 ##  - The main program (and possibly other packages that do not belong to any
15292 ##    csc is put in the top level directory (where the Makefile is).
15293 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
15294 ##                    \_ second_csc (sources) __ lib (will contain the library)
15295 ##                    \_ ...
15296 ## Although this Makefile is build for shared library, it is easy to modify
15297 ## to build partial link objects instead (modify the lines with -shared and
15298 ## gnatlink below)
15300 ## With this makefile, you can change any file in the system or add any new
15301 ## file, and everything will be recompiled correctly (only the relevant shared
15302 ## objects will be recompiled, and the main program will be re-linked).
15304 # The list of computer software component for your project. This might be
15305 # generated automatically.
15306 CSC_LIST=aa bb cc
15308 # Name of the main program (no extension)
15309 MAIN=main
15311 # If we need to build objects with -fPIC, uncomment the following line
15312 #NEED_FPIC=-fPIC
15314 # The following variable should give the directory containing libgnat.so
15315 # You can get this directory through 'gnatls -v'. This is usually the last
15316 # directory in the Object_Path.
15317 GLIB=...
15319 # The directories for the libraries
15320 # (This macro expands the list of CSC to the list of shared libraries, you
15321 # could simply use the expanded form :
15322 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
15323 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
15325 $@{MAIN@}: objects $@{LIB_DIR@}
15326     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
15327     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
15329 objects::
15330     # recompile the sources
15331     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
15333 # Note: In a future version of GNAT, the following commands will be simplified
15334 # by a new tool, gnatmlib
15335 $@{LIB_DIR@}:
15336     mkdir -p $@{dir $@@ @}
15337     cd $@{dir $@@ @}; gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
15338     cd $@{dir $@@ @}; cp -f ../*.ali .
15340 # The dependencies for the modules
15341 # Note that we have to force the expansion of *.o, since in some cases make won't
15342 # be able to do it itself.
15343 aa/lib/libaa.so: $@{wildcard aa/*.o@}
15344 bb/lib/libbb.so: $@{wildcard bb/*.o@}
15345 cc/lib/libcc.so: $@{wildcard cc/*.o@}
15347 # Make sure all of the shared libraries are in the path before starting the
15348 # program
15349 run::
15350     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
15352 clean::
15353     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
15354     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
15355     $@{RM@} $@{CSC_LIST:%=%/*.o@}
15356     $@{RM@} *.o *.ali $@{MAIN@}
15357 @end smallexample
15359 @node Automatically Creating a List of Directories
15360 @section Automatically Creating a List of Directories
15362 @noindent
15363 In most makefiles, you will have to specify a list of directories, and
15364 store it in a variable. For small projects, it is often easier to
15365 specify each of them by hand, since you then have full control over what
15366 is the proper order for these directories, which ones should be
15367 included...
15369 However, in larger projects, which might involve hundreds of
15370 subdirectories, it might be more convenient to generate this list
15371 automatically.
15373 The example below presents two methods. The first one, although less
15374 general, gives you more control over the list. It involves wildcard
15375 characters, that are automatically expanded by @code{make}. Its
15376 shortcoming is that you need to explicitly specify some of the
15377 organization of your project, such as for instance the directory tree
15378 depth, whether some directories are found in a separate tree,...
15380 The second method is the most general one. It requires an external
15381 program, called @code{find}, which is standard on all Unix systems. All
15382 the directories found under a given root directory will be added to the
15383 list.
15385 @smallexample
15386 @iftex
15387 @leftskip=0cm
15388 @font@heightrm=cmr8
15389 @heightrm
15390 @end iftex
15391 # The examples below are based on the following directory hierarchy:
15392 # All the directories can contain any number of files
15393 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
15394 #                       ->  ab
15395 #                       ->  ac
15396 #                ->  b  ->  ba  ->  baa
15397 #                       ->  bb
15398 #                       ->  bc
15399 # This Makefile creates a variable called DIRS, that can be reused any time
15400 # you need this list (see the other examples in this section)
15402 # The root of your project's directory hierarchy
15403 ROOT_DIRECTORY=.
15405 ####
15406 # First method: specify explicitly the list of directories
15407 # This allows you to specify any subset of all the directories you need.
15408 ####
15410 DIRS := a/aa/ a/ab/ b/ba/
15412 ####
15413 # Second method: use wildcards
15414 # Note that the argument(s) to wildcard below should end with a '/'.
15415 # Since wildcards also return file names, we have to filter them out
15416 # to avoid duplicate directory names.
15417 # We thus use make's @code{dir} and @code{sort} functions.
15418 # It sets DIRs to the following value (note that the directories aaa and baa
15419 # are not given, unless you change the arguments to wildcard).
15420 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
15421 ####
15423 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/ $@{ROOT_DIRECTORY@}/*/*/@}@}@}
15425 ####
15426 # Third method: use an external program
15427 # This command is much faster if run on local disks, avoiding NFS slowdowns.
15428 # This is the most complete command: it sets DIRs to the following value:
15429 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
15430 ####
15432 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
15434 @end smallexample
15436 @node Generating the Command Line Switches
15437 @section Generating the Command Line Switches
15439 @noindent
15440 Once you have created the list of directories as explained in the
15441 previous section (@pxref{Automatically Creating a List of Directories}),
15442 you can easily generate the command line arguments to pass to gnatmake.
15444 For the sake of completeness, this example assumes that the source path
15445 is not the same as the object path, and that you have two separate lists
15446 of directories.
15448 @smallexample
15449 # see "Automatically creating a list of directories" to create
15450 # these variables
15451 SOURCE_DIRS=
15452 OBJECT_DIRS=
15454 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
15455 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
15457 all:
15458         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
15459 @end smallexample
15461 @node Overcoming Command Line Length Limits
15462 @section Overcoming Command Line Length Limits
15464 @noindent
15465 One problem that might be encountered on big projects is that many
15466 operating systems limit the length of the command line. It is thus hard to give
15467 gnatmake the list of source and object directories.
15469 This example shows how you can set up environment variables, which will
15470 make @code{gnatmake} behave exactly as if the directories had been
15471 specified on the command line, but have a much higher length limit (or
15472 even none on most systems).
15474 It assumes that you have created a list of directories in your Makefile,
15475 using one of the methods presented in
15476 @ref{Automatically Creating a List of Directories}.
15477 For the sake of completeness, we assume that the object
15478 path (where the ALI files are found) is different from the sources patch.
15480 Note a small trick in the Makefile below: for efficiency reasons, we
15481 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
15482 expanded immediately by @code{make}. This way we overcome the standard
15483 make behavior which is to expand the variables only when they are
15484 actually used.
15486 @smallexample
15487 @iftex
15488 @leftskip=0cm
15489 @font@heightrm=cmr8
15490 @heightrm
15491 @end iftex
15492 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECT_PATH.
15493 # This is the same thing as putting the -I arguments on the command line.
15494 # (the equivalent of using -aI on the command line would be to define
15495 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECT_PATH).
15496 # You can of course have different values for these variables.
15498 # Note also that we need to keep the previous values of these variables, since
15499 # they might have been set before running 'make' to specify where the GNAT
15500 # library is installed.
15502 # see "Automatically creating a list of directories" to create these
15503 # variables
15504 SOURCE_DIRS=
15505 OBJECT_DIRS=
15507 empty:=
15508 space:=$@{empty@} $@{empty@}
15509 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
15510 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
15511 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
15512 ADA_OBJECT_PATH += $@{OBJECT_LIST@}
15513 export ADA_INCLUDE_PATH
15514 export ADA_OBJECT_PATH
15516 all:
15517         gnatmake main_unit
15518 @end smallexample
15520 @ifclear vxworks
15521 @node Finding Memory Problems with gnatmem
15522 @chapter Finding Memory Problems with @code{gnatmem}
15523 @findex gnatmem
15525 @noindent
15526 @code{gnatmem}, is a tool that monitors dynamic allocation and
15527 deallocation activity in a program, and displays information about
15528 incorrect deallocations and possible sources of memory leaks. Gnatmem
15529 provides three type of information:
15530 @itemize @bullet
15531 @item
15532 General information concerning memory management, such as the total
15533 number of allocations and deallocations, the amount of allocated
15534 memory and the high water mark, i.e. the largest amount of allocated
15535 memory in the course of program execution.
15537 @item
15538 Backtraces for all incorrect deallocations, that is to say deallocations
15539 which do not correspond to a valid allocation.
15541 @item
15542 Information on each allocation that is potentially the origin of a memory
15543 leak.
15544 @end itemize
15546 The @code{gnatmem} command has two modes. It can be used with @code{gdb}
15547 or with instrumented allocation and deallocation routines. The later
15548 mode is called the @code{GMEM} mode. Both modes produce the very same
15549 output.
15551 @menu
15552 * Running gnatmem (GDB Mode)::
15553 * Running gnatmem (GMEM Mode)::
15554 * Switches for gnatmem::
15555 * Examples of gnatmem Usage::
15556 * GDB and GMEM Modes::
15557 * Implementation Note::
15558 @end menu
15560 @node Running gnatmem (GDB Mode)
15561 @section Running @code{gnatmem} (GDB Mode)
15563 @noindent
15564 The @code{gnatmem} command has the form
15566 @smallexample
15567    $ gnatmem [-q] [n] [-o file] user_program [program_arg]*
15569    $ gnatmem [-q] [n] -i file
15570 @end smallexample
15572 @noindent
15573 Gnatmem must be supplied with the executable to examine, followed by its
15574 run-time inputs. For example, if a program is executed with the command:
15575 @smallexample
15576 $ my_program arg1 arg2
15577 @end smallexample
15578 then it can be run under @code{gnatmem} control using the command:
15579 @smallexample
15580 $ gnatmem my_program arg1 arg2
15581 @end smallexample
15583 The program is transparently executed under the control of the debugger
15584 @ref{The GNAT Debugger GDB}. This does not affect the behavior
15585 of the program, except for sensitive real-time programs. When the program
15586 has completed execution, @code{gnatmem} outputs a report containing general
15587 allocation/deallocation information and potential memory leak.
15588 For better results, the user program should be compiled with
15589 debugging options @ref{Switches for gcc}.
15591 Here is a simple example of use:
15593 *************** debut cc
15594 @smallexample
15595 $ gnatmem test_gm
15597 Global information
15598 ------------------
15599    Total number of allocations        :  45
15600    Total number of deallocations      :   6
15601    Final Water Mark (non freed mem)   :  11.29 Kilobytes
15602    High Water Mark                    :  11.40 Kilobytes
15607 Allocation Root # 2
15608 -------------------
15609  Number of non freed allocations    :  11
15610  Final Water Mark (non freed mem)   :   1.16 Kilobytes
15611  High Water Mark                    :   1.27 Kilobytes
15612  Backtrace                          :
15613    test_gm.adb:23 test_gm.alloc
15617 @end smallexample
15619 The first block of output give general information. In this case, the
15620 Ada construct "@b{new}" was executed 45 times, and only 6 calls to an
15621 unchecked deallocation routine occurred.
15623 Subsequent paragraphs display  information on all allocation roots.
15624 An allocation root is a specific point in the execution of the program
15625 that generates some dynamic allocation, such as a "@b{new}" construct. This
15626 root is represented by an execution backtrace (or subprogram call
15627 stack). By default the backtrace depth for allocations roots is 1, so
15628 that a root corresponds exactly to a source location. The backtrace can
15629 be made deeper, to make the root more specific.
15631 @node Running gnatmem (GMEM Mode)
15632 @section Running @code{gnatmem} (GMEM Mode)
15633 @cindex @code{GMEM} (@code{gnatmem})
15635 @noindent
15636 The @code{gnatmem} command has the form
15638 @smallexample
15639    $ gnatmem [-q] [n] -i gmem.out user_program [program_arg]*
15640 @end smallexample
15642 The program must have been linked with the instrumented version of the
15643 allocation and deallocation routines. This is done with linking with the
15644 @file{libgmem.a} library. For better results, the user program should be
15645 compiled with debugging options @ref{Switches for gcc}. For example to
15646 build @file{my_program}:
15648 @smallexample
15649 $ gnatmake -g my_program -largs -lgmem
15650 @end smallexample
15652 @noindent
15653 When running @file{my_program} the file @file{gmem.out} is produced. This file
15654 contains information about all allocations and deallocations done by the
15655 program. It is produced by the instrumented allocations and
15656 deallocations routines and will be used by @code{gnatmem}.
15658 @noindent
15659 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
15660 examine followed by its run-time inputs. For example, if a program is
15661 executed with the command:
15662 @smallexample
15663 $ my_program arg1 arg2
15664 @end smallexample
15665 then @file{gmem.out} can be analysed by @code{gnatmem} using the command:
15666 @smallexample
15667 $ gnatmem -i gmem.out my_program arg1 arg2
15668 @end smallexample
15670 @node Switches for gnatmem
15671 @section Switches for @code{gnatmem}
15673 @noindent
15674 @code{gnatmem} recognizes the following switches:
15676 @table @code
15678 @item @code{-q}
15679 @cindex @code{-q} (@code{gnatmem})
15680 Quiet. Gives the minimum output needed to identify the origin of the
15681 memory leaks. Omit statistical information.
15683 @item @code{n}
15684 @cindex @code{n} (@code{gnatmem})
15685 N is an integer literal (usually between 1 and 10) which controls the
15686 depth of the backtraces defining allocation root. The default value for
15687 N is 1. The deeper the backtrace, the more precise the localization of
15688 the root. Note that the total number of roots can depend on this
15689 parameter.
15691 @item @code{-o file}
15692 @cindex @code{-o} (@code{gnatmem})
15693 Direct the gdb output to the specified file. The @code{gdb} script used
15694 to generate this output is also saved in the file @file{gnatmem.tmp}.
15696 @item @code{-i file}
15697 @cindex @code{-i} (@code{gnatmem})
15698 Do the @code{gnatmem} processing starting from @file{file} which has
15699 been generated by a previous call to @code{gnatmem} with the -o
15700 switch or @file{gmem.out} produced by @code{GMEM} mode. This is useful
15701 for post mortem processing.
15703 @end table
15705 @node Examples of gnatmem Usage
15706 @section Example of @code{gnatmem} Usage
15708 @noindent
15709 This section is based on the @code{GDB} mode of @code{gnatmem}. The same
15710 results can be achieved using @code{GMEM} mode. See section
15711 @ref{Running gnatmem (GMEM Mode)}.
15713 @noindent
15714 The first example shows the use of @code{gnatmem}
15715 on a simple leaking program.
15716 Suppose that we have the following Ada program:
15718 @smallexample
15719 @group
15720 @cartouche
15721 @b{with} Unchecked_Deallocation;
15722 @b{procedure} Test_Gm @b{is}
15724    @b{type} T @b{is array} (1..1000) @b{of} Integer;
15725    @b{type} Ptr @b{is access} T;
15726    @b{procedure} Free @b{is new} Unchecked_Deallocation (T, Ptr);
15727    A : Ptr;
15729    @b{procedure} My_Alloc @b{is}
15730    @b{begin}
15731       A := @b{new} T;
15732    @b{end} My_Alloc;
15734    @b{procedure} My_DeAlloc @b{is}
15735       B : Ptr := A;
15736    @b{begin}
15737       Free (B);
15738    @b{end} My_DeAlloc;
15740 @b{begin}
15741    My_Alloc;
15742    @b{for} I @b{in} 1 .. 5 @b{loop}
15743       @b{for} J @b{in} I .. 5 @b{loop}
15744          My_Alloc;
15745       @b{end loop};
15746       My_Dealloc;
15747    @b{end loop};
15748 @b{end};
15749 @end cartouche
15750 @end group
15751 @end smallexample
15753 @noindent
15754 The program needs to be compiled with debugging option:
15756 @smallexample
15757 $ gnatmake -g test_gm
15758 @end smallexample
15760 @code{gnatmem} is invoked simply with
15761 @smallexample
15762 $ gnatmem test_gm
15763 @end smallexample
15765 @noindent
15766 which produces the following output:
15768 @smallexample
15769 Global information
15770 ------------------
15771    Total number of allocations        :  18
15772    Total number of deallocations      :   5
15773    Final Water Mark (non freed mem)   :  53.00 Kilobytes
15774    High Water Mark                    :  56.90 Kilobytes
15776 Allocation Root # 1
15777 -------------------
15778  Number of non freed allocations    :  11
15779  Final Water Mark (non freed mem)   :  42.97 Kilobytes
15780  High Water Mark                    :  46.88 Kilobytes
15781  Backtrace                          :
15782    test_gm.adb:11 test_gm.my_alloc
15784 Allocation Root # 2
15785 -------------------
15786  Number of non freed allocations    :   1
15787  Final Water Mark (non freed mem)   :  10.02 Kilobytes
15788  High Water Mark                    :  10.02 Kilobytes
15789  Backtrace                          :
15790    s-secsta.adb:81 system.secondary_stack.ss_init
15792 Allocation Root # 3
15793 -------------------
15794  Number of non freed allocations    :   1
15795  Final Water Mark (non freed mem)   :  12 Bytes
15796  High Water Mark                    :  12 Bytes
15797  Backtrace                          :
15798    s-secsta.adb:181 system.secondary_stack.ss_init
15799 @end smallexample
15801 @noindent
15802 Note that the GNAT run time contains itself a certain number of
15803 allocations that have no  corresponding deallocation,
15804 as shown here for root #2 and root
15805 #1. This is a normal behavior when the number of non freed allocations
15806 is one, it locates dynamic data structures that the run time needs for
15807 the complete lifetime of the program. Note also that there is only one
15808 allocation root in the user program with a single line back trace:
15809 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
15810 program shows that 'My_Alloc' is called at 2 different points in the
15811 source (line 21 and line 24). If those two allocation roots need to be
15812 distinguished, the backtrace depth parameter can be used:
15814 @smallexample
15815 $ gnatmem 3 test_gm
15816 @end smallexample
15818 @noindent
15819 which will give the following output:
15821 @smallexample
15822 Global information
15823 ------------------
15824    Total number of allocations        :  18
15825    Total number of deallocations      :   5
15826    Final Water Mark (non freed mem)   :  53.00 Kilobytes
15827    High Water Mark                    :  56.90 Kilobytes
15829 Allocation Root # 1
15830 -------------------
15831  Number of non freed allocations    :  10
15832  Final Water Mark (non freed mem)   :  39.06 Kilobytes
15833  High Water Mark                    :  42.97 Kilobytes
15834  Backtrace                          :
15835    test_gm.adb:11 test_gm.my_alloc
15836    test_gm.adb:24 test_gm
15837    b_test_gm.c:52 main
15839 Allocation Root # 2
15840 -------------------
15841  Number of non freed allocations    :   1
15842  Final Water Mark (non freed mem)   :  10.02 Kilobytes
15843  High Water Mark                    :  10.02 Kilobytes
15844  Backtrace                          :
15845    s-secsta.adb:81  system.secondary_stack.ss_init
15846    s-secsta.adb:283 <system__secondary_stack___elabb>
15847    b_test_gm.c:33   adainit
15849 Allocation Root # 3
15850 -------------------
15851  Number of non freed allocations    :   1
15852  Final Water Mark (non freed mem)   :   3.91 Kilobytes
15853  High Water Mark                    :   3.91 Kilobytes
15854  Backtrace                          :
15855    test_gm.adb:11 test_gm.my_alloc
15856    test_gm.adb:21 test_gm
15857    b_test_gm.c:52 main
15859 Allocation Root # 4
15860 -------------------
15861  Number of non freed allocations    :   1
15862  Final Water Mark (non freed mem)   :  12 Bytes
15863  High Water Mark                    :  12 Bytes
15864  Backtrace                          :
15865    s-secsta.adb:181 system.secondary_stack.ss_init
15866    s-secsta.adb:283 <system__secondary_stack___elabb>
15867    b_test_gm.c:33   adainit
15868 @end smallexample
15870 @noindent
15871 The allocation root #1 of the first example has been split in 2 roots #1
15872 and #3 thanks to the more precise associated backtrace.
15874 @node GDB and GMEM Modes
15875 @section GDB and GMEM Modes
15877 @noindent
15878 The main advantage of the @code{GMEM} mode is that it is a lot faster than the
15879 @code{GDB} mode where the application must be monitored by a @code{GDB} script.
15880 But the @code{GMEM} mode is available only for DEC Unix, Linux x86,
15881 Solaris (sparc and x86) and Windows 95/98/NT/2000 (x86).
15883 @noindent
15884 The main advantage of the @code{GDB} mode is that it is available on all
15885 supported platforms. But it can be very slow if the application does a
15886 lot of allocations and deallocations.
15888 @node Implementation Note
15889 @section Implementation Note
15891 @menu
15892 * gnatmem Using GDB Mode::
15893 * gnatmem Using GMEM Mode::
15894 @end menu
15896 @node gnatmem Using GDB Mode
15897 @subsection @code{gnatmem} Using @code{GDB} Mode
15899 @noindent
15900 @code{gnatmem} executes the user program under the control of @code{GDB} using
15901 a script that sets breakpoints and gathers information on each dynamic
15902 allocation and deallocation. The output of the script is then analyzed
15903 by @code{gnatmem}
15904 in order to locate memory leaks and their origin in the
15905 program. Gnatmem works by recording each address returned by the
15906 allocation procedure (@code{__gnat_malloc})
15907 along with the backtrace at the
15908 allocation point. On each deallocation, the deallocated address is
15909 matched with the corresponding allocation. At the end of the processing,
15910 the unmatched allocations are considered potential leaks. All the
15911 allocations associated with the same backtrace are grouped together and
15912 form an allocation root. The allocation roots are then sorted so that
15913 those with the biggest number of unmatched allocation are printed
15914 first. A delicate aspect of this technique is to distinguish between the
15915 data produced by the user program and the data produced by the gdb
15916 script. Currently, on systems that allow probing the terminal, the gdb
15917 command "tty" is used to force the program output to be redirected to the
15918 current terminal while the @code{gdb} output is directed to a file or to a
15919 pipe in order to be processed subsequently by @code{gnatmem}.
15921 @node gnatmem Using GMEM Mode
15922 @subsection @code{gnatmem} Using @code{GMEM} Mode
15924 @noindent
15925 This mode use the same algorithm to detect memory leak as the @code{GDB}
15926 mode of @code{gnatmem}, the only difference is in the way data are
15927 gathered. In @code{GMEM} mode the program is linked with instrumented
15928 version of @code{__gnat_malloc} and @code{__gnat_free}
15929 routines. Information needed to find memory leak are recorded by these
15930 routines in file @file{gmem.out}. This mode also require that the stack
15931 traceback be available, this is only implemented on some platforms
15932 @ref{GDB and GMEM Modes}.
15934 @end ifclear
15935 @end ifclear
15937 @node Finding Memory Problems with GNAT Debug Pool
15938 @chapter Finding Memory Problems with GNAT Debug Pool
15939 @findex Debug Pool
15940 @cindex storage, pool, memory corruption
15942 @noindent
15943 The use of unchecked deallocation and unchecked conversion can easily
15944 lead to incorrect memory references. The problems generated by such
15945 references are usually difficult to tackle because the symptoms can be
15946 very remote from the origin of the problem. In such cases, it is
15947 very helpful to detect the problem as early as possible. This is the
15948 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
15950 @noindent
15951 In order to use the GNAT specific debugging pool, the user must
15952 associate a debug pool object with each of the access types that may be
15953 related to suspected memory problems. See Ada Reference Manual
15954 13.11.
15955 @smallexample
15956 @b{type} Ptr @b{is} @b{access} Some_Type;
15957 Pool : GNAT.Debug_Pools.Debug_Pool;
15958 @b{for} Ptr'Storage_Pool @b{use} Pool;
15959 @end smallexample
15961 @code{GNAT.Debug_Pools} is derived from of a GNAT-specific kind of
15962 pool: the Checked_Pool. Such pools, like standard Ada storage pools,
15963 allow the user to redefine allocation and deallocation strategies. They
15964 also provide a checkpoint for each dereference, through the use of
15965 the primitive operation @code{Dereference} which is implicitly called at
15966 each dereference of an access value.
15968 Once an access type has been associated with a debug pool, operations on
15969 values of the type may raise four distinct exceptions,
15970 which correspond to four potential kinds of memory corruption:
15971 @itemize @bullet
15972 @item
15973 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
15974 @item
15975 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
15976 @item
15977 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
15978 @item
15979 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
15980 @end itemize
15982 @noindent
15983 For types associated with a Debug_Pool, dynamic allocation is performed using
15984 the standard
15985 GNAT allocation routine. References to all allocated chunks of memory
15986 are kept in an internal dictionary. The deallocation strategy consists
15987 in not releasing the memory to the underlying system but rather to fill
15988 it with a memory pattern easily recognizable during debugging sessions:
15989 The memory pattern is the old IBM hexadecimal convention: 16#DEADBEEF#.
15990 Upon each dereference, a check is made that the access value denotes a properly
15991 allocated memory location. Here is a complete example of use of
15992 @code{Debug_Pools}, that includes typical instances of  memory corruption:
15993 @smallexample
15994 @iftex
15995 @leftskip=0cm
15996 @end iftex
15997 @b{with} Gnat.Io; @b{use} Gnat.Io;
15998 @b{with} Unchecked_Deallocation;
15999 @b{with} Unchecked_Conversion;
16000 @b{with} GNAT.Debug_Pools;
16001 @b{with} System.Storage_Elements;
16002 @b{with} Ada.Exceptions; @b{use} Ada.Exceptions;
16003 @b{procedure} Debug_Pool_Test @b{is}
16005    @b{type} T @b{is} @b{access} Integer;
16006    @b{type} U @b{is} @b{access} @b{all} T;
16008    P : GNAT.Debug_Pools.Debug_Pool;
16009    @b{for} T'Storage_Pool @b{use} P;
16011    @b{procedure} Free @b{is} @b{new} Unchecked_Deallocation (Integer, T);
16012    @b{function} UC @b{is} @b{new} Unchecked_Conversion (U, T);
16013    A, B : @b{aliased} T;
16015    @b{procedure} Info @b{is} @b{new} GNAT.Debug_Pools.Print_Info(Put_Line);
16017 @b{begin}
16018    Info (P);
16019    A := @b{new} Integer;
16020    B := @b{new} Integer;
16021    B := A;
16022    Info (P);
16023    Free (A);
16024    @b{begin}
16025       Put_Line (Integer'Image(B.@b{all}));
16026    @b{exception}
16027       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16028    @b{end};
16029    @b{begin}
16030       Free (B);
16031    @b{exception}
16032       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16033    @b{end};
16034    B := UC(A'Access);
16035    @b{begin}
16036       Put_Line (Integer'Image(B.@b{all}));
16037    @b{exception}
16038       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16039    @b{end};
16040    @b{begin}
16041       Free (B);
16042    @b{exception}
16043       @b{when} E : @b{others} => Put_Line ("raised: " & Exception_Name (E));
16044    @b{end};
16045    Info (P);
16046 @b{end} Debug_Pool_Test;
16047 @end smallexample
16048 @noindent
16049 The debug pool mechanism provides the following precise diagnostics on the
16050 execution of this erroneous program:
16051 @smallexample
16052 Debug Pool info:
16053   Total allocated bytes :  0
16054   Total deallocated bytes :  0
16055   Current Water Mark:  0
16056   High Water Mark:  0
16058 Debug Pool info:
16059   Total allocated bytes :  8
16060   Total deallocated bytes :  0
16061   Current Water Mark:  8
16062   High Water Mark:  8
16064 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
16065 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
16066 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
16067 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
16068 Debug Pool info:
16069   Total allocated bytes :  8
16070   Total deallocated bytes :  4
16071   Current Water Mark:  4
16072   High Water Mark:  8
16074 @end smallexample
16076 @node Creating Sample Bodies Using gnatstub
16077 @chapter Creating Sample Bodies Using @code{gnatstub}
16078 @findex gnatstub
16080 @noindent
16081 @code{gnatstub} creates body stubs, that is, empty but compilable bodies
16082 for library unit declarations.
16084 To create a body stub, @code{gnatstub} has to compile the library
16085 unit declaration. Therefore, bodies can be created only for legal
16086 library units. Moreover, if a library unit depends semantically upon
16087 units located outside the current directory, you have to provide
16088 the source search path when calling @code{gnatstub}, see the description
16089 of @code{gnatstub} switches below.
16091 @menu
16092 * Running gnatstub::
16093 * Switches for gnatstub::
16094 @end menu
16096 @node Running gnatstub
16097 @section Running @code{gnatstub}
16099 @noindent
16100 @code{gnatstub} has the command-line interface of the form
16102 @smallexample
16103 $ gnatstub [switches] filename [directory]
16104 @end smallexample
16106 @noindent
16107 where
16108 @table @code
16109 @item filename
16110 is the name of the source file that contains a library unit declaration
16111 for which a body must be created. This name should follow the GNAT file name
16112 conventions. No crunching is allowed for this file name. The file
16113 name may contain the path information.
16115 @item directory
16116 indicates the directory to place a body stub (default is the
16117 current directory)
16119 @item switches
16120 is an optional sequence of switches as described in the next section
16121 @end table
16123 @node Switches for gnatstub
16124 @section Switches for @code{gnatstub}
16126 @table @code
16128 @item ^-f^/FULL^
16129 If the destination directory already contains a file with a name of the body file
16130 for the argument spec file, replace it with the generated body stub.
16132 @item ^-hs^/HEADER=SPEC^
16133 Put the comment header (i.e. all the comments preceding the
16134 compilation unit) from the source of the library unit declaration
16135 into the body stub.
16137 @item ^-hg^/HEADER=GENERAL^
16138 Put a sample comment header into the body stub.
16140 @item -IDIR
16141 @itemx ^-I-^/NOCURRENT_DIRECTORY^
16142 These switches have the same meaning as in calls to gcc.
16143 They define the source search path in the call to gcc issued
16144 by @code{gnatstub} to compile an argument source file.
16146 @item ^-i^/INDENTATION=^@var{n}
16147 (@var{n} is a decimal natural number). Set the indentation level in the
16148 generated body sample to n, '^-i0^/INDENTATION=0^' means "no indentation",
16149 the default indentation is 3.
16151 @item ^-k^/TREE_FILE=SAVE^
16152 Do not remove the tree file (i.e. the snapshot of the compiler internal
16153 structures used by @code{gnatstub}) after creating the body stub.
16155 @item ^-l^/LINE_LENGTH=^@var{n}
16156 (@var{n} is a decimal positive number) Set the maximum line length in the
16157 body stub to n, the default is 78.
16159 @item ^-q^/QUIET^
16160 Quiet mode: do not generate a confirmation when a body is
16161 successfully created or a message when a body is not required for an
16162 argument unit.
16164 @item ^-r^/TREE_FILE=REUSE^
16165 Reuse the tree file (if it exists) instead of creating it: instead of
16166 creating the tree file for the library unit declaration, gnatstub
16167 tries to find it in the current directory and use it for creating
16168 a body. If the tree file is not found, no body is created. @code{^-r^/REUSE^}
16169 also implies @code{^-k^/SAVE^}, whether or not
16170 @code{^-k^/SAVE^} is set explicitly.
16172 @item ^-t^/TREE_FILE=OVERWRITE^
16173 Overwrite the existing tree file: if the current directory already
16174 contains the file which, according to the GNAT file name rules should
16175 be considered as a tree file for the argument source file, gnatstub
16176 will refuse to create the tree file needed to create a body sampler,
16177 unless @code{-t} option is set
16179 @item ^-v^/VERBOSE^
16180 Verbose mode: generate version information.
16182 @end table
16184 @node Reducing the Size of Ada Executables with gnatelim
16185 @chapter Reducing the Size of Ada Executables with @code{gnatelim}
16186 @findex gnatelim
16188 @menu
16189 * About gnatelim::
16190 * Eliminate Pragma::
16191 * Tree Files::
16192 * Preparing Tree and Bind Files for gnatelim::
16193 * Running gnatelim::
16194 * Correcting the List of Eliminate Pragmas::
16195 * Making Your Executables Smaller::
16196 * Summary of the gnatelim Usage Cycle::
16197 @end menu
16199 @node About gnatelim
16200 @section About @code{gnatelim}
16202 @noindent
16203 When a program shares a set of Ada
16204 packages with other programs, it may happen that this program uses
16205 only a fraction of the subprograms defined in these packages. The code
16206 created for these unused subprograms increases the size of the executable.
16208 @code{gnatelim} tracks unused subprograms in an Ada program and
16209 outputs a list of GNAT-specific @code{Eliminate} pragmas (see next
16210 section) marking all the subprograms that are declared but never called.
16211 By placing the list of @code{Eliminate} pragmas in the GNAT configuration
16212 file @file{gnat.adc} and recompiling your program, you may decrease the
16213 size of its executable, because the compiler will not generate the code
16214 for 'eliminated' subprograms.
16216 @code{gnatelim} needs as its input data a set of tree files
16217 (see @ref{Tree Files}) representing all the components of a program to
16218 process and a bind file for a main subprogram (see
16219 @ref{Preparing Tree and Bind Files for gnatelim}).
16221 @node Eliminate Pragma
16222 @section @code{Eliminate} Pragma
16223 @findex Eliminate
16225 @noindent
16226 The simplified syntax of the Eliminate pragma used by @code{gnatelim} is:
16228 @smallexample
16229 @cartouche
16230 @b{pragma} Eliminate (Library_Unit_Name, Subprogram_Name);
16231 @end cartouche
16232 @end smallexample
16234 @noindent
16235 where
16236 @table @code
16237 @item Library_Unit_Name
16238 full expanded Ada name of a library unit
16240 @item Subprogram_Name
16241 a simple or expanded name of a subprogram declared within this
16242 compilation unit
16244 @end table
16246 @noindent
16247 The effect of an @code{Eliminate} pragma placed in the GNAT configuration
16248 file @file{gnat.adc} is:
16250 @itemize @bullet
16252 @item
16253 If the subprogram @code{Subprogram_Name} is declared within
16254 the library unit @code{Library_Unit_Name}, the compiler will not generate
16255 code for this subprogram. This applies to all overloaded subprograms denoted
16256 by @code{Subprogram_Name}.
16258 @item
16259 If a subprogram marked by the pragma @code{Eliminate} is used (called)
16260 in a program, the compiler will produce an error message in the place where
16261 it is called.
16262 @end itemize
16264 @node Tree Files
16265 @section Tree Files
16266 @cindex Tree file
16268 @noindent
16269 A tree file stores a snapshot of the compiler internal data
16270 structures at the very end of a successful compilation. It contains all the
16271 syntactic and semantic information for the compiled unit and all the
16272 units upon which it depends semantically.
16273 To use tools that make use of tree files, you
16274 need to first produce the right set of tree files.
16276 GNAT produces correct tree files when -gnatt -gnatc options are set
16277 in a gcc call. The tree files have an .adt extension.
16278 Therefore, to produce a tree file for the compilation unit contained in a file
16279 named @file{foo.adb}, you must use the command
16281 @smallexample
16282 $ gcc -c -gnatc -gnatt foo.adb
16283 @end smallexample
16285 @noindent
16286 and you will get the tree file @file{foo.adt}.
16287 compilation.
16289 @node Preparing Tree and Bind Files for gnatelim
16290 @section Preparing Tree and Bind Files for @code{gnatelim}
16292 @noindent
16293 A set of tree files covering the program to be analyzed with
16294 @code{gnatelim} and
16295 the bind file for the main subprogram does not have to
16296 be in the current directory.
16297 '-T' gnatelim option may be used to provide
16298 the search path for tree files, and '-b'
16299 option may be used to point to the bind
16300 file to process (see @ref{Running gnatelim})
16302 If you do not have the appropriate set of tree
16303 files and the right bind file, you
16304 may create them in the current directory using the following procedure.
16306 Let @code{Main_Prog} be the name of a main subprogram, and suppose
16307 this subprogram is in a file named @file{main_prog.adb}.
16309 To create a bind file for @code{gnatelim}, run @code{gnatbind} for
16310 the main subprogram. @code{gnatelim} can work with both Ada and C
16311 bind files; when both are present, it uses the Ada bind file.
16312 The following commands will build the program and create the bind file:
16314 @smallexample
16315 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
16316 $ gnatbind main_prog
16317 @end smallexample
16319 @noindent
16320 To create a minimal set of tree files covering the whole program, call
16321 @code{gnatmake} for this program as follows:
16323 @smallexample
16324 @ifset vms
16325 $ GNAT MAKE /FORCE_COMPILE /ACTIONS=COMPILE /NOLOAD /TREE_OUTPUT MAIN_PROG
16326 @end ifset
16327 @ifclear vms
16328 $ gnatmake -f -c -gnatc -gnatt Main_Prog
16329 @end ifclear
16330 @end smallexample
16332 @noindent
16333 The @code{^-c^/ACTIONS=COMPILE^} gnatmake option turns off the bind and link
16334 steps, that are useless anyway because the sources are compiled with
16335 @option{-gnatc} option which turns off code generation.
16337 The @code{^-f^/FORCE_COMPILE^} gnatmake option forces
16338 recompilation of all the needed sources.
16340 This sequence of actions will create all the data needed by @code{gnatelim}
16341 from scratch and therefore guarantee its consistency. If you would like to
16342 use some existing set of files as @code{gnatelim} output, you must make
16343 sure that the set of files is complete and consistent. You can use the
16344 @code{-m} switch to check if there are missed tree files
16346 Note, that @code{gnatelim} needs neither object nor ALI files.
16348 @node Running gnatelim
16349 @section Running @code{gnatelim}
16351 @noindent
16352 @code{gnatelim} has the following command-line interface:
16354 @smallexample
16355 $ gnatelim [options] name
16356 @end smallexample
16358 @noindent
16359 @code{name} should be a full expanded Ada name of a main subprogram
16360 of a program (partition).
16362 @code{gnatelim} options:
16364 @table @code
16365 @item ^-q^/QUIET^
16366 Quiet mode: by default @code{gnatelim} generates to the standard error
16367 stream a trace of the source file names of the compilation units being
16368 processed. This option turns this trace off.
16370 @item ^-v^/VERBOSE^
16371 Verbose mode: @code{gnatelim} version information is printed as Ada
16372 comments to the standard output stream.
16374 @item ^-a^/ALL^
16375 Also look for subprograms from the GNAT run time that can be eliminated.
16377 @item ^-m^/MISSED^
16378 Check if any tree files are missing for an accurate result.
16380 @item ^-T^/TREE_DIRS=^@var{dir}
16381 When looking for tree files also look in directory @var{dir}
16383 @item ^-b^/BIND_FILE=^@var{bind_file}
16384 Specifies @var{bind_file} as the bind file to process. If not set, the name
16385 of the bind file is computed from the full expanded Ada name of a main subprogram.
16387 @item -d@var{x}
16388 Activate internal debugging switches. @var{x} is a letter or digit, or
16389 string of letters or digits, which specifies the type of debugging
16390 mode desired.  Normally these are used only for internal development
16391 or system debugging purposes. You can find full documentation for these
16392 switches in the body of the @code{Gnatelim.Options} unit in the compiler
16393 source file @file{gnatelim-options.adb}.
16394 @end table
16396 @noindent
16397 @code{gnatelim} sends its output to the standard output stream, and all the
16398 tracing and debug information is sent to the standard error stream.
16399 In order to produce a proper GNAT configuration file
16400 @file{gnat.adc}, redirection must be used:
16402 @smallexample
16403 @ifset vms
16404 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
16405 @end ifset
16406 @ifclear vms
16407 $ gnatelim Main_Prog > gnat.adc
16408 @end ifclear
16409 @end smallexample
16411 @ifclear vms
16412 @noindent
16415 @smallexample
16416 $ gnatelim Main_Prog >> gnat.adc
16417 @end smallexample
16418 @end ifclear
16420 @noindent
16421 In order to append the @code{gnatelim} output to the existing contents of
16422 @file{gnat.adc}.
16424 @node Correcting the List of Eliminate Pragmas
16425 @section Correcting the List of Eliminate Pragmas
16427 @noindent
16428 In some rare cases it may happen that @code{gnatelim} will try to eliminate
16429 subprograms which are actually called in the program. In this case, the
16430 compiler will generate an error message of the form:
16432 @smallexample
16433 file.adb:106:07: cannot call eliminated subprogram "My_Prog"
16434 @end smallexample
16436 @noindent
16437 You will need to manually remove the wrong @code{Eliminate} pragmas from
16438 the @file{gnat.adc} file. It is advised that you recompile your program
16439 from scratch after that because you need a consistent @file{gnat.adc} file
16440 during the entire compilation.
16442 @node Making Your Executables Smaller
16443 @section Making Your Executables Smaller
16445 @noindent
16446 In order to get a smaller executable for your program you now have to
16447 recompile the program completely with the new @file{gnat.adc} file
16448 created by @code{gnatelim} in your current directory:
16450 @smallexample
16451 $ gnatmake ^-f Main_Prog^/FORCE_COMPILE MAIN_PROG^
16452 @end smallexample
16454 @noindent
16455 (you will need @code{^-f^/FORCE_COMPILE^} option for gnatmake to
16456 recompile everything
16457 with the set of pragmas @code{Eliminate} you have obtained with
16458 @code{gnatelim}).
16460 Be aware that the set of @code{Eliminate} pragmas is specific to each
16461 program. It is not recommended to merge sets of @code{Eliminate}
16462 pragmas created for different programs in one @file{gnat.adc} file.
16464 @node Summary of the gnatelim Usage Cycle
16465 @section Summary of the gnatelim Usage Cycle
16467 @noindent
16468 Here is a quick summary of the steps to be taken in order to reduce
16469 the size of your executables with @code{gnatelim}. You may use
16470 other GNAT options to control the optimization level,
16471 to produce the debugging information, to set search path, etc.
16473 @enumerate
16474 @item
16475 Produce a bind file and a set of tree files
16477 @smallexample
16478 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
16479 $ gnatbind main_prog
16480 @ifset vms
16481 $ GNAT MAKE /FORCE_COMPILE /NO_LINK /NOLOAD /TREE_OUTPUT MAIN_PROG
16482 @end ifset
16483 @ifclear vms
16484 $ gnatmake -f -c -gnatc -gnatt Main_Prog
16485 @end ifclear
16486 @end smallexample
16488 @item
16489 Generate a list of @code{Eliminate} pragmas
16490 @smallexample
16491 @ifset vms
16492 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
16493 @end ifset
16494 @ifclear vms
16495 $ gnatelim Main_Prog >[>] gnat.adc
16496 @end ifclear
16497 @end smallexample
16499 @item
16500 Recompile the application
16502 @smallexample
16503 $ gnatmake ^-f Main_Prog^/FORCE_COMPILE MAIN_PROG^
16504 @end smallexample
16506 @end enumerate
16508 @node Other Utility Programs
16509 @chapter Other Utility Programs
16511 @noindent
16512 This chapter discusses some other utility programs available in the Ada
16513 environment.
16515 @menu
16516 * Using Other Utility Programs with GNAT::
16517 * The gnatpsta Utility Program::
16518 * The External Symbol Naming Scheme of GNAT::
16519 * Ada Mode for Glide::
16520 * Converting Ada Files to html with gnathtml::
16521 * Installing gnathtml::
16522 @ifset vms
16523 * LSE::
16524 * Profiling::
16525 @end ifset
16526 @end menu
16528 @node Using Other Utility Programs with GNAT
16529 @section Using Other Utility Programs with GNAT
16531 @noindent
16532 The object files generated by GNAT are in standard system format and in
16533 particular the debugging information uses this format. This means
16534 programs generated by GNAT can be used with existing utilities that
16535 depend on these formats.
16537 @ifclear vms
16538 In general, any utility program that works with C will also often work with
16539 Ada programs generated by GNAT. This includes software utilities such as
16540 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
16541 as Purify.
16542 @end ifclear
16544 @node The gnatpsta Utility Program
16545 @section The @code{gnatpsta} Utility Program
16547 @noindent
16548 Many of the definitions in package Standard are implementation-dependent.
16549 However, the source of this package does not exist as an Ada source
16550 file, so these values cannot be determined by inspecting the source.
16551 They can be determined by examining in detail the coding of
16552 @file{cstand.adb} which creates the image of Standard in the compiler,
16553 but this is awkward and requires a great deal of internal knowledge
16554 about the system.
16556 The @code{gnatpsta} utility is designed to deal with this situation.
16557 It is an Ada program that dynamically determines the
16558 values of all the relevant parameters in Standard, and prints them
16559 out in the form of an Ada source listing for Standard, displaying all
16560 the values of interest. This output is generated to
16561 @file{stdout}.
16563 To determine the value of any parameter in package Standard, simply
16564 run @code{gnatpsta} with no qualifiers or arguments, and examine
16565 the output. This is preferable to consulting documentation, because
16566 you know that the values you are getting are the actual ones provided
16567 by the executing system.
16569 @node The External Symbol Naming Scheme of GNAT
16570 @section The External Symbol Naming Scheme of GNAT
16572 @noindent
16573 In order to interpret the output from GNAT, when using tools that are
16574 originally intended for use with other languages, it is useful to
16575 understand the conventions used to generate link names from the Ada
16576 entity names.
16578 All link names are in all lowercase letters. With the exception of library
16579 procedure names, the mechanism used is simply to use the full expanded
16580 Ada name with dots replaced by double underscores. For example, suppose
16581 we have the following package spec:
16583 @smallexample
16584 @group
16585 @cartouche
16586 @b{package} QRS @b{is}
16587    MN : Integer;
16588 @b{end} QRS;
16589 @end cartouche
16590 @end group
16591 @end smallexample
16593 @noindent
16594 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
16595 the corresponding link name is @code{qrs__mn}.
16596 @findex Export
16597 Of course if a @code{pragma Export} is used this may be overridden:
16599 @smallexample
16600 @group
16601 @cartouche
16602 @b{package} Exports @b{is}
16603    Var1 : Integer;
16604    @b{pragma} Export (Var1, C, External_Name => "var1_name");
16605    Var2 : Integer;
16606    @b{pragma} Export (Var2, C, Link_Name => "var2_link_name");
16607 @b{end} Exports;
16608 @end cartouche
16609 @end group
16610 @end smallexample
16612 @noindent
16613 In this case, the link name for @var{Var1} is whatever link name the
16614 C compiler would assign for the C function @var{var1_name}. This typically
16615 would be either @var{var1_name} or @var{_var1_name}, depending on operating
16616 system conventions, but other possibilities exist. The link name for
16617 @var{Var2} is @var{var2_link_name}, and this is not operating system
16618 dependent.
16620 @findex _main
16621 One exception occurs for library level procedures. A potential ambiguity
16622 arises between the required name @code{_main} for the C main program,
16623 and the name we would otherwise assign to an Ada library level procedure
16624 called @code{Main} (which might well not be the main program).
16626 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
16627 names. So if we have a library level procedure such as
16629 @smallexample
16630 @group
16631 @cartouche
16632 @b{procedure} Hello (S : String);
16633 @end cartouche
16634 @end group
16635 @end smallexample
16637 @noindent
16638 the external name of this procedure will be @var{_ada_hello}.
16640 @node Ada Mode for Glide
16641 @section Ada Mode for @code{Glide}
16643 @noindent
16644 The Glide mode for programming in Ada (both, Ada83 and Ada95) helps the
16645 user in understanding existing code and facilitates writing new code. It
16646 furthermore provides some utility functions for easier integration of
16647 standard Emacs features when programming in Ada.
16649 @subsection General Features:
16651 @itemize @bullet
16652 @item
16653 Full Integrated Development Environment :
16655 @itemize @bullet
16656 @item
16657 support of 'project files' for the configuration (directories,
16658 compilation options,...)
16660 @item
16661 compiling and stepping through error messages.
16663 @item
16664 running and debugging your applications within Glide.
16665 @end itemize
16667 @item
16668 easy to use for beginners by pull-down menus,
16670 @item
16671 user configurable by many user-option variables.
16672 @end itemize
16674 @subsection Ada Mode Features That Help Understanding Code:
16676 @itemize @bullet
16677 @item
16678 functions for easy and quick stepping through Ada code,
16680 @item
16681 getting cross reference information for identifiers (e.g. find the
16682 defining place by a keystroke),
16684 @item
16685 displaying an index menu of types and subprograms and move point to
16686 the chosen one,
16688 @item
16689 automatic color highlighting of the various entities in Ada code.
16690 @end itemize
16692 @subsection Glide Support for Writing Ada Code:
16694 @itemize @bullet
16695 @item
16696 switching between spec and body files with possible
16697 autogeneration of body files,
16699 @item
16700 automatic formating of subprograms parameter lists.
16702 @item
16703 automatic smart indentation according to Ada syntax,
16705 @item
16706 automatic completion of identifiers,
16708 @item
16709 automatic casing of identifiers, keywords, and attributes,
16711 @item
16712 insertion of statement templates,
16714 @item
16715 filling comment paragraphs like filling normal text,
16716 @end itemize
16718 For more information, please refer to the online Glide documentation
16719 available in the Glide --> Help Menu.
16721 @node Converting Ada Files to html with gnathtml
16722 @section Converting Ada Files to html with @code{gnathtml}
16724 @noindent
16725 This @code{Perl} script allows Ada source files to be browsed using
16726 standard Web browsers. For installation procedure, see the section
16727 @xref{Installing gnathtml}.
16729 Ada reserved keywords are highlighted in a bold font and Ada comments in
16730 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
16731 switch to suppress the generation of cross-referencing information, user
16732 defined variables and types will appear in a different color; you will
16733 be able to click on any identifier and go to its declaration.
16735 The command line is as follow:
16736 @smallexample
16737 $ perl gnathtml.pl [switches] ada-files
16738 @end smallexample
16740 You can pass it as many Ada files as you want. @code{gnathtml} will generate
16741 an html file for every ada file, and a global file called @file{index.htm}.
16742 This file is an index of every identifier defined in the files.
16744 The available switches are the following ones :
16746 @table @code
16747 @item -83
16748 @cindex @code{-83} (@code{gnathtml})
16749 Only the subset on the Ada 83 keywords will be highlighted, not the full
16750 Ada 95 keywords set.
16752 @item -cc @var{color}
16753 This option allows you to change the color used for comments. The default
16754 value is green. The color argument can be any name accepted by html.
16756 @item -d
16757 @cindex @code{-d} (@code{gnathtml})
16758 If the ada files depend on some other files (using for instance the
16759 @code{with} command, the latter will also be converted to html.
16760 Only the files in the user project will be converted to html, not the files
16761 in the run-time library itself.
16763 @item -D
16764 This command is the same as -d above, but @code{gnathtml} will also look
16765 for files in the run-time library, and generate html files for them.
16767 @item -f
16768 @cindex @code{-f} (@code{gnathtml})
16769 By default, gnathtml will generate html links only for global entities
16770 ('with'ed units, global variables and types,...). If you specify the
16771 @code{-f} on the command line, then links will be generated for local
16772 entities too.
16774 @item -l @var{number}
16775 @cindex @code{-l} (@code{gnathtml})
16776 If this switch is provided and @var{number} is not 0, then @code{gnathtml}
16777 will number the html files every @var{number} line.
16779 @item -I @var{dir}
16780 @cindex @code{-I} (@code{gnathtml})
16781 Specify a directory to search for library files (@file{.ali} files) and
16782 source files. You can provide several -I switches on the command line,
16783 and the directories will be parsed in the order of the command line.
16785 @item -o @var{dir}
16786 @cindex @code{-o} (@code{gnathtml})
16787 Specify the output directory for html files. By default, gnathtml will
16788 saved the generated html files in a subdirectory named @file{html/}.
16790 @item -p @var{file}
16791 @cindex @code{-p} (@code{gnathtml})
16792 If you are using Emacs and the most recent Emacs Ada mode, which provides
16793 a full Integrated Development Environment for compiling, checking,
16794 running and debugging applications, you may be using @file{.adp} files
16795 to give the directories where Emacs can find sources and object files.
16797 Using this switch, you can tell gnathtml to use these files. This allows
16798 you to get an html version of your application, even if it is spread
16799 over multiple directories.
16801 @item -sc @var{color}
16802 @cindex @code{-sc} (@code{gnathtml})
16803 This option allows you to change the color used for symbol definitions.
16804 The default value is red. The color argument can be any name accepted by html.
16806 @item -t @var{file}
16807 @cindex @code{-t} (@code{gnathtml})
16808 This switch provides the name of a file. This file contains a list of
16809 file names to be converted, and the effect is exactly as though they had
16810 appeared explicitly on the command line. This
16811 is the recommended way to work around the command line length limit on some
16812 systems.
16814 @end table
16816 @node Installing gnathtml
16817 @section Installing @code{gnathtml}
16819 @noindent
16820 @code{Perl} needs to be installed on your machine to run this script.
16821 @code{Perl} is freely available for almost every architecture and
16822 Operating System via the Internet.
16824 On Unix systems, you  may want to modify  the  first line of  the script
16825 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
16826 is. The syntax of this line is :
16827 @smallexample
16828 #!full_path_name_to_perl
16829 @end smallexample
16831 @noindent
16832 Alternatively, you may run the script using the following command line:
16834 @smallexample
16835 $ perl gnathtml.pl [switches] files
16836 @end smallexample
16838 @ifset vms
16839 @node LSE
16840 @section LSE
16841 @findex LSE
16843 @noindent
16844 The GNAT distribution provides an Ada 95 template for the Digital Language
16845 Sensitive Editor (LSE), a component of DECset. In order to
16846 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
16848 @node Profiling
16849 @section Profiling
16850 @findex PCA
16852 @noindent
16853 GNAT supports The Digital Performance Coverage Analyzer (PCA), a component
16854 of DECset. To use it proceed as outlined under "HELP PCA", except for running
16855 the collection phase with the /DEBUG qualifier.
16857 @smallexample
16858 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
16859 $ DEFINE LIB$DEBUG PCA$COLLECTOR
16860 $ RUN/DEBUG <PROGRAM_NAME>
16861 @end smallexample
16862 @noindent
16863 @end ifset
16865 @node Running and Debugging Ada Programs
16866 @chapter Running and Debugging Ada Programs
16867 @cindex Debugging
16869 @noindent
16870 This chapter discusses how to debug Ada programs. An incorrect Ada program
16871 may be handled in three ways by the GNAT compiler:
16873 @enumerate
16874 @item
16875 The illegality may be a violation of the static semantics of Ada. In
16876 that case GNAT diagnoses the constructs in the program that are illegal.
16877 It is then a straightforward matter for the user to modify those parts of
16878 the program.
16880 @item
16881 The illegality may be a violation of the dynamic semantics of Ada. In
16882 that case the program compiles and executes, but may generate incorrect
16883 results, or may terminate abnormally with some exception.
16885 @item
16886 When presented with a program that contains convoluted errors, GNAT
16887 itself may terminate abnormally without providing full diagnostics on
16888 the incorrect user program.
16889 @end enumerate
16891 @menu
16892 * The GNAT Debugger GDB::
16893 * Running GDB::
16894 * Introduction to GDB Commands::
16895 * Using Ada Expressions::
16896 * Calling User-Defined Subprograms::
16897 * Using the Next Command in a Function::
16898 * Ada Exceptions::
16899 * Ada Tasks::
16900 * Debugging Generic Units::
16901 * GNAT Abnormal Termination or Failure to Terminate::
16902 * Naming Conventions for GNAT Source Files::
16903 * Getting Internal Debugging Information::
16904 * Stack Traceback::
16905 @end menu
16907 @cindex Debugger
16908 @findex gdb
16910 @node The GNAT Debugger GDB
16911 @section The GNAT Debugger GDB
16913 @noindent
16914 @code{GDB} is a general purpose, platform-independent debugger that
16915 can be used to debug mixed-language programs compiled with @code{GCC},
16916 and in particular is capable of debugging Ada programs compiled with
16917 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
16918 complex Ada data structures.
16920 The manual @cite{Debugging with GDB}
16921 @ifset vms
16922 , located in the GNU:[DOCS] directory,
16923 @end ifset
16924 contains full details on the usage of @code{GDB}, including a section on
16925 its usage on programs. This manual should be consulted for full
16926 details. The section that follows is a brief introduction to the
16927 philosophy and use of @code{GDB}.
16929 When GNAT programs are compiled, the compiler optionally writes debugging
16930 information into the generated object file, including information on
16931 line numbers, and on declared types and variables. This information is
16932 separate from the generated code. It makes the object files considerably
16933 larger, but it does not add to the size of the actual executable that
16934 will be loaded into memory, and has no impact on run-time performance. The
16935 generation of debug information is triggered by the use of the
16936 ^-g^/DEBUG^ switch in the gcc or gnatmake command used to carry out
16937 the compilations. It is important to emphasize that the use of these
16938 options does not change the generated code.
16940 The debugging information is written in standard system formats that
16941 are used by many tools, including debuggers and profilers. The format
16942 of the information is typically designed to describe C types and
16943 semantics, but GNAT implements a translation scheme which allows full
16944 details about Ada types and variables to be encoded into these
16945 standard C formats. Details of this encoding scheme may be found in
16946 the file exp_dbug.ads in the GNAT source distribution. However, the
16947 details of this encoding are, in general, of no interest to a user,
16948 since @code{GDB} automatically performs the necessary decoding.
16950 When a program is bound and linked, the debugging information is
16951 collected from the object files, and stored in the executable image of
16952 the program. Again, this process significantly increases the size of
16953 the generated executable file, but it does not increase the size of
16954 the executable program itself. Furthermore, if this program is run in
16955 the normal manner, it runs exactly as if the debug information were
16956 not present, and takes no more actual memory.
16958 However, if the program is run under control of @code{GDB}, the
16959 debugger is activated.  The image of the program is loaded, at which
16960 point it is ready to run.  If a run command is given, then the program
16961 will run exactly as it would have if @code{GDB} were not present. This
16962 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
16963 entirely non-intrusive until a breakpoint is encountered.  If no
16964 breakpoint is ever hit, the program will run exactly as it would if no
16965 debugger were present. When a breakpoint is hit, @code{GDB} accesses
16966 the debugging information and can respond to user commands to inspect
16967 variables, and more generally to report on the state of execution.
16969 @node Running GDB
16970 @section Running GDB
16972 @ifclear vxworks
16973 @noindent
16974 The debugger can be launched directly and simply from @code{glide} or
16975 through its graphical interface: @code{gvd}. It can also be used
16976 directly in text mode. Here is described the basic use of @code{GDB}
16977 in text mode. All the commands described below can be used in the
16978 @code{gvd} console window eventhough there is usually other more
16979 graphical ways to achieve the same goals.
16981 @ifclear vms
16982 @noindent
16983 The command to run de graphical interface of the debugger is
16984 @smallexample
16985 $ gvd program
16986 @end smallexample
16987 @end ifclear
16989 @noindent
16990 The command to run @code{GDB} in text mode is
16992 @smallexample
16993 $ ^gdb program^$ GDB PROGRAM^
16994 @end smallexample
16996 @noindent
16997 where @code{^program^PROGRAM^} is the name of the executable file. This
16998 activates the debugger and results in a prompt for debugger commands.
16999 The simplest command is simply @code{run}, which causes the program to run
17000 exactly as if the debugger were not present. The following section
17001 describes some of the additional commands that can be given to @code{GDB}.
17002 @end ifclear
17004 @ifset vxworks
17005 Please refer to the debugging section of the chapter specific to your
17006 cross environment at the end of this manual.
17007 @end ifset
17009 @node Introduction to GDB Commands
17010 @section Introduction to GDB Commands
17012 @noindent
17013 @code{GDB} contains a large repertoire of commands. The manual
17014 @cite{Debugging with GDB}
17015 @ifset vms
17016 , located in the GNU:[DOCS] directory,
17017 @end ifset
17018 includes extensive documentation on the use
17019 of these commands, together with examples of their use. Furthermore,
17020 the command @var{help} invoked from within @code{GDB} activates a simple help
17021 facility which summarizes the available commands and their options.
17022 In this section we summarize a few of the most commonly
17023 used commands to give an idea of what @code{GDB} is about. You should create
17024 a simple program with debugging information and experiment with the use of
17025 these @code{GDB} commands on the program as you read through the
17026 following section.
17028 @table @code
17029 @item set args @var{arguments}
17030 The @var{arguments} list above is a list of arguments to be passed to
17031 the program on a subsequent run command, just as though the arguments
17032 had been entered on a normal invocation of the program. The @code{set args}
17033 command is not needed if the program does not require arguments.
17035 @item run
17036 The @code{run} command causes execution of the program to start from
17037 the beginning. If the program is already running, that is to say if
17038 you are currently positioned at a breakpoint, then a prompt will ask
17039 for confirmation that you want to abandon the current execution and
17040 restart.
17042 @item breakpoint @var{location}
17043 The breakpoint command sets a breakpoint, that is to say a point at which
17044 execution will halt and @code{GDB} will await further
17045 commands. @var{location} is
17046 either a line number within a file, given in the format @code{file:linenumber},
17047 or it is the name of a subprogram. If you request that a breakpoint be set on
17048 a subprogram that is overloaded, a prompt will ask you to specify on which of
17049 those subprograms you want to breakpoint. You can also
17050 specify that all of them should be breakpointed. If the program is run
17051 and execution encounters the breakpoint, then the program
17052 stops and @code{GDB} signals that the breakpoint was encountered by
17053 printing the line of code before which the program is halted.
17055 @item breakpoint exception @var{name}
17056 A special form of the breakpoint command which breakpoints whenever
17057 exception @var{name} is raised.
17058 If @var{name} is omitted,
17059 then a breakpoint will occur when any exception is raised.
17061 @item print @var{expression}
17062 This will print the value of the given expression. Most simple
17063 Ada expression formats are properly handled by @code{GDB}, so the expression
17064 can contain function calls, variables, operators, and attribute references.
17066 @item continue
17067 Continues execution following a breakpoint, until the next breakpoint or the
17068 termination of the program.
17070 @item step
17071 Executes a single line after a breakpoint. If the next statement is a subprogram
17072 call, execution continues into (the first statement of) the
17073 called subprogram.
17075 @item next
17076 Executes a single line. If this line is a subprogram call, executes and
17077 returns from the call.
17079 @item list
17080 Lists a few lines around the current source location. In practice, it
17081 is usually more convenient to have a separate edit window open with the
17082 relevant source file displayed. Successive applications of this command
17083 print subsequent lines. The command can be given an argument which is a
17084 line number, in which case it displays a few lines around the specified one.
17086 @item backtrace
17087 Displays a backtrace of the call chain. This command is typically
17088 used after a breakpoint has occurred, to examine the sequence of calls that
17089 leads to the current breakpoint. The display includes one line for each
17090 activation record (frame) corresponding to an active subprogram.
17092 @item up
17093 At a breakpoint, @code{GDB} can display the values of variables local
17094 to the current frame. The command @code{up} can be used to
17095 examine the contents of other active frames, by moving the focus up
17096 the stack, that is to say from callee to caller, one frame at a time.
17098 @item down
17099 Moves the focus of @code{GDB} down from the frame currently being
17100 examined to the frame of its callee (the reverse of the previous command),
17102 @item frame @var{n}
17103 Inspect the frame with the given number. The value 0 denotes the frame
17104 of the current breakpoint, that is to say the top of the call stack.
17106 @end table
17108 The above list is a very short introduction to the commands that
17109 @code{GDB} provides. Important additional capabilities, including conditional
17110 breakpoints, the ability to execute command sequences on a breakpoint,
17111 the ability to debug at the machine instruction level and many other
17112 features are described in detail in @cite{Debugging with GDB}.
17113 Note that most commands can be abbreviated
17114 (for example, c for continue, bt for backtrace).
17116 @node Using Ada Expressions
17117 @section Using Ada Expressions
17118 @cindex Ada expressions
17120 @noindent
17121 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
17122 extensions. The philosophy behind the design of this subset is
17124 @itemize @bullet
17125 @item
17126 That @code{GDB} should provide basic literals and access to operations for
17127 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
17128 leaving more sophisticated computations to subprograms written into the
17129 program (which therefore may be called from @code{GDB}).
17131 @item
17132 That type safety and strict adherence to Ada language restrictions
17133 are not particularly important to the @code{GDB} user.
17135 @item
17136 That brevity is important to the @code{GDB} user.
17137 @end itemize
17139 Thus, for brevity, the debugger acts as if there were
17140 implicit @code{with} and @code{use} clauses in effect for all user-written
17141 packages, thus making it unnecessary to fully qualify most names with
17142 their packages, regardless of context. Where this causes ambiguity,
17143 @code{GDB} asks the user's intent.
17145 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
17147 @node Calling User-Defined Subprograms
17148 @section Calling User-Defined Subprograms
17150 @noindent
17151 An important capability of @code{GDB} is the ability to call user-defined
17152 subprograms while debugging. This is achieved simply by entering
17153 a subprogram call statement in the form:
17155 @smallexample
17156 call subprogram-name (parameters)
17157 @end smallexample
17159 @noindent
17160 The keyword @code{call} can be omitted in the normal case where the
17161 @code{subprogram-name} does not coincide with any of the predefined
17162 @code{GDB} commands.
17164 The effect is to invoke the given subprogram, passing it the
17165 list of parameters that is supplied. The parameters can be expressions and
17166 can include variables from the program being debugged. The
17167 subprogram must be defined
17168 at the library level within your program, and @code{GDB} will call the
17169 subprogram within the environment of your program execution (which
17170 means that the subprogram is free to access or even modify variables
17171 within your program).
17173 The most important use of this facility is in allowing the inclusion of
17174 debugging routines that are tailored to particular data structures
17175 in your program. Such debugging routines can be written to provide a suitably
17176 high-level description of an abstract type, rather than a low-level dump
17177 of its physical layout. After all, the standard
17178 @code{GDB print} command only knows the physical layout of your
17179 types, not their abstract meaning. Debugging routines can provide information
17180 at the desired semantic level and are thus enormously useful.
17182 For example, when debugging GNAT itself, it is crucial to have access to
17183 the contents of the tree nodes used to represent the program internally.
17184 But tree nodes are represented simply by an integer value (which in turn
17185 is an index into a table of nodes).
17186 Using the @code{print} command on a tree node would simply print this integer
17187 value, which is not very useful. But the PN routine (defined in file
17188 treepr.adb in the GNAT sources) takes a tree node as input, and displays
17189 a useful high level representation of the tree node, which includes the
17190 syntactic category of the node, its position in the source, the integers
17191 that denote descendant nodes and parent node, as well as varied
17192 semantic information. To study this example in more detail, you might want to
17193 look at the body of the PN procedure in the stated file.
17195 @node Using the Next Command in a Function
17196 @section Using the Next Command in a Function
17198 @noindent
17199 When you use the @code{next} command in a function, the current source
17200 location will advance to the next statement as usual. A special case
17201 arises in the case of a @code{return} statement.
17203 Part of the code for a return statement is the "epilog" of the function.
17204 This is the code that returns to the caller. There is only one copy of
17205 this epilog code, and it is typically associated with the last return
17206 statement in the function if there is more than one return. In some
17207 implementations, this epilog is associated with the first statement
17208 of the function.
17210 The result is that if you use the @code{next} command from a return
17211 statement that is not the last return statement of the function you
17212 may see a strange apparent jump to the last return statement or to
17213 the start of the function. You should simply ignore this odd jump.
17214 The value returned is always that from the first return statement
17215 that was stepped through.
17217 @node Ada Exceptions
17218 @section Breaking on Ada Exceptions
17219 @cindex Exceptions
17221 @noindent
17222 You can set breakpoints that trip when your program raises
17223 selected exceptions.
17225 @table @code
17226 @item break exception
17227 Set a breakpoint that trips whenever (any task in the) program raises
17228 any exception.
17230 @item break exception @var{name}
17231 Set a breakpoint that trips whenever (any task in the) program raises
17232 the exception @var{name}.
17234 @item break exception unhandled
17235 Set a breakpoint that trips whenever (any task in the) program raises an
17236 exception for which there is no handler.
17238 @item info exceptions
17239 @itemx info exceptions @var{regexp}
17240 The @code{info exceptions} command permits the user to examine all defined
17241 exceptions within Ada programs. With a regular expression, @var{regexp}, as
17242 argument, prints out only those exceptions whose name matches @var{regexp}.
17243 @end table
17245 @node Ada Tasks
17246 @section Ada Tasks
17247 @cindex Tasks
17249 @noindent
17250 @code{GDB} allows the following task-related commands:
17252 @table @code
17253 @item info tasks
17254 This command shows a list of current Ada tasks, as in the following example:
17256 @smallexample
17257 @iftex
17258 @leftskip=0cm
17259 @end iftex
17260 (gdb) info tasks
17261   ID       TID P-ID   Thread Pri State                 Name
17262    1   8088000   0   807e000  15 Child Activation Wait main_task
17263    2   80a4000   1   80ae000  15 Accept/Select Wait    b
17264    3   809a800   1   80a4800  15 Child Activation Wait a
17265 *  4   80ae800   3   80b8000  15 Running               c
17266 @end smallexample
17268 @noindent
17269 In this listing, the asterisk before the first task indicates it to be the
17270 currently running task. The first column lists the task ID that is used
17271 to refer to tasks in the following commands.
17273 @item break @var{linespec} task @var{taskid}
17274 @itemx break @var{linespec} task @var{taskid} if @dots{}
17275 @cindex Breakpoints and tasks
17276 These commands are like the @code{break @dots{} thread @dots{}}.
17277 @var{linespec} specifies source lines.
17279 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
17280 to specify that you only want @code{GDB} to stop the program when a
17281 particular Ada task reaches this breakpoint. @var{taskid} is one of the
17282 numeric task identifiers assigned by @code{GDB}, shown in the first
17283 column of the @samp{info tasks} display.
17285 If you do not specify @samp{task @var{taskid}} when you set a
17286 breakpoint, the breakpoint applies to @emph{all} tasks of your
17287 program.
17289 You can use the @code{task} qualifier on conditional breakpoints as
17290 well; in this case, place @samp{task @var{taskid}} before the
17291 breakpoint condition (before the @code{if}).
17293 @item task @var{taskno}
17294 @cindex Task switching
17296 This command allows to switch to the task referred by @var{taskno}. In
17297 particular, This allows to browse the backtrace of the specified
17298 task. It is advised to switch back to the original task before
17299 continuing execution otherwise the scheduling of the program may be
17300 perturbated.
17301 @end table
17303 @noindent
17304 For more detailed information on the tasking support, see @cite{Debugging with GDB}.
17306 @node Debugging Generic Units
17307 @section Debugging Generic Units
17308 @cindex Debugging Generic Units
17309 @cindex Generics
17311 @noindent
17312 GNAT always uses code expansion for generic instantiation. This means that
17313 each time an instantiation occurs, a complete copy of the original code is
17314 made, with appropriate substitutions of formals by actuals.
17316 It is not possible to refer to the original generic entities in
17317 @code{GDB}, but it is always possible to debug a particular instance of
17318 a generic, by using the appropriate expanded names. For example, if we have
17320 @smallexample
17321 @group
17322 @cartouche
17323 @b{procedure} g @b{is}
17325    @b{generic package} k @b{is}
17326       @b{procedure} kp (v1 : @b{in out} integer);
17327    @b{end} k;
17329    @b{package body} k @b{is}
17330       @b{procedure} kp (v1 : @b{in out} integer) @b{is}
17331       @b{begin}
17332          v1 := v1 + 1;
17333       @b{end} kp;
17334    @b{end} k;
17336    @b{package} k1 @b{is new} k;
17337    @b{package} k2 @b{is new} k;
17339    var : integer := 1;
17341 @b{begin}
17342    k1.kp (var);
17343    k2.kp (var);
17344    k1.kp (var);
17345    k2.kp (var);
17346 @b{end};
17347 @end cartouche
17348 @end group
17349 @end smallexample
17351 @noindent
17352 Then to break on a call to procedure kp in the k2 instance, simply
17353 use the command:
17355 @smallexample
17356 (gdb) break g.k2.kp
17357 @end smallexample
17359 @noindent
17360 When the breakpoint occurs, you can step through the code of the
17361 instance in the normal manner and examine the values of local variables, as for
17362 other units.
17364 @node GNAT Abnormal Termination or Failure to Terminate
17365 @section GNAT Abnormal Termination or Failure to Terminate
17366 @cindex GNAT Abnormal Termination or Failure to Terminate
17368 @noindent
17369 When presented with programs that contain serious errors in syntax
17370 or semantics,
17371 GNAT may on rare occasions  experience problems in operation, such
17372 as aborting with a
17373 segmentation fault or illegal memory access, raising an internal
17374 exception, terminating abnormally, or failing to terminate at all.
17375 In such cases, you can activate
17376 various features of GNAT that can help you pinpoint the construct in your
17377 program that is the likely source of the problem.
17379 The following strategies are presented in increasing order of
17380 difficulty, corresponding to your experience in using GNAT and your
17381 familiarity with compiler internals.
17383 @enumerate
17384 @item
17385 Run @code{gcc} with the @option{-gnatf}. This first
17386 switch causes all errors on a given line to be reported. In its absence,
17387 only the first error on a line is displayed.
17389 The @option{-gnatdO} switch causes errors to be displayed as soon as they
17390 are encountered, rather than after compilation is terminated. If GNAT
17391 terminates prematurely or goes into an infinite loop, the last error
17392 message displayed may help to pinpoint the culprit.
17394 @item
17395 Run @code{gcc} with the @code{^-v (verbose)^/VERBOSE^} switch. In this mode,
17396 @code{gcc} produces ongoing information about the progress of the
17397 compilation and provides the name of each procedure as code is
17398 generated. This switch allows you to find which Ada procedure was being
17399 compiled when it encountered a code generation problem.
17401 @item
17402 @cindex @option{-gnatdc} switch
17403 Run @code{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
17404 switch that does for the front-end what @code{^-v^VERBOSE^} does for the back end.
17405 The system prints the name of each unit, either a compilation unit or
17406 nested unit, as it is being analyzed.
17407 @item
17408 Finally, you can start
17409 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
17410 front-end of GNAT, and can be run independently (normally it is just
17411 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
17412 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
17413 @code{where} command is the first line of attack; the variable
17414 @code{lineno} (seen by @code{print lineno}), used by the second phase of
17415 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
17416 which the execution stopped, and @code{input_file name} indicates the name of
17417 the source file.
17418 @end enumerate
17420 @node Naming Conventions for GNAT Source Files
17421 @section Naming Conventions for GNAT Source Files
17423 @noindent
17424 In order to examine the workings of the GNAT system, the following
17425 brief description of its organization may be helpful:
17427 @itemize @bullet
17428 @item
17429 Files with prefix @file{^sc^SC^} contain the lexical scanner.
17431 @item
17432 All files prefixed with @file{^par^PAR^} are components of the parser. The
17433 numbers correspond to chapters of the Ada 95 Reference Manual. For example,
17434 parsing of select statements can be found in @file{par-ch9.adb}.
17436 @item
17437 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
17438 numbers correspond to chapters of the Ada standard. For example, all
17439 issues involving context clauses can be found in @file{sem_ch10.adb}. In
17440 addition, some features of the language require sufficient special processing
17441 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
17442 dynamic dispatching, etc.
17444 @item
17445 All files prefixed with @file{^exp^EXP^} perform normalization and
17446 expansion of the intermediate representation (abstract syntax tree, or AST).
17447 these files use the same numbering scheme as the parser and semantics files.
17448 For example, the construction of record initialization procedures is done in
17449 @file{exp_ch3.adb}.
17451 @item
17452 The files prefixed with @file{^bind^BIND^} implement the binder, which
17453 verifies the consistency of the compilation, determines an order of
17454 elaboration, and generates the bind file.
17456 @item
17457 The files @file{atree.ads} and @file{atree.adb} detail the low-level
17458 data structures used by the front-end.
17460 @item
17461 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
17462 the abstract syntax tree as produced by the parser.
17464 @item
17465 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
17466 all entities, computed during semantic analysis.
17468 @item
17469 Library management issues are dealt with in files with prefix
17470 @file{^lib^LIB^}.
17472 @item
17473 @findex Ada
17474 @cindex Annex A
17475 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
17476 defined in Annex A.
17478 @item
17479 @findex Interfaces
17480 @cindex Annex B
17481 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
17482 defined in Annex B.
17484 @item
17485 @findex System
17486 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
17487 both language-defined children and GNAT run-time routines.
17489 @item
17490 @findex GNAT
17491 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
17492 general-purpose packages, fully documented in their specifications. All
17493 the other @file{.c} files are modifications of common @code{gcc} files.
17494 @end itemize
17496 @node Getting Internal Debugging Information
17497 @section Getting Internal Debugging Information
17499 @noindent
17500 Most compilers have internal debugging switches and modes. GNAT
17501 does also, except GNAT internal debugging switches and modes are not
17502 secret. A summary and full description of all the compiler and binder
17503 debug flags are in the file @file{debug.adb}. You must obtain the
17504 sources of the compiler to see the full detailed effects of these flags.
17506 The switches that print the source of the program (reconstructed from
17507 the internal tree) are of general interest for user programs, as are the
17508 options to print
17509 the full internal tree, and the entity table (the symbol table
17510 information). The reconstructed source provides a readable version of the
17511 program after the front-end has completed analysis and  expansion, and is useful
17512 when studying the performance of specific constructs. For example, constraint
17513 checks are indicated, complex aggregates are replaced with loops and
17514 assignments, and tasking primitives are replaced with run-time calls.
17516 @node Stack Traceback
17517 @section Stack Traceback
17518 @cindex traceback
17519 @cindex stack traceback
17520 @cindex stack unwinding
17522 @noindent
17523 Traceback is a mechanism to display the sequence of subprogram calls that
17524 leads to a specified execution point in a program. Often (but not always)
17525 the execution point is an instruction at which an exception has been raised.
17526 This mechanism is also known as @i{stack unwinding} because it obtains
17527 its information by scanning the run-time stack and recovering the activation
17528 records of all active subprograms. Stack unwinding is one of the most
17529 important tools for program debugging.
17531 @noindent
17532 The first entry stored in traceback corresponds to the deepest calling level,
17533 that is to say the subprogram currently executing the instruction
17534 from which we want to obtain the traceback.
17536 @noindent
17537 Note that there is no runtime performance penalty when stack traceback
17538 is enabled and no exception are raised during program execution.
17540 @menu
17541 * Non-Symbolic Traceback::
17542 * Symbolic Traceback::
17543 @end menu
17545 @node Non-Symbolic Traceback
17546 @subsection Non-Symbolic Traceback
17547 @cindex traceback, non-symbolic
17549 @noindent
17550 Note: this feature is not supported on all platforms. See
17551 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
17552 platforms.
17554 @menu
17555 * Tracebacks From an Unhandled Exception::
17556 * Tracebacks From Exception Occurrences (non-symbolic)::
17557 * Tracebacks From Anywhere in a Program (non-symbolic)::
17558 @end menu
17560 @node Tracebacks From an Unhandled Exception
17561 @subsubsection Tracebacks From an Unhandled Exception
17563 @noindent
17564 A runtime non-symbolic traceback is a list of addresses of call instructions.
17565 To enable this feature you must use the @code{-E}
17566 @code{gnatbind}'s option. With this option a stack traceback is stored as part
17567 of exception information. It is possible to retrieve this information using the
17568 standard @code{Ada.Exception.Exception_Information} routine.
17570 @noindent
17571 Let's have a look at a simple example:
17573 @smallexample
17574 @cartouche
17575 @group
17576 procedure STB is
17578    procedure P1 is
17579    begin
17580       raise Constraint_Error;
17581    end P1;
17583    procedure P2 is
17584    begin
17585       P1;
17586    end P2;
17588 begin
17589    P2;
17590 end STB;
17591 @end group
17592 @end cartouche
17593 @end smallexample
17595 @smallexample
17596 $ gnatmake stb -bargs -E
17597 $ stb
17599 Execution terminated by unhandled exception
17600 Exception name: CONSTRAINT_ERROR
17601 Message: stb.adb:5
17602 Call stack traceback locations:
17603 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
17604 @end smallexample
17606 @noindent
17607 As we see the traceback lists a sequence of addresses for the unhandled
17608 exception @code{CONSTAINT_ERROR} raised in procedure P1. It is easy to
17609 guess that this exception come from procedure P1. To translate these
17610 addresses into the source lines where the calls appear, the
17611 @code{addr2line} tool, described below, is invaluable. The use of this tool
17612 requires the program to be compiled with debug information.
17614 @smallexample
17615 $ gnatmake -g stb -bargs -E
17616 $ stb
17618 Execution terminated by unhandled exception
17619 Exception name: CONSTRAINT_ERROR
17620 Message: stb.adb:5
17621 Call stack traceback locations:
17622 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
17624 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
17625    0x4011f1 0x77e892a4
17627 00401373 at d:/stb/stb.adb:5
17628 0040138B at d:/stb/stb.adb:10
17629 0040139C at d:/stb/stb.adb:14
17630 00401335 at d:/stb/b~stb.adb:104
17631 004011C4 at /build/.../crt1.c:200
17632 004011F1 at /build/.../crt1.c:222
17633 77E892A4 in ?? at ??:0
17634 @end smallexample
17636 @noindent
17637 @code{addr2line} has a number of other useful options:
17639 @table @code
17640 @item --functions
17641 to get the function name corresponding to any location
17643 @item --demangle=gnat
17644 to use the @b{gnat} decoding mode for the function names. Note that
17645 for binutils version 2.9.x the option is simply @code{--demangle}.
17646 @end table
17648 @smallexample
17649 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
17650    0x40139c 0x401335 0x4011c4 0x4011f1
17652 00401373 in stb.p1 at d:/stb/stb.adb:5
17653 0040138B in stb.p2 at d:/stb/stb.adb:10
17654 0040139C in stb at d:/stb/stb.adb:14
17655 00401335 in main at d:/stb/b~stb.adb:104
17656 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
17657 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
17658 @end smallexample
17660 @noindent
17661 From this traceback we can see that the exception was raised in
17662 @file{stb.adb} at line 5, which was reached from a procedure call in
17663 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
17664 which contains the call to the main program.
17665 @pxref{Running gnatbind}. The remaining entries are assorted runtime routines,
17666 and the output will vary from platform to platform.
17668 @noindent
17669 It is also possible to use @code{GDB} with these traceback addresses to debug
17670 the program. For example, we can break at a given code location, as reported
17671 in the stack traceback:
17673 @smallexample
17674 $ gdb -nw stb
17675 @ifset wnt
17676 @noindent
17677 Furthermore, this feature is not implemented inside Windows DLL. Only
17678 the non-symbolic traceback is reported in this case.
17679 @end ifset
17681 (gdb) break *0x401373
17682 Breakpoint 1 at 0x401373: file stb.adb, line 5.
17683 @end smallexample
17685 @noindent
17686 It is important to note that the stack traceback addresses
17687 do not change when debug information is included. This is particularly useful
17688 because it makes it possible to release software without debug information (to
17689 minimize object size), get a field report that includes a stack traceback
17690 whenever an internal bug occurs, and then be able to retrieve the sequence
17691 of calls with the same program compiled with debug information.
17693 @node Tracebacks From Exception Occurrences (non-symbolic)
17694 @subsubsection Tracebacks From Exception Occurrences
17696 @noindent
17697 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
17698 The stack traceback is attached to the exception information string, and can
17699 be retrieved in an exception handler within the Ada program, by means of the
17700 Ada95 facilities defined in @code{Ada.Exceptions}. Here is a simple example:
17702 @smallexample
17703 @cartouche
17704 @group
17705 with Ada.Text_IO;
17706 with Ada.Exceptions;
17708 procedure STB is
17710    use Ada;
17711    use Ada.Exceptions;
17713    procedure P1 is
17714       K : Positive := 1;
17715    begin
17716       K := K - 1;
17717    exception
17718       when E : others =>
17719          Text_IO.Put_Line (Exception_Information (E));
17720    end P1;
17722    procedure P2 is
17723    begin
17724       P1;
17725    end P2;
17727 begin
17728    P2;
17729 end STB;
17730 @end group
17731 @end cartouche
17732 @end smallexample
17734 @noindent
17735 This program will output:
17737 @smallexample
17738 $ stb
17740 Exception name: CONSTRAINT_ERROR
17741 Message: stb.adb:12
17742 Call stack traceback locations:
17743 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
17744 @end smallexample
17746 @node Tracebacks From Anywhere in a Program (non-symbolic)
17747 @subsubsection Tracebacks From Anywhere in a Program
17749 @noindent
17750 It is also possible to retrieve a stack traceback from anywhere in a
17751 program. For this you need to
17752 use the @code{GNAT.Traceback} API. This package includes a procedure called
17753 @code{Call_Chain} that computes a complete stack traceback, as well as useful
17754 display procedures described below. It is not necessary to use the
17755 @code{-E gnatbind} option in this case, because the stack traceback mechanism
17756 is invoked explicitly.
17758 @noindent
17759 In the following example we compute a traceback at a specific location in
17760 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
17761 convert addresses to strings:
17763 @smallexample
17764 @cartouche
17765 @group
17766 with Ada.Text_IO;
17767 with GNAT.Traceback;
17768 with GNAT.Debug_Utilities;
17770 procedure STB is
17772    use Ada;
17773    use GNAT;
17774    use GNAT.Traceback;
17776    procedure P1 is
17777       TB  : Tracebacks_Array (1 .. 10);
17778       --  We are asking for a maximum of 10 stack frames.
17779       Len : Natural;
17780       --  Len will receive the actual number of stack frames returned.
17781    begin
17782       Call_Chain (TB, Len);
17784       Text_IO.Put ("In STB.P1 : ");
17786       for K in 1 .. Len loop
17787          Text_IO.Put (Debug_Utilities.Image (TB (K)));
17788          Text_IO.Put (' ');
17789       end loop;
17791       Text_IO.New_Line;
17792    end P1;
17794    procedure P2 is
17795    begin
17796       P1;
17797    end P2;
17799 begin
17800    P2;
17801 end STB;
17802 @end group
17803 @end cartouche
17804 @end smallexample
17806 @smallexample
17807 $ gnatmake stb
17808 $ stb
17810 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
17811 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
17812 @end smallexample
17814 @node Symbolic Traceback
17815 @subsection Symbolic Traceback
17816 @cindex traceback, symbolic
17818 @noindent
17819 A symbolic traceback is a stack traceback in which procedure names are
17820 associated with each code location.
17822 @noindent
17823 Note that this feature is not supported on all platforms. See
17824 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
17825 list of currently supported platforms.
17827 @noindent
17828 Note that the symbolic traceback requires that the program be compiled
17829 with debug information. If it is not compiled with debug information
17830 only the non-symbolic information will be valid.
17832 @menu
17833 * Tracebacks From Exception Occurrences (symbolic)::
17834 * Tracebacks From Anywhere in a Program (symbolic)::
17835 @end menu
17837 @node Tracebacks From Exception Occurrences (symbolic)
17838 @subsubsection Tracebacks From Exception Occurrences
17840 @smallexample
17841 @cartouche
17842 @group
17843 with Ada.Text_IO;
17844 with GNAT.Traceback.Symbolic;
17846 procedure STB is
17848    procedure P1 is
17849    begin
17850       raise Constraint_Error;
17851    end P1;
17853    procedure P2 is
17854    begin
17855       P1;
17856    end P2;
17858    procedure P3 is
17859    begin
17860       P2;
17861    end P3;
17863 begin
17864    P3;
17865 exception
17866    when E : others =>
17867       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
17868 end STB;
17869 @end group
17870 @end cartouche
17871 @end smallexample
17873 @smallexample
17874 $ gnatmake -g stb -bargs -E -largs -lgnat -laddr2line -lintl
17875 $ stb
17877 0040149F in stb.p1 at stb.adb:8
17878 004014B7 in stb.p2 at stb.adb:13
17879 004014CF in stb.p3 at stb.adb:18
17880 004015DD in ada.stb at stb.adb:22
17881 00401461 in main at b~stb.adb:168
17882 004011C4 in __mingw_CRTStartup at crt1.c:200
17883 004011F1 in mainCRTStartup at crt1.c:222
17884 77E892A4 in ?? at ??:0
17885 @end smallexample
17887 @noindent
17888 The exact sequence of linker options may vary from platform to platform.
17889 The above @code{-largs} section is for Windows platforms. By contrast,
17890 under Unix there is no need for the @code{-largs} section.
17891 Differences across platforms are due to details of linker implementation.
17893 @node Tracebacks From Anywhere in a Program (symbolic)
17894 @subsubsection Tracebacks From Anywhere in a Program
17896 @noindent
17897 It is possible to get a symbolic stack traceback
17898 from anywhere in a program, just as for non-symbolic tracebacks.
17899 The first step is to obtain a non-symbolic
17900 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
17901 information. Here is an example:
17903 @smallexample
17904 @cartouche
17905 @group
17906 with Ada.Text_IO;
17907 with GNAT.Traceback;
17908 with GNAT.Traceback.Symbolic;
17910 procedure STB is
17912    use Ada;
17913    use GNAT.Traceback;
17914    use GNAT.Traceback.Symbolic;
17916    procedure P1 is
17917       TB  : Tracebacks_Array (1 .. 10);
17918       --  We are asking for a maximum of 10 stack frames.
17919       Len : Natural;
17920       --  Len will receive the actual number of stack frames returned.
17921    begin
17922       Call_Chain (TB, Len);
17923       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
17924    end P1;
17926    procedure P2 is
17927    begin
17928       P1;
17929    end P2;
17931 begin
17932    P2;
17933 end STB;
17934 @end group
17935 @end cartouche
17936 @end smallexample
17938 @ifset vms
17939 @node Compatibility with DEC Ada
17940 @chapter Compatibility with DEC Ada
17941 @cindex Compatibility
17943 @noindent
17944 This section of the manual compares DEC Ada for OpenVMS Alpha and GNAT
17945 OpenVMS Alpha. GNAT achieves a high level of compatibility
17946 with DEC Ada, and it should generally be straightforward to port code
17947 from the DEC Ada environment to GNAT. However, there are a few language
17948 and implementation differences of which the user must be aware. These
17949 differences are discussed in this section. In
17950 addition, the operating environment and command structure for the
17951 compiler are different, and these differences are also discussed.
17953 Note that this discussion addresses specifically the implementation
17954 of Ada 83 for DIGITAL OpenVMS Alpha Systems. In cases where the implementation
17955 of DEC Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems, GNAT
17956 always follows the Alpha implementation.
17958 @menu
17959 * Ada 95 Compatibility::
17960 * Differences in the Definition of Package System::
17961 * Language-Related Features::
17962 * The Package STANDARD::
17963 * The Package SYSTEM::
17964 * Tasking and Task-Related Features::
17965 * Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems::
17966 * Pragmas and Pragma-Related Features::
17967 * Library of Predefined Units::
17968 * Bindings::
17969 * Main Program Definition::
17970 * Implementation-Defined Attributes::
17971 * Compiler and Run-Time Interfacing::
17972 * Program Compilation and Library Management::
17973 * Input-Output::
17974 * Implementation Limits::
17975 * Tools::
17976 @end menu
17978 @node Ada 95 Compatibility
17979 @section Ada 95 Compatibility
17981 @noindent
17982 GNAT is an Ada 95 compiler, and DEC Ada is an Ada 83
17983 compiler. Ada 95 is almost completely upwards compatible
17984 with Ada 83, and therefore Ada 83 programs will compile
17985 and run under GNAT with
17986 no changes or only minor changes. The Ada 95 Reference
17987 Manual (ANSI/ISO/IEC-8652:1995) provides details on specific
17988 incompatibilities.
17990 GNAT provides the switch /83 on the GNAT COMPILE command,
17991 as well as the pragma ADA_83, to force the compiler to
17992 operate in Ada 83 mode. This mode does not guarantee complete
17993 conformance to Ada 83, but in practice is sufficient to
17994 eliminate most sources of incompatibilities.
17995 In particular, it eliminates the recognition of the
17996 additional Ada 95 keywords, so that their use as identifiers
17997 in Ada83 program is legal, and handles the cases of packages
17998 with optional bodies, and generics that instantiate unconstrained
17999 types without the use of @code{(<>)}.
18001 @node Differences in the Definition of Package System
18002 @section Differences in the Definition of Package System
18004 @noindent
18005 Both the Ada 95 and Ada 83 reference manuals permit a compiler to add
18006 implementation-dependent declarations to package System. In normal mode,
18007 GNAT does not take advantage of this permission, and the version of System
18008 provided by GNAT exactly matches that in the Ada 95 Reference Manual.
18010 However, DEC Ada adds an extensive set of declarations to package System,
18011 as fully documented in the DEC Ada manuals. To minimize changes required
18012 for programs that make use of these extensions, GNAT provides the pragma
18013 Extend_System for extending the definition of package System. By using:
18015 @smallexample
18016 @group
18017 @cartouche
18018 @b{pragma} Extend_System (Aux_DEC);
18019 @end cartouche
18020 @end group
18021 @end smallexample
18023 @noindent
18024 The set of definitions in System is extended to include those in package
18025 @code{System.Aux_DEC}.
18026 These definitions are incorporated directly into package
18027 System, as though they had been declared there in the first place. For a
18028 list of the declarations added, see the specification of this package,
18029 which can be found in the file @code{s-auxdec.ads} in the GNAT library.
18030 The pragma Extend_System is a configuration pragma, which means that
18031 it can be placed in the file @file{gnat.adc}, so that it will automatically
18032 apply to all subsequent compilations. See the section on Configuration
18033 Pragmas for further details.
18035 An alternative approach that avoids the use of the non-standard
18036 Extend_System pragma is to add a context clause to the unit that
18037 references these facilities:
18039 @smallexample
18040 @group
18041 @cartouche
18042 @b{with} System.Aux_DEC;
18043 @b{use}  System.Aux_DEC;
18044 @end cartouche
18045 @end group
18046 @end smallexample
18048 @noindent
18049 The effect is not quite semantically identical to incorporating the declarations
18050 directly into package @code{System},
18051 but most programs will not notice a difference
18052 unless they use prefix notation (e.g. @code{System.Integer_8})
18053 to reference the
18054 entities directly in package @code{System}.
18055 For units containing such references,
18056 the prefixes must either be removed, or the pragma @code{Extend_System}
18057 must be used.
18059 @node Language-Related Features
18060 @section Language-Related Features
18062 @noindent
18063 The following sections highlight differences in types,
18064 representations of types, operations, alignment, and
18065 related topics.
18067 @menu
18068 * Integer Types and Representations::
18069 * Floating-Point Types and Representations::
18070 * Pragmas Float_Representation and Long_Float::
18071 * Fixed-Point Types and Representations::
18072 * Record and Array Component Alignment::
18073 * Address Clauses::
18074 * Other Representation Clauses::
18075 @end menu
18077 @node Integer Types and Representations
18078 @subsection Integer Types and Representations
18080 @noindent
18081 The set of predefined integer types is identical in DEC Ada and GNAT.
18082 Furthermore the representation of these integer types is also identical,
18083 including the capability of size clauses forcing biased representation.
18085 In addition,
18086 DEC Ada for OpenVMS Alpha systems has defined the
18087 following additional integer types in package System:
18089 @itemize @bullet
18091 @item
18092 INTEGER_8
18094 @item
18095 INTEGER_16
18097 @item
18098 INTEGER_32
18100 @item
18101 INTEGER_64
18103 @item
18104 LARGEST_INTEGER
18105 @end itemize
18107 @noindent
18108 When using GNAT, the first four of these types may be obtained from the
18109 standard Ada 95 package @code{Interfaces}.
18110 Alternatively, by use of the pragma
18111 @code{Extend_System}, identical
18112 declarations can be referenced directly in package @code{System}.
18113 On both GNAT and DEC Ada, the maximum integer size is 64 bits.
18115 @node Floating-Point Types and Representations
18116 @subsection Floating-Point Types and Representations
18117 @cindex Floating-Point types
18119 @noindent
18120 The set of predefined floating-point types is identical in DEC Ada and GNAT.
18121 Furthermore the representation of these floating-point
18122 types is also identical. One important difference is that the default
18123 representation for DEC Ada is VAX_Float, but the default representation
18124 for GNAT is IEEE.
18126 Specific types may be declared to be VAX_Float or IEEE, using the pragma
18127 @code{Float_Representation} as described in the DEC Ada documentation.
18128 For example, the declarations:
18130 @smallexample
18131 @group
18132 @cartouche
18133 @b{type} F_Float @b{is digits} 6;
18134 @b{pragma} Float_Representation (VAX_Float, F_Float);
18135 @end cartouche
18136 @end group
18137 @end smallexample
18139 @noindent
18140 declare a type F_Float that will be represented in VAX_Float format.
18141 This set of declarations actually appears in System.Aux_DEC, which provides
18142 the full set of additional floating-point declarations provided in
18143 the DEC Ada version of package
18144 System. This and similar declarations may be accessed in a user program by using
18145 pragma @code{Extend_System}. The use of this
18146 pragma, and the related pragma @code{Long_Float} is described in further
18147 detail in the following section.
18149 @node Pragmas Float_Representation and Long_Float
18150 @subsection Pragmas Float_Representation and Long_Float
18152 @noindent
18153 DEC Ada provides the pragma @code{Float_Representation}, which
18154 acts as a program library switch to allow control over
18155 the internal representation chosen for the predefined
18156 floating-point types declared in the package @code{Standard}.
18157 The format of this pragma is as follows:
18159 @smallexample
18160 @group
18161 @cartouche
18162 @b{pragma} @code{Float_Representation}(VAX_Float | IEEE_Float);
18163 @end cartouche
18164 @end group
18165 @end smallexample
18167 @noindent
18168 This pragma controls the representation of floating-point
18169 types as follows:
18171 @itemize @bullet
18172 @item
18173 @code{VAX_Float} specifies that floating-point
18174 types are represented by default with the VAX hardware types
18175 F-floating, D-floating, G-floating. Note that the H-floating
18176 type is available only on DIGITAL Vax systems, and is not available
18177 in either DEC Ada or GNAT for Alpha systems.
18179 @item
18180 @code{IEEE_Float} specifies that floating-point
18181 types are represented by default with the IEEE single and
18182 double floating-point types.
18183 @end itemize
18185 @noindent
18186 GNAT provides an identical implementation of the pragma
18187 @code{Float_Representation}, except that it functions as a
18188 configuration pragma, as defined by Ada 95. Note that the
18189 notion of configuration pragma corresponds closely to the
18190 DEC Ada notion of a program library switch.
18192 When no pragma is used in GNAT, the default is IEEE_Float, which is different
18193 from DEC Ada 83, where the default is VAX_Float. In addition, the
18194 predefined libraries in GNAT are built using IEEE_Float, so it is not
18195 advisable to change the format of numbers passed to standard library
18196 routines, and if necessary explicit type conversions may be needed.
18198 The use of IEEE_Float is recommended in GNAT since it is more efficient,
18199 and (given that it conforms to an international standard) potentially more
18200 portable. The situation in which VAX_Float may be useful is in interfacing
18201 to existing code and data that expects the use of VAX_Float. There are
18202 two possibilities here. If the requirement for the use of VAX_Float is
18203 localized, then the best approach is to use the predefined VAX_Float
18204 types in package @code{System}, as extended by
18205 @code{Extend_System}. For example, use @code{System.F_Float}
18206 to specify the 32-bit @code{F-Float} format.
18208 Alternatively, if an entire program depends heavily on the use of
18209 the @code{VAX_Float} and in particular assumes that the types in
18210 package @code{Standard} are in @code{Vax_Float} format, then it
18211 may be desirable to reconfigure GNAT to assume Vax_Float by default.
18212 This is done by using the GNAT LIBRARY command to rebuild the library, and
18213 then using the general form of the @code{Float_Representation}
18214 pragma to ensure that this default format is used throughout.
18215 The form of the GNAT LIBRARY command is:
18217 @smallexample
18218 GNAT LIBRARY /CONFIG=@i{file} /CREATE=@i{directory}
18219 @end smallexample
18221 @noindent
18222 where @i{file} contains the new configuration pragmas
18223 and @i{directory} is the directory to be created to contain
18224 the new library.
18226 @noindent
18227 On OpenVMS systems, DEC Ada provides the pragma @code{Long_Float}
18228 to allow control over the internal representation chosen
18229 for the predefined type @code{Long_Float} and for floating-point
18230 type declarations with digits specified in the range 7 .. 15.
18231 The format of this pragma is as follows:
18233 @smallexample
18234 @cartouche
18235 @b{pragma} Long_Float (D_FLOAT | G_FLOAT);
18236 @end cartouche
18237 @end smallexample
18239 @node Fixed-Point Types and Representations
18240 @subsection Fixed-Point Types and Representations
18242 @noindent
18243 On DEC Ada for OpenVMS Alpha systems, rounding is
18244 away from zero for both positive and negative numbers.
18245 Therefore, +0.5 rounds to 1 and -0.5 rounds to -1.
18247 On GNAT for OpenVMS Alpha, the results of operations
18248 on fixed-point types are in accordance with the Ada 95
18249 rules. In particular, results of operations on decimal
18250 fixed-point types are truncated.
18252 @node Record and Array Component Alignment
18253 @subsection Record and Array Component Alignment
18255 @noindent
18256 On DEC Ada for OpenVMS Alpha, all non composite components
18257 are aligned on natural boundaries. For example, 1-byte
18258 components are aligned on byte boundaries, 2-byte
18259 components on 2-byte boundaries, 4-byte components on 4-byte
18260 byte boundaries, and so on. The OpenVMS Alpha hardware
18261 runs more efficiently with naturally aligned data.
18263 ON GNAT for OpenVMS Alpha, alignment rules are compatible
18264 with DEC Ada for OpenVMS Alpha.
18266 @node Address Clauses
18267 @subsection Address Clauses
18269 @noindent
18270 In DEC Ada and GNAT, address clauses are supported for
18271 objects and imported subprograms.
18272 The predefined type @code{System.Address} is a private type
18273 in both compilers, with the same representation (it is simply
18274 a machine pointer). Addition, subtraction, and comparison
18275 operations are available in the standard Ada 95 package
18276 @code{System.Storage_Elements}, or in package @code{System}
18277 if it is extended to include @code{System.Aux_DEC} using a
18278 pragma @code{Extend_System} as previously described.
18280 Note that code that with's both this extended package @code{System}
18281 and the package @code{System.Storage_Elements} should not @code{use}
18282 both packages, or ambiguities will result. In general it is better
18283 not to mix these two sets of facilities. The Ada 95 package was
18284 designed specifically to provide the kind of features that DEC Ada
18285 adds directly to package @code{System}.
18287 GNAT is compatible with DEC Ada in its handling of address
18288 clauses, except for some limitations in
18289 the form of address clauses for composite objects with
18290 initialization. Such address clauses are easily replaced
18291 by the use of an explicitly-defined constant as described
18292 in the Ada 95 Reference Manual (13.1(22)). For example, the sequence
18293 of declarations:
18295 @smallexample
18296 @group
18297 @cartouche
18298 X, Y : Integer := Init_Func;
18299 Q : String (X .. Y) := "abc";
18301 @b{for} Q'Address @b{use} Compute_Address;
18302 @end cartouche
18303 @end group
18304 @end smallexample
18306 @noindent
18307 will be rejected by GNAT, since the address cannot be computed at the time
18308 that Q is declared. To achieve the intended effect, write instead:
18310 @smallexample
18311 @group
18312 @cartouche
18313 X, Y : Integer := Init_Func;
18314 Q_Address : @b{constant} Address := Compute_Address;
18315 Q : String (X .. Y) := "abc";
18317 @b{for} Q'Address @b{use} Q_Address;
18318 @end cartouche
18319 @end group
18320 @end smallexample
18322 @noindent
18323 which will be accepted by GNAT (and other Ada 95 compilers), and is also
18324 backwards compatible with Ada 83. A fuller description of the restrictions
18325 on address specifications is found in the GNAT Reference Manual.
18327 @node Other Representation Clauses
18328 @subsection Other Representation Clauses
18330 @noindent
18331 GNAT supports in a compatible manner all the representation
18332 clauses supported by DEC Ada. In addition, it
18333 supports representation clause forms that are new in Ada 95
18334 including COMPONENT_SIZE and SIZE clauses for objects.
18336 @node The Package STANDARD
18337 @section The Package STANDARD
18339 @noindent
18340 The package STANDARD, as implemented by DEC Ada, is fully
18341 described in the Reference Manual for the Ada Programming
18342 Language (ANSI/MIL-STD-1815A-1983) and in the DEC Ada
18343 Language Reference Manual. As implemented by GNAT, the
18344 package STANDARD is described in the Ada 95 Reference
18345 Manual.
18347 In addition, DEC Ada supports the Latin-1 character set in
18348 the type CHARACTER. GNAT supports the Latin-1 character set
18349 in the type CHARACTER and also Unicode (ISO 10646 BMP) in
18350 the type WIDE_CHARACTER.
18352 The floating-point types supported by GNAT are those
18353 supported by DEC Ada, but defaults are different, and are controlled by
18354 pragmas. See @pxref{Floating-Point Types and Representations} for details.
18356 @node The Package SYSTEM
18357 @section The Package SYSTEM
18359 @noindent
18360 DEC Ada provides a system-specific version of the package
18361 SYSTEM for each platform on which the language ships.
18362 For the complete specification of the package SYSTEM, see
18363 Appendix F of the DEC Ada Language Reference Manual.
18365 On DEC Ada, the package SYSTEM includes the following conversion functions:
18366 @itemize @bullet
18367 @item TO_ADDRESS(INTEGER)
18369 @item  TO_ADDRESS(UNSIGNED_LONGWORD)
18371 @item  TO_ADDRESS(universal_integer)
18373 @item  TO_INTEGER(ADDRESS)
18375 @item  TO_UNSIGNED_LONGWORD(ADDRESS)
18377 @item  Function IMPORT_VALUE return UNSIGNED_LONGWORD and the
18378                  functions IMPORT_ADDRESS and IMPORT_LARGEST_VALUE
18379 @end itemize
18381 @noindent
18382 By default, GNAT supplies a version of SYSTEM that matches
18383 the definition given in the Ada 95 Reference Manual.
18384 This
18385 is a subset of the DIGITAL system definitions, which is as
18386 close as possible to the original definitions. The only difference
18387 is that the definition of SYSTEM_NAME is different:
18389 @smallexample
18390 @group
18391 @cartouche
18392 @b{type} Name @b{is} (SYSTEM_NAME_GNAT);
18393 System_Name : @b{constant} Name := SYSTEM_NAME_GNAT;
18394 @end cartouche
18395 @end group
18396 @end smallexample
18398 @noindent
18399 Also, GNAT adds the new Ada 95 declarations for
18400 BIT_ORDER and DEFAULT_BIT_ORDER.
18402 However, the use of the following pragma causes GNAT
18403 to extend the definition of package SYSTEM so that it
18404 encompasses the full set of DIGITAL-specific extensions,
18405 including the functions listed above:
18407 @smallexample
18408 @cartouche
18409 @b{pragma} Extend_System (Aux_DEC);
18410 @end cartouche
18411 @end smallexample
18413 @noindent
18414 The pragma Extend_System is a configuration pragma that
18415 is most conveniently placed in the @file{gnat.adc} file. See the
18416 GNAT Reference Manual for further details.
18418 DEC Ada does not allow the recompilation of the package
18419 SYSTEM. Instead DEC Ada provides several pragmas (SYSTEM_
18420 NAME, STORAGE_UNIT, and MEMORY_SIZE) to modify values in
18421 the package SYSTEM. On OpenVMS Alpha systems, the pragma
18422 SYSTEM_NAME takes the enumeration literal OPENVMS_AXP as
18423 its single argument.
18425 GNAT does permit the recompilation of package SYSTEM using
18426 a special switch (-gnatg) and this switch can be used if
18427 it is necessary to change constants in SYSTEM. GNAT does
18428 not permit the specification of SYSTEM_NAME, STORAGE_UNIT
18429 or MEMORY_SIZE by any other means.
18431 On GNAT systems, the pragma SYSTEM_NAME takes the
18432 enumeration literal SYSTEM_NAME_GNAT.
18434 The definitions provided by the use of
18436 @smallexample
18437 pragma Extend_System (AUX_Dec);
18438 @end smallexample
18440 @noindent
18441 are virtually identical to those provided by the DEC Ada 83 package
18442 System. One important difference is that the name of the TO_ADDRESS
18443 function for type UNSIGNED_LONGWORD is changed to TO_ADDRESS_LONG.
18444 See the GNAT Reference manual for a discussion of why this change was
18445 necessary.
18447 @noindent
18448 The version of TO_ADDRESS taking a universal integer argument is in fact
18449 an extension to Ada 83 not strictly compatible with the reference manual.
18450 In GNAT, we are constrained to be exactly compatible with the standard,
18451 and this means we cannot provide this capability. In DEC Ada 83, the
18452 point of this definition is to deal with a call like:
18454 @smallexample
18455 TO_ADDRESS (16#12777#);
18456 @end smallexample
18458 @noindent
18459 Normally, according to the Ada 83 standard, one would expect this to be
18460 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
18461 of TO_ADDRESS. However, in DEC Ada 83, there is no ambiguity, since the
18462 definition using universal_integer takes precedence.
18464 In GNAT, since the version with universal_integer cannot be supplied, it is
18465 not possible to be 100% compatible. Since there are many programs using
18466 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
18467 to change the name of the function in the UNSIGNED_LONGWORD case, so the
18468 declarations provided in the GNAT version of AUX_Dec are:
18470 @smallexample
18471 function To_Address (X : Integer) return Address;
18472 pragma Pure_Function (To_Address);
18474 function To_Address_Long (X : Unsigned_Longword) return Address;
18475 pragma Pure_Function (To_Address_Long);
18476 @end smallexample
18478 @noindent
18479 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
18480 change the name to TO_ADDRESS_LONG.
18482 @node Tasking and Task-Related Features
18483 @section Tasking and Task-Related Features
18485 @noindent
18486 The concepts relevant to a comparison of tasking on GNAT
18487 and on DEC Ada for OpenVMS Alpha systems are discussed in
18488 the following sections.
18490 For detailed information on concepts related to tasking in
18491 DEC Ada, see the DEC Ada Language Reference Manual and the
18492 relevant run-time reference manual.
18494 @node Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
18495 @section Implementation of Tasks in DEC Ada for OpenVMS Alpha Systems
18497 @noindent
18498 On OpenVMS Alpha systems, each Ada task (except a passive
18499 task) is implemented as a single stream of execution
18500 that is created and managed by the kernel. On these
18501 systems, DEC Ada tasking support is based on DECthreads,
18502 an implementation of the POSIX standard for threads.
18504 Although tasks are implemented as threads, all tasks in
18505 an Ada program are part of the same process. As a result,
18506 resources such as open files and virtual memory can be
18507 shared easily among tasks. Having all tasks in one process
18508 allows better integration with the programming environment
18509 (the shell and the debugger, for example).
18511 Also, on OpenVMS Alpha systems, DEC Ada tasks and foreign
18512 code that calls DECthreads routines can be used together.
18513 The interaction between Ada tasks and DECthreads routines
18514 can have some benefits. For example when on OpenVMS Alpha,
18515 DEC Ada can call C code that is already threaded.
18516 GNAT on OpenVMS Alpha uses the facilities of DECthreads,
18517 and Ada tasks are mapped to threads.
18519 @menu
18520 * Assigning Task IDs::
18521 * Task IDs and Delays::
18522 * Task-Related Pragmas::
18523 * Scheduling and Task Priority::
18524 * The Task Stack::
18525 * External Interrupts::
18526 @end menu
18528 @node Assigning Task IDs
18529 @subsection Assigning Task IDs
18531 @noindent
18532 The DEC Ada Run-Time Library always assigns %TASK 1 to
18533 the environment task that executes the main program. On
18534 OpenVMS Alpha systems, %TASK 0 is often used for tasks
18535 that have been created but are not yet activated.
18537 On OpenVMS Alpha systems, task IDs are assigned at
18538 activation. On GNAT systems, task IDs are also assigned at
18539 task creation but do not have the same form or values as
18540 task ID values in DEC Ada. There is no null task, and the
18541 environment task does not have a specific task ID value.
18543 @node Task IDs and Delays
18544 @subsection Task IDs and Delays
18546 @noindent
18547 On OpenVMS Alpha systems, tasking delays are implemented
18548 using Timer System Services. The Task ID is used for the
18549 identification of the timer request (the REQIDT parameter).
18550 If Timers are used in the application take care not to use
18551 0 for the identification, because cancelling such a timer
18552 will cancel all timers and may lead to unpredictable results.
18554 @node Task-Related Pragmas
18555 @subsection Task-Related Pragmas
18557 @noindent
18558 Ada supplies the pragma TASK_STORAGE, which allows
18559 specification of the size of the guard area for a task
18560 stack. (The guard area forms an area of memory that has no
18561 read or write access and thus helps in the detection of
18562 stack overflow.) On OpenVMS Alpha systems, if the pragma
18563 TASK_STORAGE specifies a value of zero, a minimal guard
18564 area is created. In the absence of a pragma TASK_STORAGE, a default guard
18565 area is created.
18567 GNAT supplies the following task-related pragmas:
18569 @itemize @bullet
18570 @item  TASK_INFO
18572               This pragma appears within a task definition and
18573               applies to the task in which it appears. The argument
18574               must be of type SYSTEM.TASK_INFO.TASK_INFO_TYPE.
18576 @item  TASK_STORAGE
18578               GNAT implements pragma TASK_STORAGE in the same way as
18579               DEC Ada.
18580               Both DEC Ada and GNAT supply the pragmas PASSIVE,
18581               SUPPRESS, and VOLATILE.
18582 @end itemize
18583 @node Scheduling and Task Priority
18584 @subsection Scheduling and Task Priority
18586 @noindent
18587 DEC Ada implements the Ada language requirement that
18588 when two tasks are eligible for execution and they have
18589 different priorities, the lower priority task does not
18590 execute while the higher priority task is waiting. The DEC
18591 Ada Run-Time Library keeps a task running until either the
18592 task is suspended or a higher priority task becomes ready.
18594 On OpenVMS Alpha systems, the default strategy is round-
18595 robin with preemption. Tasks of equal priority take turns
18596 at the processor. A task is run for a certain period of
18597 time and then placed at the rear of the ready queue for
18598 its priority level.
18600 DEC Ada provides the implementation-defined pragma TIME_SLICE,
18601 which can be used to enable or disable round-robin
18602 scheduling of tasks with the same priority.
18603 See the relevant DEC Ada run-time reference manual for
18604 information on using the pragmas to control DEC Ada task
18605 scheduling.
18607 GNAT follows the scheduling rules of Annex D (real-time
18608 Annex) of the Ada 95 Reference Manual. In general, this
18609 scheduling strategy is fully compatible with DEC Ada
18610 although it provides some additional constraints (as
18611 fully documented in Annex D).
18612 GNAT implements time slicing control in a manner compatible with
18613 DEC Ada 83, by means of the pragma Time_Slice, whose semantics are identical
18614 to the DEC Ada 83 pragma of the same name.
18615 Note that it is not possible to mix GNAT tasking and
18616 DEC Ada 83 tasking in the same program, since the two run times are
18617 not compatible.
18619 @node The Task Stack
18620 @subsection The Task Stack
18622 @noindent
18623 In DEC Ada, a task stack is allocated each time a
18624 non passive task is activated. As soon as the task is
18625 terminated, the storage for the task stack is deallocated.
18626 If you specify a size of zero (bytes) with T'STORAGE_SIZE,
18627 a default stack size is used. Also, regardless of the size
18628 specified, some additional space is allocated for task
18629 management purposes. On OpenVMS Alpha systems, at least
18630 one page is allocated.
18632 GNAT handles task stacks in a similar manner. According to
18633 the Ada 95 rules, it provides the pragma STORAGE_SIZE as
18634 an alternative method for controlling the task stack size.
18635 The specification of the attribute T'STORAGE_SIZE is also
18636 supported in a manner compatible with DEC Ada.
18638 @node External Interrupts
18639 @subsection External Interrupts
18641 @noindent
18642 On DEC Ada, external interrupts can be associated with task entries.
18643 GNAT is compatible with DEC Ada in its handling of external interrupts.
18645 @node Pragmas and Pragma-Related Features
18646 @section Pragmas and Pragma-Related Features
18648 @noindent
18649 Both DEC Ada and GNAT supply all language-defined pragmas
18650 as specified by the Ada 83 standard. GNAT also supplies all
18651 language-defined pragmas specified in the Ada 95 Reference Manual.
18652 In addition, GNAT implements the implementation-defined pragmas
18653 from DEC Ada 83.
18655 @itemize @bullet
18656 @item  AST_ENTRY
18658 @item  COMMON_OBJECT
18660 @item  COMPONENT_ALIGNMENT
18662 @item  EXPORT_EXCEPTION
18664 @item  EXPORT_FUNCTION
18666 @item  EXPORT_OBJECT
18668 @item  EXPORT_PROCEDURE
18670 @item  EXPORT_VALUED_PROCEDURE
18672 @item  FLOAT_REPRESENTATION
18674 @item  IDENT
18676 @item  IMPORT_EXCEPTION
18678 @item  IMPORT_FUNCTION
18680 @item  IMPORT_OBJECT
18682 @item  IMPORT_PROCEDURE
18684 @item  IMPORT_VALUED_PROCEDURE
18686 @item  INLINE_GENERIC
18688 @item  INTERFACE_NAME
18690 @item  LONG_FLOAT
18692 @item  MAIN_STORAGE
18694 @item  PASSIVE
18696 @item  PSET_OBJECT
18698 @item  SHARE_GENERIC
18700 @item  SUPPRESS_ALL
18702 @item  TASK_STORAGE
18704 @item  TIME_SLICE
18706 @item  TITLE
18707 @end itemize
18709 @noindent
18710 These pragmas are all fully implemented, with the exception of @code{Title},
18711 @code{Passive}, and @code{Share_Generic}, which are
18712 recognized, but which have no
18713 effect in GNAT. The effect of @code{Passive} may be obtained by the
18714 use of protected objects in Ada 95. In GNAT, all generics are inlined.
18716 Unlike DEC Ada, the GNAT 'EXPORT_@i{subprogram}' pragmas require
18717 a separate subprogram specification which must appear before the
18718 subprogram body.
18720 GNAT also supplies a number of implementation-defined pragmas as follows:
18721 @itemize @bullet
18722 @item  C_PASS_BY_COPY
18724 @item  EXTEND_SYSTEM
18726 @item  SOURCE_FILE_NAME
18728 @item  UNSUPPRESS
18730 @item  WARNINGS
18732 @item  ABORT_DEFER
18734 @item  ADA_83
18736 @item  ADA_95
18738 @item  ANNOTATE
18740 @item  ASSERT
18742 @item  CPP_CLASS
18744 @item  CPP_CONSTRUCTOR
18746 @item  CPP_DESTRUCTOR
18748 @item  CPP_VIRTUAL
18750 @item  CP_VTABLE
18752 @item  DEBUG
18754 @item  LINKER_ALIAS
18756 @item  LINKER_SECTION
18758 @item  MACHINE_ATTRIBUTE
18760 @item  NO_RETURN
18762 @item  PURE_FUNCTION
18764 @item  SOURCE_REFERENCE
18766 @item  TASK_INFO
18768 @item  UNCHECKED_UNION
18770 @item  UNIMPLEMENTED_UNIT
18772 @item  WEAK_EXTERNAL
18773 @end itemize
18775 @noindent
18776 For full details on these GNAT implementation-defined pragmas, see
18777 the GNAT Reference Manual.
18779 @menu
18780 * Restrictions on the Pragma INLINE::
18781 * Restrictions on the Pragma INTERFACE::
18782 * Restrictions on the Pragma SYSTEM_NAME::
18783 @end menu
18785 @node Restrictions on the Pragma INLINE
18786 @subsection Restrictions on the Pragma INLINE
18788 @noindent
18789 DEC Ada applies the following restrictions to the pragma INLINE:
18790 @itemize @bullet
18791 @item  Parameters cannot be a task type.
18793 @item  Function results cannot be task types, unconstrained
18794 array types, or unconstrained types with discriminants.
18796 @item  Bodies cannot declare the following:
18797 @itemize @bullet
18798 @item  Subprogram body or stub (imported subprogram is allowed)
18800 @item  Tasks
18802 @item  Generic declarations
18804 @item  Instantiations
18806 @item  Exceptions
18808 @item  Access types (types derived from access types allowed)
18810 @item  Array or record types
18812 @item  Dependent tasks
18814 @item  Direct recursive calls of subprogram or containing
18815 subprogram, directly or via a renaming
18817 @end itemize
18818 @end itemize
18820 @noindent
18821 In GNAT, the only restriction on pragma INLINE is that the
18822 body must occur before the call if both are in the same
18823 unit, and the size must be appropriately small. There are
18824 no other specific restrictions which cause subprograms to
18825 be incapable of being inlined.
18827 @node  Restrictions on the Pragma INTERFACE
18828 @subsection  Restrictions on the Pragma INTERFACE
18830 @noindent
18831 The following lists and describes the restrictions on the
18832 pragma INTERFACE on DEC Ada and GNAT:
18833 @itemize @bullet
18834 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
18835 Default is the default on OpenVMS Alpha systems.
18837 @item  Parameter passing: Language specifies default
18838 mechanisms but can be overridden with an EXPORT pragma.
18840 @itemize @bullet
18841 @item  Ada: Use internal Ada rules.
18843 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
18844 record or task type. Result cannot be a string, an
18845 array, or a record.
18847 @item  Fortran: Parameters cannot be a task. Result cannot
18848 be a string, an array, or a record.
18849 @end itemize
18850 @end itemize
18852 @noindent
18853 GNAT is entirely upwards compatible with DEC Ada, and in addition allows
18854 record parameters for all languages.
18856 @node  Restrictions on the Pragma SYSTEM_NAME
18857 @subsection  Restrictions on the Pragma SYSTEM_NAME
18859 @noindent
18860 For DEC Ada for OpenVMS Alpha, the enumeration literal
18861 for the type NAME is OPENVMS_AXP. In GNAT, the enumeration
18862 literal for the type NAME is SYSTEM_NAME_GNAT.
18864 @node  Library of Predefined Units
18865 @section  Library of Predefined Units
18867 @noindent
18868 A library of predefined units is provided as part of the
18869 DEC Ada and GNAT implementations. DEC Ada does not provide
18870 the package MACHINE_CODE but instead recommends importing
18871 assembler code.
18873 The GNAT versions of the DEC Ada Run-Time Library (ADA$PREDEFINED:)
18874 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
18875 version. During GNAT installation, the DEC Ada Predefined
18876 Library units are copied into the GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
18877 (aka DECLIB) directory and patched to remove Ada 95 incompatibilities
18878 and to make them interoperable with GNAT, @pxref{Changes to DECLIB}
18879 for details.
18881 The GNAT RTL is contained in
18882 the GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB] (aka ADALIB) directory and
18883 the default search path is set up to find DECLIB units in preference
18884 to ADALIB units with the same name (TEXT_IO, SEQUENTIAL_IO, and DIRECT_IO,
18885 for example).
18887 However, it is possible to change the default so that the
18888 reverse is true, or even to mix them using child package
18889 notation. The DEC Ada 83 units are available as DEC.xxx where xxx
18890 is the package name, and the Ada units are available in the
18891 standard manner defined for Ada 95, that is to say as Ada.xxx. To
18892 change the default, set ADA_INCLUDE_PATH and ADA_OBJECTS_PATH
18893 appropriately. For example, to change the default to use the Ada95
18894 versions do:
18896 @smallexample
18897 $ DEFINE ADA_INCLUDE_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADAINCLUDE],-
18898                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
18899 $ DEFINE ADA_OBJECTS_PATH GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB],-
18900                           GNU:[LIB.OPENVMS7_1.2_8_1.DECLIB]
18901 @end smallexample
18903 @menu
18904 * Changes to DECLIB::
18905 @end menu
18907 @node Changes to DECLIB
18908 @subsection Changes to DECLIB
18910 @noindent
18911 The changes made to the DEC Ada predefined library for GNAT and Ada 95
18912 compatibility are minor and include the following:
18914 @itemize @bullet
18915 @item  Adjusting the location of pragmas and record representation
18916 clauses to obey Ada 95 rules
18918 @item  Adding the proper notation to generic formal parameters
18919 that take unconstrained types in instantiation
18921 @item  Adding pragma ELABORATE_BODY to package specifications
18922 that have package bodies not otherwise allowed
18924 @item  Occurrences of the identifier "PROTECTED" are renamed to "PROTECTD".
18925 Currently these are found only in the STARLET package spec.
18926 @end itemize
18928 @noindent
18929 None of the above changes is visible to users.
18931 @node Bindings
18932 @section Bindings
18934 @noindent
18935 On OpenVMS Alpha, DEC Ada provides the following strongly-typed bindings:
18936 @itemize @bullet
18938 @item  Command Language Interpreter (CLI interface)
18940 @item  DECtalk Run-Time Library (DTK interface)
18942 @item  Librarian utility routines (LBR interface)
18944 @item  General Purpose Run-Time Library (LIB interface)
18946 @item  Math Run-Time Library (MTH interface)
18948 @item  National Character Set Run-Time Library (NCS interface)
18950 @item  Compiled Code Support Run-Time Library (OTS interface)
18952 @item  Parallel Processing Run-Time Library (PPL interface)
18954 @item  Screen Management Run-Time Library (SMG interface)
18956 @item  Sort Run-Time Library (SOR interface)
18958 @item  String Run-Time Library (STR interface)
18960 @item STARLET System Library
18961 @findex Starlet
18963 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
18965 @item  X Windows Toolkit (XT interface)
18967 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
18968 @end itemize
18970 @noindent
18971 GNAT provides implementations of these DEC bindings in the DECLIB directory.
18973 The X/Motif bindings used to build DECLIB are whatever versions are in the
18974 DEC Ada ADA$PREDEFINED directory with extension .ADC. The build script will
18975 automatically add a pragma Linker_Options to packages Xm, Xt, and X_Lib
18976 causing the default X/Motif shareable image libraries to be linked in. This
18977 is done via options files named xm.opt, xt.opt, and x_lib.opt (also located
18978 in the DECLIB directory).
18980 It may be necessary to edit these options files to update or correct the
18981 library names if, for example, the newer X/Motif bindings from ADA$EXAMPLES
18982 had been (previous to installing GNAT) copied and renamed to superseded the
18983 default ADA$PREDEFINED versions.
18985 @menu
18986 * Shared Libraries and Options Files::
18987 * Interfaces to C::
18988 @end menu
18990 @node Shared Libraries and Options Files
18991 @subsection Shared Libraries and Options Files
18993 @noindent
18994 When using the DEC Ada
18995 predefined X and Motif bindings, the linking with their shareable images is
18996 done automatically by GNAT LINK. When using other X and Motif bindings, it
18997 is necessary to add the corresponding shareable images to the command line for
18998 GNAT LINK. When linking with shared libraries, or with .OPT files, it is
18999 also necessary to add them to the command line for GNAT LINK.
19001 A shared library to be used with GNAT is built in the same way as other
19002 libraries under VMS. The VMS Link command can be used in standard fashion.
19004 @node Interfaces to C
19005 @subsection Interfaces to C
19007 @noindent
19008 DEC Ada
19009 provides the following Ada types and operations:
19011 @itemize @bullet
19012 @item C types package (C_TYPES)
19014 @item C strings (C_TYPES.NULL_TERMINATED)
19016 @item Other_types (SHORT_INT)
19017 @end itemize
19019 @noindent
19020 Interfacing to C with GNAT, one can use the above approach
19021 described for DEC Ada or the facilities of Annex B of
19022 the Ada 95 Reference Manual (packages INTERFACES.C,
19023 INTERFACES.C.STRINGS and INTERFACES.C.POINTERS). For more
19024 information, see the section "Interfacing to C" in the
19025 GNAT Reference Manual.
19027 The @option{-gnatF} qualifier forces default and explicit
19028 @code{External_Name} parameters in pragmas Import and Export
19029 to be uppercased for compatibility with the default behavior
19030 of DEC C. The qualifier has no effect on @code{Link_Name} parameters.
19032 @node Main Program Definition
19033 @section Main Program Definition
19035 @noindent
19036 The following section discusses differences in the
19037 definition of main programs on DEC Ada and GNAT.
19038 On DEC Ada, main programs are defined to meet the
19039 following conditions:
19040 @itemize @bullet
19041 @item  Procedure with no formal parameters (returns 0 upon
19042        normal completion)
19044 @item  Procedure with no formal parameters (returns 42 when
19045        unhandled exceptions are raised)
19047 @item  Function with no formal parameters whose returned value
19048        is of a discrete type
19050 @item  Procedure with one OUT formal of a discrete type for
19051        which a specification of pragma EXPORT_VALUED_PROCEDURE is given.
19053 @end itemize
19055 @noindent
19056 When declared with the pragma EXPORT_VALUED_PROCEDURE,
19057 a main function or main procedure returns a discrete
19058 value whose size is less than 64 bits (32 on VAX systems),
19059 the value is zero- or sign-extended as appropriate.
19060 On GNAT, main programs are defined as follows:
19061 @itemize @bullet
19062 @item  Must be a non-generic, parameter-less subprogram that
19063 is either a procedure or function returning an Ada
19064 STANDARD.INTEGER (the predefined type)
19066 @item  Cannot be a generic subprogram or an instantiation of a
19067 generic subprogram
19068 @end itemize
19070 @node Implementation-Defined Attributes
19071 @section Implementation-Defined Attributes
19073 @noindent
19074 GNAT provides all DEC Ada implementation-defined
19075 attributes.
19077 @node Compiler and Run-Time Interfacing
19078 @section Compiler and Run-Time Interfacing
19080 @noindent
19081 DEC Ada provides the following ways to pass options to the linker (ACS LINK):
19082 @itemize @bullet
19083 @item  /WAIT and /SUBMIT qualifiers
19085 @item  /COMMAND qualifier
19087 @item  /[NO]MAP qualifier
19089 @item  /OUTPUT=file-spec
19091 @item  /[NO]DEBUG and /[NO]TRACEBACK qualifiers
19092 @end itemize
19094 @noindent
19095 To pass options to the linker, GNAT provides the following
19096 switches:
19098 @itemize @bullet
19099 @item   /EXECUTABLE=exec-name
19101 @item   /VERBOSE qualifier
19103 @item   /[NO]DEBUG and /[NO]TRACEBACK qualifiers
19104 @end itemize
19106 @noindent
19107 For more information on these switches, see the section
19108 "Switches for gnatlink" in the corresponding section of this Guide.
19109 In DEC Ada, the command-line switch /OPTIMIZE is available
19110 to control optimization. DEC Ada also supplies the
19111 following pragmas:
19112 @itemize @bullet
19113 @item  OPTIMIZE
19115 @item  INLINE
19117 @item  INLINE_GENERIC
19119 @item  SUPPRESS_ALL
19121 @item  PASSIVE
19122 @end itemize
19124 @noindent
19125 In GNAT, optimization is controlled strictly by command
19126 line parameters, as described in the corresponding section of this guide.
19127 The DIGITAL pragmas for control of optimization are
19128 recognized but ignored.
19130 Note that in GNAT, the default is optimization off, whereas in DEC Ada 83,
19131 the default is that optimization is turned on.
19133 @node Program Compilation and Library Management
19134 @section Program Compilation and Library Management
19136 @noindent
19137 DEC Ada and GNAT provide a comparable set of commands to
19138 build programs. DEC Ada also provides a program library,
19139 which is a concept that does not exist on GNAT. Instead,
19140 GNAT provides directories of sources that are compiled as
19141 needed.
19143 The following table summarizes
19144 the DEC Ada commands and provides
19145 equivalent GNAT commands. In this table, some GNAT
19146 equivalents reflect the fact that GNAT does not use the
19147 concept of a program library. Instead, it uses a model
19148 in which collections of source and object files are used
19149 in a manner consistent with other languages like C and
19150 Fortran. Therefore, standard system file commands are used
19151 to manipulate these elements. Those GNAT commands are marked with
19152 an asterisk in the table that follows.
19153 Note that, unlike DEC Ada,  none of the GNAT commands accepts wild cards.
19155 @need 1500
19156 @multitable @columnfractions .31 .30 .39
19158 @item @strong{DEC_Ada_Command}
19159 @tab @strong{GNAT_Equivalent}
19160 @tab @strong{Description}
19162 @item  ADA
19163 @tab     GNAT COMPILE
19164 @tab     Invokes the compiler to compile one or more Ada source files.
19166 @item  ACS ATTACH
19167 @tab     No equivalent
19168 @tab     Switches control of terminal from current process running the program
19169                                                 library manager.
19171 @item   ACS CHECK
19172 @tab      GNAT MAKE /DEPENDENCY_LIST
19173 @tab      Forms the execution closure of one
19174           or more compiled units and checks completeness and currency.
19176 @item   ACS COMPILE
19177 @tab      GNAT MAKE /ACTIONS=COMPILE
19178 @tab      Forms the execution closure of one or
19179           more specified units, checks completeness and currency,
19180           identifies units that have revised source files, compiles same,
19181           and recompiles units that are or will become obsolete.
19182           Also completes incomplete generic instantiations.
19184 @item   ACS COPY FOREIGN
19185 @tab      Copy (*)
19186 @tab      Copies a foreign object file into the program library as a
19187           library unit body.
19189 @item   ACS COPY UNIT
19190 @tab      Copy (*)
19191 @tab      Copies a compiled unit from one program library to another.
19193 @item   ACS CREATE LIBRARY
19194 @tab      Create /directory (*)
19195 @tab      Creates a program library.
19197 @item   ACS CREATE SUBLIBRARY
19198 @tab      Create /directory (*)
19199 @tab      Creates a program sublibrary.
19201 @item   ACS DELETE LIBRARY
19202 @tab
19203 @tab       Deletes a program library and its contents.
19205 @item   ACS DELETE SUBLIBRARY
19206 @tab
19207 @tab      Deletes a program sublibrary and its contents.
19209 @item   ACS DELETE UNIT
19210 @tab      Delete @i{file} (*)
19211 @tab      On OpenVMS systems, deletes one or more compiled units from
19212           the current program library.
19214 @item   ACS DIRECTORY
19215 @tab       Directory (*)
19216 @tab       On OpenVMS systems, lists units contained in the current
19217            program library.
19219 @item   ACS ENTER FOREIGN
19220 @tab      Copy (*)
19221 @tab      Allows the import of a foreign body as an Ada library
19222           specification and enters a reference to a pointer.
19224 @item   ACS ENTER UNIT
19225 @tab      Copy (*)
19226 @tab      Enters a reference (pointer) from the current program library to
19227           a unit compiled into another program library.
19229 @item   ACS EXIT
19230 @tab      No equivalent
19231 @tab      Exits from the program library manager.
19233 @item   ACS EXPORT
19234 @tab      Copy (*)
19235 @tab      Creates an object file that contains system-specific object code
19236           for one or more units. With GNAT, object files can simply be copied
19237           into the desired directory.
19239 @item   ACS EXTRACT SOURCE
19240 @tab      Copy (*)
19241 @tab      Allows access to the copied source file for each Ada compilation unit
19243 @item   ACS HELP
19244 @tab      HELP GNAT
19245 @tab      Provides online help.
19247 @item    ACS LINK
19248 @tab       GNAT LINK
19249 @tab       Links an object file containing Ada units into an executable
19250            file.
19252 @item    ACS LOAD
19253 @tab       Copy (*)
19254 @tab       Loads (partially compiles) Ada units into the program library.
19255            Allows loading a program from a collection of files into a library
19256            without knowing the relationship among units.
19258 @item    ACS MERGE
19259 @tab      Copy (*)
19260 @tab      Merges into the current program library, one or more units from
19261           another library where they were modified.
19263 @item    ACS RECOMPILE
19264 @tab       GNAT MAKE /ACTIONS=COMPILE
19265 @tab       Recompiles from   external or copied source files any obsolete
19266            unit in the closure. Also, completes any incomplete generic
19267            instantiations.
19269 @item    ACS REENTER
19270 @tab       GNAT MAKE
19271 @tab       Reenters current references to units compiled after last entered
19272            with the ACS ENTER UNIT command.
19274 @item    ACS SET LIBRARY
19275 @tab       Set default (*)
19276 @tab       Defines a program library to be the compilation context as well
19277            as the target library for compiler output and commands in general.
19279 @item    ACS SET PRAGMA
19280 @tab       Edit gnat.adc (*)
19281 @tab       Redefines specified  values of the library characteristics
19282             LONG_ FLOAT, MEMORY_SIZE, SYSTEM_NAME, and @code{Float_Representation}.
19284 @item    ACS SET SOURCE
19285 @tab       define @* ADA_INCLUDE_PATH @i{path} (*)
19286 @tab       Defines the source file search list for the ACS COMPILE  command.
19288 @item    ACS SHOW LIBRARY
19289 @tab       Directory (*)
19290 @tab        Lists information about one or more program libraries.
19292 @item    ACS SHOW PROGRAM
19293 @tab       No equivalent
19294 @tab       Lists information about the execution closure of one or
19295            more units in the program library.
19297 @item    ACS SHOW SOURCE
19298 @tab       Show logical @* ADA_INCLUDE_PATH
19299 @tab       Shows the source file search used when compiling units.
19301 @item    ACS SHOW VERSION
19302 @tab       Compile with VERBOSE option
19303 @tab       Displays the version number of the compiler and program library
19304            manager used.
19306 @item    ACS SPAWN
19307 @tab        No equivalent
19308 @tab        Creates a subprocess of the current process (same as DCL SPAWN
19309             command).
19311 @item    ACS VERIFY
19312 @tab       No equivalent
19313 @tab       Performs a series of consistency checks on a program library to
19314            determine whether the library structure and library files are in
19315            valid_form.
19317 @end multitable
19319 @noindent
19321 @node Input-Output
19322 @section Input-Output
19324 @noindent
19325 On OpenVMS Alpha systems, DEC Ada uses OpenVMS Record
19326 Management Services (RMS) to perform operations on
19327 external files.
19329 @noindent
19330 DEC Ada and GNAT predefine an identical set of input-
19331 output packages. To make the use of the
19332 generic TEXT_IO operations more convenient, DEC Ada
19333 provides predefined library packages that instantiate the
19334 integer and floating-point operations for the predefined
19335 integer and floating-point types as shown in the following table.
19337 @table @code
19339 @item   Package_Name
19340       Instantiation
19342 @item   INTEGER_TEXT_IO
19343       INTEGER_IO(INTEGER)
19345 @item   SHORT_INTEGER_TEXT_IO
19346      INTEGER_IO(SHORT_INTEGER)
19348 @item   SHORT_SHORT_INTEGER_TEXT_IO
19349      INTEGER_IO(SHORT_SHORT_ INTEGER)
19351 @item   FLOAT_TEXT_IO
19352       FLOAT_IO(FLOAT)
19354 @item   LONG_FLOAT_TEXT_IO
19355       FLOAT_IO(LONG_FLOAT)
19356 @end table
19358 @noindent
19359 The DEC Ada predefined packages and their operations
19360 are implemented using OpenVMS Alpha files and input-
19361 output facilities. DEC Ada supports asynchronous input-
19362 output on OpenVMS Alpha. Familiarity with the following is
19363 recommended:
19364 @itemize @bullet
19365 @item  RMS file organizations and access methods
19367 @item  OpenVMS file specifications and directories
19369 @item  OpenVMS File Definition Language (FDL)
19370 @end itemize
19372 @noindent
19373 GNAT provides I/O facilities that are completely
19374 compatible with DEC Ada. The distribution includes the
19375 standard DEC Ada versions of all I/O packages, operating
19376 in a manner compatible with DEC Ada. In particular, the
19377 following packages are by default the DEC Ada (Ada 83)
19378 versions of these packages rather than the renamings
19379 suggested in annex J of the Ada 95 Reference Manual:
19380 @itemize @bullet
19381 @item  TEXT_IO
19383 @item  SEQUENTIAL_IO
19385 @item  DIRECT_IO
19386 @end itemize
19388 @noindent
19389 The use of the standard Ada 95 syntax for child packages (for
19390 example, ADA.TEXT_IO) retrieves the Ada 95 versions of these
19391 packages, as defined in the Ada 95 Reference Manual.
19392 GNAT provides DIGITAL-compatible predefined instantiations
19393 of the TEXT_IO packages, and also
19394 provides the standard predefined instantiations required
19395 by the Ada 95 Reference Manual.
19397 For further information on how GNAT interfaces to the file
19398 system or how I/O is implemented in programs written in
19399 mixed languages, see the chapter "Implementation of the
19400 Standard I/O" in the GNAT Reference Manual.
19401 This chapter covers the following:
19402 @itemize @bullet
19403 @item  Standard I/O packages
19405 @item  FORM strings
19407 @item  DIRECT_IO
19409 @item  SEQUENTIAL_IO
19411 @item  TEXT_IO
19413 @item  Stream pointer positioning
19415 @item  Reading and writing non-regular files
19417 @item  GET_IMMEDIATE
19419 @item  Treating TEXT_IO files as streams
19421 @item  Shared files
19423 @item  Open modes
19424 @end itemize
19426 @node Implementation Limits
19427 @section Implementation Limits
19429 @noindent
19430 The following table lists implementation limits for DEC Ada and GNAT systems.
19431 @multitable @columnfractions .60 .20 .20
19432 @item  Compilation Parameter
19433 @tab   DEC Ada
19434 @tab   GNAT
19436 @item  In a subprogram or entry  declaration, maximum number of
19437        formal parameters that are of an unconstrained record type
19438 @tab   32
19439 @tab   No set limit
19441 @item  Maximum identifier length (number of characters)
19442 @tab   255
19443 @tab   255
19445 @item  Maximum number of characters in a source line
19446 @tab   255
19447 @tab   255
19449 @item  Maximum collection size   (number of bytes)
19450 @tab   2**31-1
19451 @tab   2**31-1
19453 @item  Maximum number of discriminants for a record type
19454 @tab   245
19455 @tab   No set limit
19457 @item  Maximum number of formal parameters in an entry or
19458        subprogram declaration
19459 @tab   246
19460 @tab    No set limit
19462 @item  Maximum number of dimensions in an array type
19463 @tab   255
19464 @tab   No set limit
19466 @item  Maximum number of library  units and subunits in a compilation.
19467 @tab   4095
19468 @tab   No set limit
19470 @item  Maximum number of library units and subunits in an execution.
19471 @tab   16383
19472 @tab   No set limit
19474 @item  Maximum number of objects declared with the pragma COMMON_OBJECT
19475        or PSECT_OBJECT
19476 @tab   32757
19477 @tab   No set limit
19479 @item  Maximum number of enumeration literals in an enumeration type
19480        definition
19481 @tab   65535
19482 @tab   No set limit
19484 @item  Maximum number of lines in a source file
19485 @tab   65534
19486 @tab   No set limit
19488 @item  Maximum number of bits in any object
19489 @tab   2**31-1
19490 @tab   2**31-1
19492 @item  Maximum size of the static portion of a stack frame (approximate)
19493 @tab   2**31-1
19494 @tab   2**31-1
19495 @end multitable
19497 @node  Tools
19498 @section Tools
19500 @end ifset
19502 @node Inline Assembler
19503 @chapter Inline Assembler
19505 @noindent
19506 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:
19508 @itemize @bullet
19509 @item No need to use non-Ada tools
19510 @item Consistent interface over different targets
19511 @item Automatic usage of the proper calling conventions
19512 @item Access to Ada constants and variables
19513 @item Definition of intrinsic routines
19514 @item Possibility of inlining a subprogram comprising assembler code
19515 @item Code optimizer can take Inline Assembler code into account
19516 @end itemize
19518 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.
19520 @menu
19521 * Basic Assembler Syntax::
19522 * A Simple Example of Inline Assembler::
19523 * Output Variables in Inline Assembler::
19524 * Input Variables in Inline Assembler::
19525 * Inlining Inline Assembler Code::
19526 * Other Asm Functionality::
19527 * A Complete Example::
19528 @end menu
19530 @c ---------------------------------------------------------------------------
19531 @node Basic Assembler Syntax
19532 @section Basic Assembler Syntax
19534 @noindent
19535 The assembler used by GNAT and gcc is based not on the Intel assembly language, but rather on a
19536 language that descends from the AT&T Unix assembler @emph{as} (and which is often
19537 referred to as ``AT&T syntax'').
19538 The following table summarizes the main features of @emph{as} syntax and points out the differences from the Intel conventions.
19539 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
19540 pre-processor) documentation for further information.
19542 @table @asis
19543 @item Register names
19544 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
19546 Intel: No extra punctuation; for example @code{eax}
19548 @item Immediate operand
19549 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
19551 Intel: No extra punctuation; for example @code{4}
19553 @item Address
19554 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
19556 Intel: No extra punctuation; for example @code{loc}
19558 @item Memory contents
19559 gcc / @emph{as}: No extra punctuation; for example @code{loc}
19561 Intel: Square brackets; for example @code{[loc]}
19563 @item Register contents
19564 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
19566 Intel: Square brackets; for example @code{[eax]}
19568 @item Hexadecimal numbers
19569 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
19571 Intel: Trailing ``h''; for example @code{A0h}
19573 @item Operand size
19574 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move a 16-bit word
19576 Intel: Implicit, deduced by assembler; for example @code{mov}
19578 @item Instruction repetition
19579 gcc / @emph{as}: Split into two lines; for example
19581 @code{rep}
19583 @code{stosl}
19585 Intel: Keep on one line; for example @code{rep stosl}
19587 @item Order of operands
19588 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
19590 Intel: Destination first; for example @code{mov eax, 4}
19591 @end table
19593 @c ---------------------------------------------------------------------------
19594 @node A Simple Example of Inline Assembler
19595 @section A Simple Example of Inline Assembler
19597 @noindent
19598 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.
19600 @smallexample
19601 @group
19602 with System.Machine_Code; use System.Machine_Code;
19603 procedure Nothing is
19604 begin
19605    Asm ("nop");
19606 end Nothing;
19607 @end group
19608 @end smallexample
19610 @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.
19611 @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.
19613 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}.
19615 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:
19616 @smallexample
19617 gnatmake nothing
19618 @end smallexample
19619 However, the interesting aspect of this example is not its run-time behavior but rather the
19620 generated assembly code.  To see this output, invoke the compiler as follows:
19621 @smallexample
19622    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
19623 @end smallexample
19624 where the options are:
19626 @table @code
19627 @item -c
19628 compile only (no bind or link)
19629 @item -S
19630 generate assembler listing
19631 @item -fomit-frame-pointer
19632 do not set up separate stack frames
19633 @item -gnatp
19634 do not add runtime checks
19635 @end table
19637 This gives a human-readable assembler version of the code. The resulting
19638 file will have the same name as the Ada source file, but with a @code{.s} extension.
19639 In our example, the file @file{nothing.s} has the following contents:
19641 @smallexample
19642 @group
19643 .file "nothing.adb"
19644 gcc2_compiled.:
19645 ___gnu_compiled_ada:
19646 .text
19647    .align 4
19648 .globl __ada_nothing
19649 __ada_nothing:
19650 #APP
19651    nop
19652 #NO_APP
19653    jmp L1
19654    .align 2,0x90
19656    ret
19657 @end group
19658 @end smallexample
19660 The assembly code you included is clearly indicated by
19661 the compiler, between the @code{#APP} and @code{#NO_APP}
19662 delimiters. The character before the 'APP' and 'NOAPP'
19663 can differ on different targets. For example, Linux uses '#APP' while
19664 on NT you will see '/APP'.
19666 If you make a mistake in your assembler code (such as using the
19667 wrong size modifier, or using a wrong operand for the instruction) GNAT
19668 will report this error in a temporary file, which will be deleted when
19669 the compilation is finished.  Generating an assembler file will help
19670 in such cases, since you can assemble this file separately using the
19671 @emph{as} assembler that comes with gcc.
19673 Assembling the file using the command
19675 @smallexample
19676 as @file{nothing.s}
19677 @end smallexample
19678 @noindent
19679 will give you error messages whose lines correspond to the assembler
19680 input file, so you can easily find and correct any mistakes you made.
19681 If there are no errors, @emph{as} will generate an object file @file{nothing.out}.
19683 @c ---------------------------------------------------------------------------
19684 @node Output Variables in Inline Assembler
19685 @section Output Variables in Inline Assembler
19687 @noindent
19688 The examples in this section, showing how to access the processor flags, illustrate how to specify the destination operands for assembly language statements.
19690 @smallexample
19691 @group
19692 with Interfaces; use Interfaces;
19693 with Ada.Text_IO; use Ada.Text_IO;
19694 with System.Machine_Code; use System.Machine_Code;
19695 procedure Get_Flags is
19696    Flags : Unsigned_32;
19697    use ASCII;
19698 begin
19699    Asm ("pushfl"          & LF & HT & -- push flags on stack
19700         "popl %%eax"      & LF & HT & -- load eax with flags
19701         "movl %%eax, %0",             -- store flags in variable
19702         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19703    Put_Line ("Flags register:" & Flags'Img);
19704 end Get_Flags;
19705 @end group
19706 @end smallexample
19708 In order to have a nicely aligned assembly listing, we have separated
19709 multiple assembler statements in the Asm template string with linefeed (ASCII.LF)
19710 and horizontal tab (ASCII.HT) characters.  The resulting section of the
19711 assembly output file is:
19713 @smallexample
19714 @group
19715 #APP
19716    pushfl
19717    popl %eax
19718    movl %eax, -40(%ebp)
19719 #NO_APP
19720 @end group
19721 @end smallexample
19723 It would have been legal to write the Asm invocation as:
19725 @smallexample
19726 Asm ("pushfl popl %%eax movl %%eax, %0")
19727 @end smallexample
19729 but in the generated assembler file, this would come out as:
19731 @smallexample
19732 #APP
19733    pushfl popl %eax movl %eax, -40(%ebp)
19734 #NO_APP
19735 @end smallexample
19737 which is not so convenient for the human reader.
19739 We use Ada comments
19740 at the end of each line to explain what the assembler instructions
19741 actually do.  This is a useful convention.
19743 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.
19745 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}.
19746 An output variable is illustrated in
19747 the third statement in the Asm template string:
19748 @smallexample
19749 movl %%eax, %0
19750 @end smallexample
19751 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.
19753 Information about the output variable is supplied in the @code{Outputs} parameter to @code{Asm}:
19754 @smallexample
19755 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19756 @end smallexample
19758 The output is defined by the @code{Asm_Output} attribute of the target type; the general format is
19759 @smallexample
19760 Type'Asm_Output (constraint_string, variable_name)
19761 @end smallexample
19763 The constraint string directs the compiler how
19764 to store/access the associated variable.  In the example
19765 @smallexample
19766 Unsigned_32'Asm_Output ("=m", Flags);
19767 @end smallexample
19768 the @code{"m"} (memory) constraint tells the compiler that the variable
19769 @code{Flags} should be stored in a memory variable, thus preventing
19770 the optimizer from keeping it in a register.  In contrast,
19771 @smallexample
19772 Unsigned_32'Asm_Output ("=r", Flags);
19773 @end smallexample
19774 uses the @code{"r"} (register) constraint, telling the compiler to
19775 store the variable in a register.
19777 If the constraint is preceded by the equal character (@strong{=}), it tells the
19778 compiler that the variable will be used to store data into it.
19780 In the @code{Get_Flags} example, we used the "g" (global) constraint, allowing the optimizer
19781 to choose whatever it deems best.
19783 There are a fairly large number of constraints, but the ones that are most useful (for the Intel x86 processor) are the following:
19785 @table @code
19786 @item =
19787 output constraint
19788 @item g
19789 global (i.e. can be stored anywhere)
19790 @item m
19791 in memory
19792 @item I
19793 a constant
19794 @item a
19795 use eax
19796 @item b
19797 use ebx
19798 @item c
19799 use ecx
19800 @item d
19801 use edx
19802 @item S
19803 use esi
19804 @item D
19805 use edi
19806 @item r
19807 use one of eax, ebx, ecx or edx
19808 @item q
19809 use one of eax, ebx, ecx, edx, esi or edi
19810 @end table
19812 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.
19814 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
19815 @smallexample
19816 @group
19817 Asm ("pushfl"          & LF & HT & -- push flags on stack
19818      "popl %%eax"      & LF & HT & -- load eax with flags
19819      "movl %%eax, %0",             -- store flags in variable
19820      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19821 @end group
19822 @end smallexample
19823 @noindent
19824 @code{%0} will be replaced in the expanded code by the appropriate operand,
19825 whatever
19826 the compiler decided for the @code{Flags} variable.
19828 In general, you may have any number of output variables:
19829 @itemize @bullet
19830 @item
19831 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
19832 @item
19833 Specify the @code{Outputs} parameter as a parenthesized comma-separated list of @code{Asm_Output} attributes
19834 @end itemize
19836 For example:
19837 @smallexample
19838 @group
19839 Asm ("movl %%eax, %0" & LF & HT &
19840      "movl %%ebx, %1" & LF & HT &
19841      "movl %%ecx, %2",
19842      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
19843                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
19844                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
19845 @end group
19846 @end smallexample
19847 @noindent
19848 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables in the Ada program.
19850 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:
19852 @smallexample
19853 @group
19854 with Interfaces; use Interfaces;
19855 with Ada.Text_IO; use Ada.Text_IO;
19856 with System.Machine_Code; use System.Machine_Code;
19857 procedure Get_Flags_2 is
19858    Flags : Unsigned_32;
19859    use ASCII;
19860 begin
19861    Asm ("pushfl"      & LF & HT & -- push flags on stack
19862         "popl %%eax",             -- save flags in eax
19863         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
19864    Put_Line ("Flags register:" & Flags'Img);
19865 end Get_Flags_2;
19866 @end group
19867 @end smallexample
19869 @noindent
19870 The @code{"a"} constraint tells the compiler that the @code{Flags}
19871 variable will come from the eax register. Here is the resulting code:
19873 @smallexample
19874 @group
19875 #APP
19876    pushfl
19877    popl %eax
19878 #NO_APP
19879    movl %eax,-40(%ebp)
19880 @end group
19881 @end smallexample
19883 @noindent
19884 The compiler generated the store of eax into Flags after
19885 expanding the assembler code.
19887 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:
19889 @smallexample
19890 @group
19891 with Interfaces; use Interfaces;
19892 with Ada.Text_IO; use Ada.Text_IO;
19893 with System.Machine_Code; use System.Machine_Code;
19894 procedure Get_Flags_3 is
19895    Flags : Unsigned_32;
19896    use ASCII;
19897 begin
19898    Asm ("pushfl"  & LF & HT & -- push flags on stack
19899         "pop %0",             -- save flags in Flags
19900         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
19901    Put_Line ("Flags register:" & Flags'Img);
19902 end Get_Flags_3;
19903 @end group
19904 @end smallexample
19906 @c ---------------------------------------------------------------------------
19907 @node Input Variables in Inline Assembler
19908 @section Input Variables in Inline Assembler
19910 @noindent
19911 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:
19913 @smallexample
19914 @group
19915 with Interfaces; use Interfaces;
19916 with Ada.Text_IO; use Ada.Text_IO;
19917 with System.Machine_Code; use System.Machine_Code;
19918 procedure Increment is
19920    function Incr (Value : Unsigned_32) return Unsigned_32 is
19921       Result : Unsigned_32;
19922    begin
19923       Asm ("incl %0",
19924            Inputs  => Unsigned_32'Asm_Input ("a", Value),
19925            Outputs => Unsigned_32'Asm_Output ("=a", Result));
19926       return Result;
19927    end Incr;
19929    Value : Unsigned_32;
19931 begin
19932    Value := 5;
19933    Put_Line ("Value before is" & Value'Img);
19934    Value := Incr (Value);
19935    Put_Line ("Value after is" & Value'Img);
19936 end Increment;
19937 @end group
19938 @end smallexample
19940 The @code{Outputs} parameter to @code{Asm} specifies
19941 that the result will be in the eax register and that it is to be stored in the @code{Result}
19942 variable.
19944 The @code{Inputs} parameter looks much like the @code{Outputs} parameter, but with an
19945 @code{Asm_Input} attribute. The
19946 @code{"="} constraint, indicating an output value, is not present.
19948 You can have multiple input variables, in the same way that you can have more
19949 than one output variable.
19951 The parameter count (%0, %1) etc, now starts at the first input
19952 statement, and continues with the output statements.
19953 When both parameters use the same variable, the
19954 compiler will treat them as the same %n operand, which is the case here.
19956 Just as the @code{Outputs} parameter causes the register to be stored into the
19957 target variable after execution of the assembler statements, so does the
19958 @code{Inputs} parameter cause its variable to be loaded into the register before execution
19959 of the
19960 assembler statements.
19962 Thus the effect of the @code{Asm} invocation is:
19963 @enumerate
19964 @item load the 32-bit value of @code{Value} into eax
19965 @item execute the @code{incl %eax} instruction
19966 @item store the contents of eax into the @code{Result} variable
19967 @end enumerate
19969 The resulting assembler file (with @code{-O2} optimization) contains:
19970 @smallexample
19971 @group
19972 _increment__incr.1:
19973    subl $4,%esp
19974    movl 8(%esp),%eax
19975 #APP
19976    incl %eax
19977 #NO_APP
19978    movl %eax,%edx
19979    movl %ecx,(%esp)
19980    addl $4,%esp
19981    ret
19982 @end group
19983 @end smallexample
19985 @c ---------------------------------------------------------------------------
19986 @node Inlining Inline Assembler Code
19987 @section Inlining Inline Assembler Code
19989 @noindent
19990 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)
19991 can be significant, compared to the amount of code in the subprogram body.
19992 A solution is to apply Ada's @code{Inline} pragma to the subprogram,
19993 which directs the compiler to expand invocations of the subprogram at the point(s)
19994 of call, instead of setting up a stack frame for out-of-line calls.
19995 Here is the resulting program:
19997 @smallexample
19998 @group
19999 with Interfaces; use Interfaces;
20000 with Ada.Text_IO; use Ada.Text_IO;
20001 with System.Machine_Code; use System.Machine_Code;
20002 procedure Increment_2 is
20004    function Incr (Value : Unsigned_32) return Unsigned_32 is
20005       Result : Unsigned_32;
20006    begin
20007       Asm ("incl %0",
20008            Inputs  => Unsigned_32'Asm_Input ("a", Value),
20009            Outputs => Unsigned_32'Asm_Output ("=a", Result));
20010       return Result;
20011    end Incr;
20012    pragma Inline (Increment);
20014    Value : Unsigned_32;
20016 begin
20017    Value := 5;
20018    Put_Line ("Value before is" & Value'Img);
20019    Value := Increment (Value);
20020    Put_Line ("Value after is" & Value'Img);
20021 end Increment_2;
20022 @end group
20023 @end smallexample
20025 Compile the program with both optimization (@code{-O2}) and inlining
20026 enabled (@option{-gnatpn} instead of @option{-gnatp}).
20028 The @code{Incr} function is still compiled as usual, but at the
20029 point in @code{Increment} where our function used to be called:
20031 @smallexample
20032 @group
20033 pushl %edi
20034 call _increment__incr.1
20035 @end group
20036 @end smallexample
20038 @noindent
20039 the code for the function body directly appears:
20041 @smallexample
20042 @group
20043 movl %esi,%eax
20044 #APP
20045    incl %eax
20046 #NO_APP
20047    movl %eax,%edx
20048 @end group
20049 @end smallexample
20051 @noindent
20052 thus saving the overhead of stack frame setup and an out-of-line call.
20054 @c ---------------------------------------------------------------------------
20055 @node Other Asm Functionality
20056 @section Other @code{Asm} Functionality
20058 @noindent
20059 This section describes two important parameters to the @code{Asm} procedure: @code{Clobber}, which identifies register usage; and @code{Volatile}, which inhibits unwanted optimizations.
20061 @menu
20062 * The Clobber Parameter::
20063 * The Volatile Parameter::
20064 @end menu
20066 @c ---------------------------------------------------------------------------
20067 @node The Clobber Parameter
20068 @subsection The @code{Clobber} Parameter
20070 @noindent
20071 One of the dangers of intermixing assembly language and a compiled language such as Ada is
20072 that the compiler needs to be aware of which registers are being used by the assembly code.
20073 In some cases, such as the earlier examples, the constraint string is sufficient to
20074 indicate register usage (e.g. "a" for the eax register).  But more generally, the
20075 compiler needs an explicit identification of the registers that are used by the Inline
20076 Assembly statements.
20078 Using a register that the compiler doesn't know about
20079 could be a side effect of an instruction (like @code{mull}
20080 storing its result in both eax and edx).
20081 It can also arise from explicit register usage in your
20082 assembly code; for example:
20083 @smallexample
20084 @group
20085 Asm ("movl %0, %%ebx" & LF & HT &
20086      "movl %%ebx, %1",
20087      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
20088      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out));
20089 @end group
20090 @end smallexample
20091 @noindent
20092 where the compiler (since it does not analyze the @code{Asm} template string)
20093 does not know you are using the ebx register.
20095 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
20096 to identify the registers that will be used by your assembly code:
20098 @smallexample
20099 @group
20100 Asm ("movl %0, %%ebx" & LF & HT &
20101      "movl %%ebx, %1",
20102      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
20103      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
20104      Clobber => "ebx");
20105 @end group
20106 @end smallexample
20108 The Clobber parameter is a static string expression specifying the
20109 register(s) you are using.  Note that register names are @emph{not} prefixed by a percent sign.
20110 Also, if more than one register is used then their names are separated by commas; e.g., @code{"eax, ebx"}
20112 The @code{Clobber} parameter has several additional uses:
20113 @enumerate
20114 @item Use the "register" name @code{cc} to indicate that flags might have changed
20115 @item Use the "register" name @code{memory} if you changed a memory location
20116 @end enumerate
20118 @c ---------------------------------------------------------------------------
20119 @node The Volatile Parameter
20120 @subsection The @code{Volatile} Parameter
20121 @cindex Volatile parameter
20123 @noindent
20124 Compiler optimizations in the presence of Inline Assembler may sometimes have unwanted effects.
20125 For example, when
20126 an @code{Asm} invocation with an input variable is inside a loop, the compiler might move
20127 the loading of the input variable outside the loop, regarding it as a
20128 one-time initialization.
20130 If this effect is not desired, you can disable such optimizations by setting the
20131 @code{Volatile} parameter to @code{True}; for example:
20133 @smallexample
20134 @group
20135 Asm ("movl %0, %%ebx" & LF & HT &
20136      "movl %%ebx, %1",
20137      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
20138      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
20139      Clobber  => "ebx",
20140      Volatile => True);
20141 @end group
20142 @end smallexample
20144 By default, @code{Volatile} is set to @code{False} unless there is no @code{Outputs}
20145 parameter.
20147 Although setting @code{Volatile} to @code{True} prevents unwanted optimizations,
20148 it will also disable other optimizations that might be important for efficiency.
20149 In general, you should set @code{Volatile} to @code{True} only if the compiler's
20150 optimizations have created problems.
20152 @c ---------------------------------------------------------------------------
20153 @node A Complete Example
20154 @section A Complete Example
20156 @noindent
20157 This section contains a complete program illustrating a realistic usage of GNAT's Inline Assembler
20158 capabilities.  It comprises a main procedure @code{Check_CPU} and a package @code{Intel_CPU}.
20159 The package declares a collection of functions that detect the properties of the 32-bit
20160 x86 processor that is running the program.  The main procedure invokes these functions
20161 and displays the information.
20163 The Intel_CPU package could be enhanced by adding functions to
20164 detect the type of x386 co-processor, the processor caching options and
20165 special operations such as the SIMD extensions.
20167 Although the Intel_CPU package has been written for 32-bit Intel
20168 compatible CPUs, it is OS neutral. It has been tested on DOS,
20169 Windows/NT and Linux.
20171 @menu
20172 * Check_CPU Procedure::
20173 * Intel_CPU Package Specification::
20174 * Intel_CPU Package Body::
20175 @end menu
20177 @c ---------------------------------------------------------------------------
20178 @node Check_CPU Procedure
20179 @subsection @code{Check_CPU} Procedure
20180 @cindex Check_CPU procedure
20182 @smallexample
20183 ---------------------------------------------------------------------
20184 --                                                                 --
20185 --  Uses the Intel_CPU package to identify the CPU the program is  --
20186 --  running on, and some of the features it supports.              --
20187 --                                                                 --
20188 ---------------------------------------------------------------------
20190 with Intel_CPU;                     --  Intel CPU detection functions
20191 with Ada.Text_IO;                   --  Standard text I/O
20192 with Ada.Command_Line;              --  To set the exit status
20194 procedure Check_CPU is
20196    Type_Found : Boolean := False;
20197    --  Flag to indicate that processor was identified
20199    Features   : Intel_CPU.Processor_Features;
20200    --  The processor features
20202    Signature  : Intel_CPU.Processor_Signature;
20203    --  The processor type signature
20205 begin
20207    -----------------------------------
20208    --  Display the program banner.  --
20209    -----------------------------------
20211    Ada.Text_IO.Put_Line (Ada.Command_Line.Command_Name &
20212                          ": check Intel CPU version and features, v1.0");
20213    Ada.Text_IO.Put_Line ("distribute freely, but no warranty whatsoever");
20214    Ada.Text_IO.New_Line;
20216    -----------------------------------------------------------------------
20217    --  We can safely start with the assumption that we are on at least  --
20218    --  a x386 processor. If the CPUID instruction is present, then we   --
20219    --  have a later processor type.                                     --
20220    -----------------------------------------------------------------------
20222    if Intel_CPU.Has_CPUID = False then
20224       --  No CPUID instruction, so we assume this is indeed a x386
20225       --  processor. We can still check if it has a FP co-processor.
20226       if Intel_CPU.Has_FPU then
20227          Ada.Text_IO.Put_Line
20228            ("x386-type processor with a FP co-processor");
20229       else
20230          Ada.Text_IO.Put_Line
20231            ("x386-type processor without a FP co-processor");
20232       end if;  --  check for FPU
20234       --  Program done
20235       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
20236       return;
20238    end if;  --  check for CPUID
20240    -----------------------------------------------------------------------
20241    --  If CPUID is supported, check if this is a true Intel processor,  --
20242    --  if it is not, display a warning.                                 --
20243    -----------------------------------------------------------------------
20245    if Intel_CPU.Vendor_ID /= Intel_CPU.Intel_Processor then
20246       Ada.Text_IO.Put_Line ("*** This is a Intel compatible processor");
20247       Ada.Text_IO.Put_Line ("*** Some information may be incorrect");
20248    end if;  --  check if Intel
20250    ----------------------------------------------------------------------
20251    --  With the CPUID instruction present, we can assume at least a    --
20252    --  x486 processor. If the CPUID support level is < 1 then we have  --
20253    --  to leave it at that.                                            --
20254    ----------------------------------------------------------------------
20256    if Intel_CPU.CPUID_Level < 1 then
20258       --  Ok, this is a x486 processor. we still can get the Vendor ID
20259       Ada.Text_IO.Put_Line ("x486-type processor");
20260       Ada.Text_IO.Put_Line ("Vendor ID is " & Intel_CPU.Vendor_ID);
20262       --  We can also check if there is a FPU present
20263       if Intel_CPU.Has_FPU then
20264          Ada.Text_IO.Put_Line ("Floating-Point support");
20265       else
20266          Ada.Text_IO.Put_Line ("No Floating-Point support");
20267       end if;  --  check for FPU
20269       --  Program done
20270       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
20271       return;
20273    end if;  --  check CPUID level
20275    ---------------------------------------------------------------------
20276    --  With a CPUID level of 1 we can use the processor signature to  --
20277    --  determine it's exact type.                                     --
20278    ---------------------------------------------------------------------
20280    Signature := Intel_CPU.Signature;
20282    ----------------------------------------------------------------------
20283    --  Ok, now we go into a lot of messy comparisons to get the        --
20284    --  processor type. For clarity, no attememt to try to optimize the --
20285    --  comparisons has been made. Note that since Intel_CPU does not   --
20286    --  support getting cache info, we cannot distinguish between P5    --
20287    --  and Celeron types yet.                                          --
20288    ----------------------------------------------------------------------
20290    --  x486SL
20291    if Signature.Processor_Type = 2#00#   and
20292      Signature.Family          = 2#0100# and
20293      Signature.Model           = 2#0100# then
20294       Type_Found := True;
20295       Ada.Text_IO.Put_Line ("x486SL processor");
20296    end if;
20298    --  x486DX2 Write-Back
20299    if Signature.Processor_Type = 2#00#   and
20300      Signature.Family          = 2#0100# and
20301      Signature.Model           = 2#0111# then
20302       Type_Found := True;
20303       Ada.Text_IO.Put_Line ("Write-Back Enhanced x486DX2 processor");
20304    end if;
20306    --  x486DX4
20307    if Signature.Processor_Type = 2#00#   and
20308      Signature.Family          = 2#0100# and
20309      Signature.Model           = 2#1000# then
20310       Type_Found := True;
20311       Ada.Text_IO.Put_Line ("x486DX4 processor");
20312    end if;
20314    --  x486DX4 Overdrive
20315    if Signature.Processor_Type = 2#01#   and
20316      Signature.Family          = 2#0100# and
20317      Signature.Model           = 2#1000# then
20318       Type_Found := True;
20319       Ada.Text_IO.Put_Line ("x486DX4 OverDrive processor");
20320    end if;
20322    --  Pentium (60, 66)
20323    if Signature.Processor_Type = 2#00#   and
20324      Signature.Family          = 2#0101# and
20325      Signature.Model           = 2#0001# then
20326       Type_Found := True;
20327       Ada.Text_IO.Put_Line ("Pentium processor (60, 66)");
20328    end if;
20330    --  Pentium (75, 90, 100, 120, 133, 150, 166, 200)
20331    if Signature.Processor_Type = 2#00#   and
20332      Signature.Family          = 2#0101# and
20333      Signature.Model           = 2#0010# then
20334       Type_Found := True;
20335       Ada.Text_IO.Put_Line
20336         ("Pentium processor (75, 90, 100, 120, 133, 150, 166, 200)");
20337    end if;
20339    --  Pentium OverDrive (60, 66)
20340    if Signature.Processor_Type = 2#01#   and
20341      Signature.Family          = 2#0101# and
20342      Signature.Model           = 2#0001# then
20343       Type_Found := True;
20344       Ada.Text_IO.Put_Line ("Pentium OverDrive processor (60, 66)");
20345    end if;
20347    --  Pentium OverDrive (75, 90, 100, 120, 133, 150, 166, 200)
20348    if Signature.Processor_Type = 2#01#   and
20349      Signature.Family          = 2#0101# and
20350      Signature.Model           = 2#0010# then
20351       Type_Found := True;
20352       Ada.Text_IO.Put_Line
20353         ("Pentium OverDrive cpu (75, 90, 100, 120, 133, 150, 166, 200)");
20354    end if;
20356    --  Pentium OverDrive processor for x486 processor-based systems
20357    if Signature.Processor_Type = 2#01#   and
20358      Signature.Family          = 2#0101# and
20359      Signature.Model           = 2#0011# then
20360       Type_Found := True;
20361       Ada.Text_IO.Put_Line
20362         ("Pentium OverDrive processor for x486 processor-based systems");
20363    end if;
20365    --  Pentium processor with MMX technology (166, 200)
20366    if Signature.Processor_Type = 2#00#   and
20367      Signature.Family          = 2#0101# and
20368      Signature.Model           = 2#0100# then
20369       Type_Found := True;
20370       Ada.Text_IO.Put_Line
20371         ("Pentium processor with MMX technology (166, 200)");
20372    end if;
20374    --  Pentium OverDrive with MMX for Pentium (75, 90, 100, 120, 133)
20375    if Signature.Processor_Type = 2#01#   and
20376      Signature.Family          = 2#0101# and
20377      Signature.Model           = 2#0100# then
20378       Type_Found := True;
20379       Ada.Text_IO.Put_Line
20380         ("Pentium OverDrive processor with MMX " &
20381          "technology for Pentium processor (75, 90, 100, 120, 133)");
20382    end if;
20384    --  Pentium Pro processor
20385    if Signature.Processor_Type = 2#00#   and
20386      Signature.Family          = 2#0110# and
20387      Signature.Model           = 2#0001# then
20388       Type_Found := True;
20389       Ada.Text_IO.Put_Line ("Pentium Pro processor");
20390    end if;
20392    --  Pentium II processor, model 3
20393    if Signature.Processor_Type = 2#00#   and
20394      Signature.Family          = 2#0110# and
20395      Signature.Model           = 2#0011# then
20396       Type_Found := True;
20397       Ada.Text_IO.Put_Line ("Pentium II processor, model 3");
20398    end if;
20400    --  Pentium II processor, model 5 or Celeron processor
20401    if Signature.Processor_Type = 2#00#   and
20402      Signature.Family          = 2#0110# and
20403      Signature.Model           = 2#0101# then
20404       Type_Found := True;
20405       Ada.Text_IO.Put_Line
20406         ("Pentium II processor, model 5 or Celeron processor");
20407    end if;
20409    --  Pentium Pro OverDrive processor
20410    if Signature.Processor_Type = 2#01#   and
20411      Signature.Family          = 2#0110# and
20412      Signature.Model           = 2#0011# then
20413       Type_Found := True;
20414       Ada.Text_IO.Put_Line ("Pentium Pro OverDrive processor");
20415    end if;
20417    --  If no type recognized, we have an unknown. Display what
20418    --  we _do_ know
20419    if Type_Found = False then
20420       Ada.Text_IO.Put_Line ("Unknown processor");
20421    end if;
20423    -----------------------------------------
20424    --  Display processor stepping level.  --
20425    -----------------------------------------
20427    Ada.Text_IO.Put_Line ("Stepping level:" & Signature.Stepping'Img);
20429    ---------------------------------
20430    --  Display vendor ID string.  --
20431    ---------------------------------
20433    Ada.Text_IO.Put_Line ("Vendor ID: " & Intel_CPU.Vendor_ID);
20435    ------------------------------------
20436    --  Get the processors features.  --
20437    ------------------------------------
20439    Features := Intel_CPU.Features;
20441    -----------------------------
20442    --  Check for a FPU unit.  --
20443    -----------------------------
20445    if Features.FPU = True then
20446       Ada.Text_IO.Put_Line ("Floating-Point unit available");
20447    else
20448       Ada.Text_IO.Put_Line ("no Floating-Point unit");
20449    end if;  --  check for FPU
20451    --------------------------------
20452    --  List processor features.  --
20453    --------------------------------
20455    Ada.Text_IO.Put_Line ("Supported features: ");
20457    --  Virtual Mode Extension
20458    if Features.VME = True then
20459       Ada.Text_IO.Put_Line ("    VME    - Virtual Mode Extension");
20460    end if;
20462    --  Debugging Extension
20463    if Features.DE = True then
20464       Ada.Text_IO.Put_Line ("    DE     - Debugging Extension");
20465    end if;
20467    --  Page Size Extension
20468    if Features.PSE = True then
20469       Ada.Text_IO.Put_Line ("    PSE    - Page Size Extension");
20470    end if;
20472    --  Time Stamp Counter
20473    if Features.TSC = True then
20474       Ada.Text_IO.Put_Line ("    TSC    - Time Stamp Counter");
20475    end if;
20477    --  Model Specific Registers
20478    if Features.MSR = True then
20479       Ada.Text_IO.Put_Line ("    MSR    - Model Specific Registers");
20480    end if;
20482    --  Physical Address Extension
20483    if Features.PAE = True then
20484       Ada.Text_IO.Put_Line ("    PAE    - Physical Address Extension");
20485    end if;
20487    --  Machine Check Extension
20488    if Features.MCE = True then
20489       Ada.Text_IO.Put_Line ("    MCE    - Machine Check Extension");
20490    end if;
20492    --  CMPXCHG8 instruction supported
20493    if Features.CX8 = True then
20494       Ada.Text_IO.Put_Line ("    CX8    - CMPXCHG8 instruction");
20495    end if;
20497    --  on-chip APIC hardware support
20498    if Features.APIC = True then
20499       Ada.Text_IO.Put_Line ("    APIC   - on-chip APIC hardware support");
20500    end if;
20502    --  Fast System Call
20503    if Features.SEP = True then
20504       Ada.Text_IO.Put_Line ("    SEP    - Fast System Call");
20505    end if;
20507    --  Memory Type Range Registers
20508    if Features.MTRR = True then
20509       Ada.Text_IO.Put_Line ("    MTTR   - Memory Type Range Registers");
20510    end if;
20512    --  Page Global Enable
20513    if Features.PGE = True then
20514       Ada.Text_IO.Put_Line ("    PGE    - Page Global Enable");
20515    end if;
20517    --  Machine Check Architecture
20518    if Features.MCA = True then
20519       Ada.Text_IO.Put_Line ("    MCA    - Machine Check Architecture");
20520    end if;
20522    --  Conditional Move Instruction Supported
20523    if Features.CMOV = True then
20524       Ada.Text_IO.Put_Line
20525         ("    CMOV   - Conditional Move Instruction Supported");
20526    end if;
20528    --  Page Attribute Table
20529    if Features.PAT = True then
20530       Ada.Text_IO.Put_Line ("    PAT    - Page Attribute Table");
20531    end if;
20533    --  36-bit Page Size Extension
20534    if Features.PSE_36 = True then
20535       Ada.Text_IO.Put_Line ("    PSE_36 - 36-bit Page Size Extension");
20536    end if;
20538    --  MMX technology supported
20539    if Features.MMX = True then
20540       Ada.Text_IO.Put_Line ("    MMX    - MMX technology supported");
20541    end if;
20543    --  Fast FP Save and Restore
20544    if Features.FXSR = True then
20545       Ada.Text_IO.Put_Line ("    FXSR   - Fast FP Save and Restore");
20546    end if;
20548    ---------------------
20549    --  Program done.  --
20550    ---------------------
20552    Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Success);
20554 exception
20556    when others =>
20557       Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
20558       raise;
20560 end Check_CPU;
20561 @end smallexample
20563 @c ---------------------------------------------------------------------------
20564 @node Intel_CPU Package Specification
20565 @subsection @code{Intel_CPU} Package Specification
20566 @cindex Intel_CPU package specification
20568 @smallexample
20569 -------------------------------------------------------------------------
20570 --                                                                     --
20571 --  file: intel_cpu.ads                                                --
20572 --                                                                     --
20573 --           *********************************************             --
20574 --           * WARNING: for 32-bit Intel processors only *             --
20575 --           *********************************************             --
20576 --                                                                     --
20577 --  This package contains a number of subprograms that are useful in   --
20578 --  determining the Intel x86 CPU (and the features it supports) on    --
20579 --  which the program is running.                                      --
20580 --                                                                     --
20581 --  The package is based upon the information given in the Intel       --
20582 --  Application Note AP-485: "Intel Processor Identification and the   --
20583 --  CPUID Instruction" as of April 1998. This application note can be  --
20584 --  found on www.intel.com.                                            --
20585 --                                                                     --
20586 --  It currently deals with 32-bit processors only, will not detect    --
20587 --  features added after april 1998, and does not guarantee proper     --
20588 --  results on Intel-compatible processors.                            --
20589 --                                                                     --
20590 --  Cache info and x386 fpu type detection are not supported.          --
20591 --                                                                     --
20592 --  This package does not use any privileged instructions, so should   --
20593 --  work on any OS running on a 32-bit Intel processor.                --
20594 --                                                                     --
20595 -------------------------------------------------------------------------
20597 with Interfaces;             use Interfaces;
20598 --  for using unsigned types
20600 with System.Machine_Code;    use System.Machine_Code;
20601 --  for using inline assembler code
20603 with Ada.Characters.Latin_1; use Ada.Characters.Latin_1;
20604 --  for inserting control characters
20606 package Intel_CPU is
20608    ----------------------
20609    --  Processor bits  --
20610    ----------------------
20612    subtype Num_Bits is Natural range 0 .. 31;
20613    --  the number of processor bits (32)
20615    --------------------------
20616    --  Processor register  --
20617    --------------------------
20619    --  define a processor register type for easy access to
20620    --  the individual bits
20622    type Processor_Register is array (Num_Bits) of Boolean;
20623    pragma Pack (Processor_Register);
20624    for Processor_Register'Size use 32;
20626    -------------------------
20627    --  Unsigned register  --
20628    -------------------------
20630    --  define a processor register type for easy access to
20631    --  the individual bytes
20633    type Unsigned_Register is
20634       record
20635          L1 : Unsigned_8;
20636          H1 : Unsigned_8;
20637          L2 : Unsigned_8;
20638          H2 : Unsigned_8;
20639       end record;
20641    for Unsigned_Register use
20642       record
20643          L1 at 0 range  0 ..  7;
20644          H1 at 0 range  8 .. 15;
20645          L2 at 0 range 16 .. 23;
20646          H2 at 0 range 24 .. 31;
20647       end record;
20649    for Unsigned_Register'Size use 32;
20651    ---------------------------------
20652    --  Intel processor vendor ID  --
20653    ---------------------------------
20655    Intel_Processor : constant String (1 .. 12) := "GenuineIntel";
20656    --  indicates an Intel manufactured processor
20658    ------------------------------------
20659    --  Processor signature register  --
20660    ------------------------------------
20662    --  a register type to hold the processor signature
20664    type Processor_Signature is
20665       record
20666          Stepping       : Natural range 0 .. 15;
20667          Model          : Natural range 0 .. 15;
20668          Family         : Natural range 0 .. 15;
20669          Processor_Type : Natural range 0 .. 3;
20670          Reserved       : Natural range 0 .. 262143;
20671       end record;
20673    for Processor_Signature use
20674       record
20675          Stepping       at 0 range  0 ..  3;
20676          Model          at 0 range  4 ..  7;
20677          Family         at 0 range  8 .. 11;
20678          Processor_Type at 0 range 12 .. 13;
20679          Reserved       at 0 range 14 .. 31;
20680       end record;
20682    for Processor_Signature'Size use 32;
20684    -----------------------------------
20685    --  Processor features register  --
20686    -----------------------------------
20688    --  a processor register to hold the processor feature flags
20690    type Processor_Features is
20691       record
20692          FPU    : Boolean;                --  floating point unit on chip
20693          VME    : Boolean;                --  virtual mode extension
20694          DE     : Boolean;                --  debugging extension
20695          PSE    : Boolean;                --  page size extension
20696          TSC    : Boolean;                --  time stamp counter
20697          MSR    : Boolean;                --  model specific registers
20698          PAE    : Boolean;                --  physical address extension
20699          MCE    : Boolean;                --  machine check extension
20700          CX8    : Boolean;                --  cmpxchg8 instruction
20701          APIC   : Boolean;                --  on-chip apic hardware
20702          Res_1  : Boolean;                --  reserved for extensions
20703          SEP    : Boolean;                --  fast system call
20704          MTRR   : Boolean;                --  memory type range registers
20705          PGE    : Boolean;                --  page global enable
20706          MCA    : Boolean;                --  machine check architecture
20707          CMOV   : Boolean;                --  conditional move supported
20708          PAT    : Boolean;                --  page attribute table
20709          PSE_36 : Boolean;                --  36-bit page size extension
20710          Res_2  : Natural range 0 .. 31;  --  reserved for extensions
20711          MMX    : Boolean;                --  MMX technology supported
20712          FXSR   : Boolean;                --  fast FP save and restore
20713          Res_3  : Natural range 0 .. 127; --  reserved for extensions
20714       end record;
20716    for Processor_Features use
20717       record
20718          FPU    at 0 range  0 ..  0;
20719          VME    at 0 range  1 ..  1;
20720          DE     at 0 range  2 ..  2;
20721          PSE    at 0 range  3 ..  3;
20722          TSC    at 0 range  4 ..  4;
20723          MSR    at 0 range  5 ..  5;
20724          PAE    at 0 range  6 ..  6;
20725          MCE    at 0 range  7 ..  7;
20726          CX8    at 0 range  8 ..  8;
20727          APIC   at 0 range  9 ..  9;
20728          Res_1  at 0 range 10 .. 10;
20729          SEP    at 0 range 11 .. 11;
20730          MTRR   at 0 range 12 .. 12;
20731          PGE    at 0 range 13 .. 13;
20732          MCA    at 0 range 14 .. 14;
20733          CMOV   at 0 range 15 .. 15;
20734          PAT    at 0 range 16 .. 16;
20735          PSE_36 at 0 range 17 .. 17;
20736          Res_2  at 0 range 18 .. 22;
20737          MMX    at 0 range 23 .. 23;
20738          FXSR   at 0 range 24 .. 24;
20739          Res_3  at 0 range 25 .. 31;
20740       end record;
20742    for Processor_Features'Size use 32;
20744    -------------------
20745    --  Subprograms  --
20746    -------------------
20748    function Has_FPU return Boolean;
20749    --  return True if a FPU is found
20750    --  use only if CPUID is not supported
20752    function Has_CPUID return Boolean;
20753    --  return True if the processor supports the CPUID instruction
20755    function CPUID_Level return Natural;
20756    --  return the CPUID support level (0, 1 or 2)
20757    --  can only be called if the CPUID instruction is supported
20759    function Vendor_ID return String;
20760    --  return the processor vendor identification string
20761    --  can only be called if the CPUID instruction is supported
20763    function Signature return Processor_Signature;
20764    --  return the processor signature
20765    --  can only be called if the CPUID instruction is supported
20767    function Features return Processor_Features;
20768    --  return the processors features
20769    --  can only be called if the CPUID instruction is supported
20771 private
20773    ------------------------
20774    --  EFLAGS bit names  --
20775    ------------------------
20777    ID_Flag : constant Num_Bits := 21;
20778    --  ID flag bit
20780 end Intel_CPU;
20781 @end smallexample
20783 @c ---------------------------------------------------------------------------
20784 @node Intel_CPU Package Body
20785 @subsection @code{Intel_CPU} Package Body
20786 @cindex Intel_CPU package body
20788 @smallexample
20789 package body Intel_CPU is
20791    ---------------------------
20792    --  Detect FPU presence  --
20793    ---------------------------
20795    --  There is a FPU present if we can set values to the FPU Status
20796    --  and Control Words.
20798    function Has_FPU return Boolean is
20800       Register : Unsigned_16;
20801       --  processor register to store a word
20803    begin
20805       --  check if we can change the status word
20806       Asm (
20808            --  the assembler code
20809            "finit"              & LF & HT &    --  reset status word
20810            "movw $0x5A5A, %%ax" & LF & HT &    --  set value status word
20811            "fnstsw %0"          & LF & HT &    --  save status word
20812            "movw %%ax, %0",                    --  store status word
20814            --  output stored in Register
20815            --  register must be a memory location
20816            Outputs => Unsigned_16'Asm_output ("=m", Register),
20818            --  tell compiler that we used eax
20819            Clobber => "eax");
20821       --  if the status word is zero, there is no FPU
20822       if Register = 0 then
20823          return False;   --  no status word
20824       end if;  --  check status word value
20826       --  check if we can get the control word
20827       Asm (
20829            --  the assembler code
20830            "fnstcw %0",   --  save the control word
20832            --  output into Register
20833            --  register must be a memory location
20834            Outputs => Unsigned_16'Asm_output ("=m", Register));
20836       --  check the relevant bits
20837       if (Register and 16#103F#) /= 16#003F# then
20838          return False;   --  no control word
20839       end if;  --  check control word value
20841       --  FPU found
20842       return True;
20844    end Has_FPU;
20846    --------------------------------
20847    --  Detect CPUID instruction  --
20848    --------------------------------
20850    --  The processor supports the CPUID instruction if it is possible
20851    --  to change the value of ID flag bit in the EFLAGS register.
20853    function Has_CPUID return Boolean is
20855       Original_Flags, Modified_Flags : Processor_Register;
20856       --  EFLAG contents before and after changing the ID flag
20858    begin
20860       --  try flipping the ID flag in the EFLAGS register
20861       Asm (
20863            --  the assembler code
20864            "pushfl"               & LF & HT &     --  push EFLAGS on stack
20865            "pop %%eax"            & LF & HT &     --  pop EFLAGS into eax
20866            "movl %%eax, %0"       & LF & HT &     --  save EFLAGS content
20867            "xor $0x200000, %%eax" & LF & HT &     --  flip ID flag
20868            "push %%eax"           & LF & HT &     --  push EFLAGS on stack
20869            "popfl"                & LF & HT &     --  load EFLAGS register
20870            "pushfl"               & LF & HT &     --  push EFLAGS on stack
20871            "pop %1",                              --  save EFLAGS content
20873            --  output values, may be anything
20874            --  Original_Flags is %0
20875            --  Modified_Flags is %1
20876            Outputs =>
20877               (Processor_Register'Asm_output ("=g", Original_Flags),
20878                Processor_Register'Asm_output ("=g", Modified_Flags)),
20880            --  tell compiler eax is destroyed
20881            Clobber => "eax");
20883       --  check if CPUID is supported
20884       if Original_Flags(ID_Flag) /= Modified_Flags(ID_Flag) then
20885          return True;   --  ID flag was modified
20886       else
20887          return False;  --  ID flag unchanged
20888       end if;  --  check for CPUID
20890    end Has_CPUID;
20892    -------------------------------
20893    --  Get CPUID support level  --
20894    -------------------------------
20896    function CPUID_Level return Natural is
20898       Level : Unsigned_32;
20899       --  returned support level
20901    begin
20903       --  execute CPUID, storing the results in the Level register
20904       Asm (
20906            --  the assembler code
20907            "cpuid",    --  execute CPUID
20909            --  zero is stored in eax
20910            --  returning the support level in eax
20911            Inputs => Unsigned_32'Asm_input ("a", 0),
20913            --  eax is stored in Level
20914            Outputs => Unsigned_32'Asm_output ("=a", Level),
20916            --  tell compiler ebx, ecx and edx registers are destroyed
20917            Clobber => "ebx, ecx, edx");
20919       --  return the support level
20920       return Natural (Level);
20922    end CPUID_Level;
20924    --------------------------------
20925    --  Get CPU Vendor ID String  --
20926    --------------------------------
20928    --  The vendor ID string is returned in the ebx, ecx and edx register
20929    --  after executing the CPUID instruction with eax set to zero.
20930    --  In case of a true Intel processor the string returned is
20931    --  "GenuineIntel"
20933    function Vendor_ID return String is
20935       Ebx, Ecx, Edx : Unsigned_Register;
20936       --  registers containing the vendor ID string
20938       Vendor_ID : String (1 .. 12);
20939       -- the vendor ID string
20941    begin
20943       --  execute CPUID, storing the results in the processor registers
20944       Asm (
20946            --  the assembler code
20947            "cpuid",    --  execute CPUID
20949            --  zero stored in eax
20950            --  vendor ID string returned in ebx, ecx and edx
20951            Inputs => Unsigned_32'Asm_input ("a", 0),
20953            --  ebx is stored in Ebx
20954            --  ecx is stored in Ecx
20955            --  edx is stored in Edx
20956            Outputs => (Unsigned_Register'Asm_output ("=b", Ebx),
20957                        Unsigned_Register'Asm_output ("=c", Ecx),
20958                        Unsigned_Register'Asm_output ("=d", Edx)));
20960       --  now build the vendor ID string
20961       Vendor_ID( 1) := Character'Val (Ebx.L1);
20962       Vendor_ID( 2) := Character'Val (Ebx.H1);
20963       Vendor_ID( 3) := Character'Val (Ebx.L2);
20964       Vendor_ID( 4) := Character'Val (Ebx.H2);
20965       Vendor_ID( 5) := Character'Val (Edx.L1);
20966       Vendor_ID( 6) := Character'Val (Edx.H1);
20967       Vendor_ID( 7) := Character'Val (Edx.L2);
20968       Vendor_ID( 8) := Character'Val (Edx.H2);
20969       Vendor_ID( 9) := Character'Val (Ecx.L1);
20970       Vendor_ID(10) := Character'Val (Ecx.H1);
20971       Vendor_ID(11) := Character'Val (Ecx.L2);
20972       Vendor_ID(12) := Character'Val (Ecx.H2);
20974       --  return string
20975       return Vendor_ID;
20977    end Vendor_ID;
20979    -------------------------------
20980    --  Get processor signature  --
20981    -------------------------------
20983    function Signature return Processor_Signature is
20985       Result : Processor_Signature;
20986       --  processor signature returned
20988    begin
20990       --  execute CPUID, storing the results in the Result variable
20991       Asm (
20993            --  the assembler code
20994            "cpuid",    --  execute CPUID
20996            --  one is stored in eax
20997            --  processor signature returned in eax
20998            Inputs => Unsigned_32'Asm_input ("a", 1),
21000            --  eax is stored in Result
21001            Outputs => Processor_Signature'Asm_output ("=a", Result),
21003            --  tell compiler that ebx, ecx and edx are also destroyed
21004            Clobber => "ebx, ecx, edx");
21006       --  return processor signature
21007       return Result;
21009    end Signature;
21011    ------------------------------
21012    --  Get processor features  --
21013    ------------------------------
21015    function Features return Processor_Features is
21017       Result : Processor_Features;
21018       --  processor features returned
21020    begin
21022       --  execute CPUID, storing the results in the Result variable
21023       Asm (
21025            --  the assembler code
21026            "cpuid",    --  execute CPUID
21028            --  one stored in eax
21029            --  processor features returned in edx
21030            Inputs => Unsigned_32'Asm_input ("a", 1),
21032            --  edx is stored in Result
21033            Outputs => Processor_Features'Asm_output ("=d", Result),
21035            --  tell compiler that ebx and ecx are also destroyed
21036            Clobber => "ebx, ecx");
21038       --  return processor signature
21039       return Result;
21041    end Features;
21043 end Intel_CPU;
21044 @end smallexample
21045 @c END OF INLINE ASSEMBLER CHAPTER
21046 @c ===============================
21048 @ifset wnt
21049 @node Microsoft Windows Topics
21050 @chapter Microsoft Windows Topics
21051 @cindex Windows NT
21052 @cindex Windows 95
21053 @cindex Windows 98
21055 @noindent
21056 This chapter describes topics that are specific to the Microsoft Windows
21057 platforms (NT, 95 and 98).
21059 @menu
21060 * Using GNAT on Windows::
21061 * GNAT Setup Tool::
21062 * CONSOLE and WINDOWS subsystems::
21063 * Temporary Files::
21064 * Mixed-Language Programming on Windows::
21065 * Windows Calling Conventions::
21066 * Introduction to Dynamic Link Libraries (DLLs)::
21067 * Using DLLs with GNAT::
21068 * Building DLLs with GNAT::
21069 * GNAT and Windows Resources::
21070 * Debugging a DLL::
21071 * GNAT and COM/DCOM Objects::
21072 @end menu
21074 @node Using GNAT on Windows
21075 @section Using GNAT on Windows
21077 @noindent
21078 One of the strengths of the GNAT technology is that its tool set
21079 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
21080 @code{gdb} debugger, etc.) is used in the same way regardless of the
21081 platform.
21083 On Windows this tool set is complemented by a number of Microsoft-specific
21084 tools that have been provided to facilitate interoperability with Windows
21085 when this is required. With these tools:
21087 @itemize @bullet
21089 @item
21090 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
21091 subsystems.
21093 @item
21094 You can use any Dynamically Linked Library (DLL) in your Ada code (both
21095 relocatable and non-relocatable DLLs are supported).
21097 @item
21098 You can build Ada DLLs for use in other applications. These applications
21099 can be written in a language other than Ada (e.g., C, C++, etc). Again both
21100 relocatable and non-relocatable Ada DLLs are supported.
21102 @item
21103 You can include Windows resources in your Ada application.
21105 @item
21106 You can use or create COM/DCOM objects.
21107 @end itemize
21109 @noindent
21110 Immediately below are listed all known general GNAT-for-Windows restrictions.
21111 Other restrictions about specific features like Windows Resources and DLLs
21112 are listed in separate sections below.
21114 @itemize @bullet
21116 @item
21117 It is not possible to use @code{GetLastError} and @code{SetLastError}
21118 when tasking, protected records, or exceptions are used. In these
21119 cases, in order to implement Ada semantics, the GNAT run-time system
21120 calls certain Win32 routines that set the last error variable to 0 upon
21121 success. It should be possible to use @code{GetLastError} and
21122 @code{SetLastError} when tasking, protected record, and exception
21123 features are not used, but it is not guaranteed to work.
21124 @end itemize
21126 @node GNAT Setup Tool
21127 @section GNAT Setup Tool
21128 @cindex GNAT Setup Tool
21129 @cindex Setup Tool
21130 @cindex gnatreg
21132 @menu
21133 * Command-line arguments::
21134 * Creating a network installation of GNAT::
21135 * Registering and unregistering additional libraries::
21136 @end menu
21138 @noindent
21139 GNAT installation on Windows is using the Windows registry in order to
21140 locate proper executables and standard libraries. GNAT setup tool, called
21141 @code{gnatreg.exe}, is provided in order to display and modify GNAT-specific
21142 registry entries, allowing to create network GNAT installations, modify the
21143 locations of GNAT components, as well as register and unregister additional
21144 libraries for use with GNAT.
21146 @node Command-line arguments
21147 @subsection Command-line arguments
21149 @noindent
21150 @code{gnatreg [switches] [parameter]}
21152 @noindent
21153 Specifying no arguments causes gnatreg to display current configuration.
21155 @noindent
21156 The switches understood by gnatreg are:
21157 @table @asis
21158 @item  -h
21159        print the help message
21160 @item  -a
21161        add a standard library
21162 @item  -r
21163        remove a standard library
21164 @item  -f
21165        force creation of keys if they don't exist
21166 @item  -q
21167        be quiet/terse
21168 @end table
21170 @node Creating a network installation of GNAT
21171 @subsection Creating a network installation of GNAT
21173 @noindent
21174 Make sure the system on which GNAT is installed is accessible from the
21175 current machine.
21177 Use the command
21179 @code{@ @ @ gnatreg -f \\server\sharename\path}
21181 in order to setup the registry entries on a current machine.
21183 For example, if GNAT is installed in @file{\GNAT} directory of a share location
21184 called @file{c-drive} on a machine @file{LOKI}, the command that can be used on
21185 other machines to allow the remote use of GNAT is,
21187 @code{@ @ @ gnatreg -f \\loki\c-drive\gnat}
21189 Remember to also add @file{\\loki\c-drive\gnat\bin} in front of your PATH variable.
21191 Be aware that every compilation using the network installation results in the
21192 transfer of large amounts of data across the network and may cause serious
21193 performance penalty.
21195 @node Registering and unregistering additional libraries
21196 @subsection Registering and unregistering additional libraries
21198 @noindent
21199 To register a standard library use a command:
21201 @code{@ @ @ gnatreg -a <library_name>=<path>}
21203 For example:
21205 @code{@ @ @ gnatreg -a WIN32ADA=c:\Win32Ada}
21207 The libraries registered in this manner will be treated like standard libraries
21208 by the compiler (i.e. they don't have to be specified in -I and -l switches to
21209 various GNAT tools).
21211 To unregister a library, enter
21212 @code{   gnatreg -r <library_name>}
21214 e.g.,
21215 @code{   gnatreg -r WIN32ADA}
21217 @node CONSOLE and WINDOWS subsystems
21218 @section CONSOLE and WINDOWS subsystems
21219 @cindex CONSOLE Subsystem
21220 @cindex WINDOWS Subsystem
21221 @cindex -mwindows
21223 @noindent
21224 Under Windows there is two main subsystems. The @code{CONSOLE} subsystem
21225 (which is the default subsystem) will always create a console when
21226 launching the application. This is not something desirable when the
21227 application has a Windows GUI. To get rid of this console the
21228 application must be using the @code{WINDOWS} subsystem. To do so
21229 the @code{-mwindows} linker option must be specified.
21231 @smallexample
21232 $ gnatmake winprog -largs -mwindows
21233 @end smallexample
21235 @node Temporary Files
21236 @section Temporary Files
21237 @cindex Temporary files
21239 @noindent
21240 It is possible to control where temporary files gets created by setting
21241 the TMP environment variable. The file will be created:
21243 @itemize
21244 @item Under the directory pointed to by the TMP environment variable if
21245 this directory exists.
21247 @item Under c:\temp, if the TMP environment variable is not set (or not
21248 pointing to a directory) and if this directory exists.
21250 @item Under the current working directory otherwise.
21251 @end itemize
21253 @noindent
21254 This allows you to determine exactly where the temporary
21255 file will be created. This is particularly useful in networked
21256 environments where you may not have write access to some
21257 directories.
21259 @node Mixed-Language Programming on Windows
21260 @section Mixed-Language Programming on Windows
21262 @noindent
21263 Developing pure Ada applications on Windows is no different than on
21264 other GNAT-supported platforms. However, when developing or porting an
21265 application that contains a mix of Ada and C/C++, the choice of your
21266 Windows C/C++ development environment conditions your overall
21267 interoperability strategy.
21269 If you use @code{gcc} to compile the non-Ada part of your application,
21270 there are no Windows-specific restrictions that affect the overall
21271 interoperability with your Ada code. If you plan to use
21272 Microsoft tools (e.g. Microsoft Visual C/C++), you should be aware of
21273 the following limitations:
21275 @itemize @bullet
21276 @item
21277 You cannot link your Ada code with an object or library generated with
21278 Microsoft tools if these use the @code{.tls} section (Thread Local
21279 Storage section) since the GNAT linker does not yet support this section.
21281 @item
21282 You cannot link your Ada code with an object or library generated with
21283 Microsoft tools if these use I/O routines other than those provided in
21284 the Microsoft DLL: @code{msvcrt.dll}. This is because the GNAT run time
21285 uses the services of @code{msvcrt.dll} for its I/Os. Use of other I/O
21286 libraries can cause a conflict with @code{msvcrt.dll} services. For
21287 instance Visual C++ I/O stream routines conflict with those in
21288 @code{msvcrt.dll}.
21289 @end itemize
21291 @noindent
21292 If you do want to use the Microsoft tools for your non-Ada code and hit one
21293 of the above limitations, you have two choices:
21295 @enumerate
21296 @item
21297 Encapsulate your non Ada code in a DLL to be linked with your Ada
21298 application. In this case, use the Microsoft or whatever environment to
21299 build the DLL and use GNAT to build your executable
21300 (@pxref{Using DLLs with GNAT}).
21302 @item
21303 Or you can encapsulate your Ada code in a DLL to be linked with the
21304 other part of your application. In this case, use GNAT to build the DLL
21305 (@pxref{Building DLLs with GNAT}) and use the Microsoft or whatever
21306 environment to build your executable.
21307 @end enumerate
21309 @node Windows Calling Conventions
21310 @section Windows Calling Conventions
21311 @findex Stdcall
21312 @findex APIENTRY
21314 @menu
21315 * C Calling Convention::
21316 * Stdcall Calling Convention::
21317 * DLL Calling Convention::
21318 @end menu
21320 @noindent
21321 When a subprogram @code{F} (caller) calls a subprogram @code{G}
21322 (callee), there are several ways to push @code{G}'s parameters on the
21323 stack and there are several possible scenarios to clean up the stack
21324 upon @code{G}'s return. A calling convention is an agreed upon software
21325 protocol whereby the responsibilities between the caller (@code{F}) and
21326 the callee (@code{G}) are clearly defined. Several calling conventions
21327 are available for Windows:
21329 @itemize @bullet
21330 @item
21331 @code{C} (Microsoft defined)
21333 @item
21334 @code{Stdcall} (Microsoft defined)
21336 @item
21337 @code{DLL} (GNAT specific)
21338 @end itemize
21340 @node C Calling Convention
21341 @subsection @code{C} Calling Convention
21343 @noindent
21344 This is the default calling convention used when interfacing to C/C++
21345 routines compiled with either @code{gcc} or Microsoft Visual C++.
21347 In the @code{C} calling convention subprogram parameters are pushed on the
21348 stack by the caller from right to left. The caller itself is in charge of
21349 cleaning up the stack after the call. In addition, the name of a routine
21350 with @code{C} calling convention is mangled by adding a leading underscore.
21352 The name to use on the Ada side when importing (or exporting) a routine
21353 with @code{C} calling convention is the name of the routine. For
21354 instance the C function:
21356 @smallexample
21357 int get_val (long);
21358 @end smallexample
21360 @noindent
21361 should be imported from Ada as follows:
21363 @smallexample
21364 @group
21365 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21366 @b{pragma} Import (C, Get_Val, External_Name => "get_val");
21367 @end group
21368 @end smallexample
21370 @noindent
21371 Note that in this particular case the @code{External_Name} parameter could
21372 have been omitted since, when missing, this parameter is taken to be the
21373 name of the Ada entity in lower case. When the @code{Link_Name} parameter
21374 is missing, as in the above example, this parameter is set to be the
21375 @code{External_Name} with a leading underscore.
21377 When importing a variable defined in C, you should always use the @code{C}
21378 calling convention unless the object containing the variable is part of a
21379 DLL (in which case you should use the @code{DLL} calling convention,
21380 @pxref{DLL Calling Convention}).
21382 @node Stdcall Calling Convention
21383 @subsection @code{Stdcall} Calling Convention
21385 @noindent
21386 This convention, which was the calling convention used for Pascal
21387 programs, is used by Microsoft for all the routines in the Win32 API for
21388 efficiency reasons. It must be used to import any routine for which this
21389 convention was specified.
21391 In the @code{Stdcall} calling convention subprogram parameters are pushed
21392 on the stack by the caller from right to left. The callee (and not the
21393 caller) is in charge of cleaning the stack on routine exit. In addition,
21394 the name of a routine with @code{Stdcall} calling convention is mangled by
21395 adding a leading underscore (as for the @code{C} calling convention) and a
21396 trailing @code{@@}@code{@i{nn}}, where @i{nn} is the overall size (in
21397 bytes) of the parameters passed to the routine.
21399 The name to use on the Ada side when importing a C routine with a
21400 @code{Stdcall} calling convention is the name of the C routine. The leading
21401 underscore and trailing @code{@@}@code{@i{nn}} are added automatically by
21402 the compiler. For instance the Win32 function:
21404 @smallexample
21405 @b{APIENTRY} int get_val (long);
21406 @end smallexample
21408 @noindent
21409 should be imported from Ada as follows:
21411 @smallexample
21412 @group
21413 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21414 @b{pragma} Import (Stdcall, Get_Val);
21415 --  @i{On the x86 a long is 4 bytes, so the Link_Name is }"_get_val@@4"
21416 @end group
21417 @end smallexample
21419 @noindent
21420 As for the @code{C} calling convention, when the @code{External_Name}
21421 parameter is missing, it is taken to be the name of the Ada entity in lower
21422 case. If instead of writing the above import pragma you write:
21424 @smallexample
21425 @group
21426 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21427 @b{pragma} Import (Stdcall, Get_Val, External_Name => "retrieve_val");
21428 @end group
21429 @end smallexample
21431 @noindent
21432 then the imported routine is @code{_retrieve_val@@4}. However, if instead
21433 of specifying the @code{External_Name} parameter you specify the
21434 @code{Link_Name} as in the following example:
21436 @smallexample
21437 @group
21438 @b{function} Get_Val (V : Interfaces.C.long) @b{return} Interfaces.C.int;
21439 @b{pragma} Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
21440 @end group
21441 @end smallexample
21443 @noindent
21444 then the imported routine is @code{retrieve_val@@4}, that is, there is no
21445 trailing underscore but the appropriate @code{@@}@code{@i{nn}} is always
21446 added at the end of the @code{Link_Name} by the compiler.
21448 @noindent
21449 Note, that in some special cases a DLL's entry point name lacks a trailing
21450 @code{@@}@code{@i{nn}} while the exported name generated for a call has it.
21451 The @code{gnatdll} tool, which creates the import library for the DLL, is able
21452 to handle those cases (see the description of the switches in
21453 @pxref{Using gnatdll} section).
21455 @node DLL Calling Convention
21456 @subsection @code{DLL} Calling Convention
21458 @noindent
21459 This convention, which is GNAT-specific, must be used when you want to
21460 import in Ada a variables defined in a DLL. For functions and procedures
21461 this convention is equivalent to the @code{Stdcall} convention. As an
21462 example, if a DLL contains a variable defined as:
21464 @smallexample
21465 int my_var;
21466 @end smallexample
21468 @noindent
21469 then, to access this variable from Ada you should write:
21471 @smallexample
21472 @group
21473 My_Var : Interfaces.C.int;
21474 @b{pragma} Import (DLL, My_Var);
21475 @end group
21476 @end smallexample
21478 The remarks concerning the @code{External_Name} and @code{Link_Name}
21479 parameters given in the previous sections equally apply to the @code{DLL}
21480 calling convention.
21482 @node Introduction to Dynamic Link Libraries (DLLs)
21483 @section Introduction to Dynamic Link Libraries (DLLs)
21484 @findex DLL
21486 @noindent
21487 A Dynamically Linked Library (DLL) is a library that can be shared by
21488 several applications running under Windows. A DLL can contain any number of
21489 routines and variables.
21491 One advantage of DLLs is that you can change and enhance them without
21492 forcing all the applications that depend on them to be relinked or
21493 recompiled. However, you should be aware than all calls to DLL routines are
21494 slower since, as you will understand below, such calls are indirect.
21496 To illustrate the remainder of this section, suppose that an application
21497 wants to use the services of a DLL @file{API.dll}. To use the services
21498 provided by @file{API.dll} you must statically link against an import
21499 library which contains a jump table with an entry for each routine and
21500 variable exported by the DLL. In the Microsoft world this import library is
21501 called @file{API.lib}. When using GNAT this import library is called either
21502 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
21504 After you have statically linked your application with the import library
21505 and you run your application, here is what happens:
21507 @enumerate
21508 @item
21509 Your application is loaded into memory.
21511 @item
21512 The DLL @file{API.dll} is mapped into the address space of your
21513 application. This means that:
21515 @itemize @bullet
21516 @item
21517 The DLL will use the stack of the calling thread.
21519 @item
21520 The DLL will use the virtual address space of the calling process.
21522 @item
21523 The DLL will allocate memory from the virtual address space of the calling
21524 process.
21526 @item
21527 Handles (pointers) can be safely exchanged between routines in the DLL
21528 routines and routines in the application using the DLL.
21529 @end itemize
21531 @item
21532 The entries in the @file{libAPI.a} or @file{API.lib} jump table which is
21533 part of your application are initialized with the addresses of the routines
21534 and variables in @file{API.dll}.
21536 @item
21537 If present in @file{API.dll}, routines @code{DllMain} or
21538 @code{DllMainCRTStartup} are invoked. These routines typically contain
21539 the initialization code needed for the well-being of the routines and
21540 variables exported by the DLL.
21541 @end enumerate
21543 @noindent
21544 There is an additional point which is worth mentioning. In the Windows
21545 world there are two kind of DLLs: relocatable and non-relocatable
21546 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
21547 in the target application address space. If the addresses of two
21548 non-relocatable DLLs overlap and these happen to be used by the same
21549 application, a conflict will occur and the application will run
21550 incorrectly. Hence, when possible, it is always preferable to use and
21551 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
21552 supported by GNAT.
21554 As a side note, an interesting difference between Microsoft DLLs and
21555 Unix shared libraries, is the fact that on most Unix systems all public
21556 routines are exported by default in a Unix shared library, while under
21557 Windows the exported routines must be listed explicitly in a definition
21558 file (@pxref{The Definition File}).
21560 @node Using DLLs with GNAT
21561 @section Using DLLs with GNAT
21563 @menu
21564 * Creating an Ada Spec for the DLL Services::
21565 * Creating an Import Library::
21566 @end menu
21568 @noindent
21569 To use the services of a DLL, say @file{API.dll}, in your Ada application
21570 you must have:
21572 @enumerate
21573 @item
21574 The Ada spec for the routines and/or variables you want to access in
21575 @file{API.dll}. If not available this Ada spec must be built from the C/C++
21576 header files provided with the DLL.
21578 @item
21579 The import library (@file{libAPI.a} or @file{API.lib}). As previously
21580 mentioned an import library is a statically linked library containing the
21581 import table which will be filled at load time to point to the actual
21582 @file{API.dll} routines. Sometimes you don't have an import library for the
21583 DLL you want to use. The following sections will explain how to build one.
21585 @item
21586 The actual DLL, @file{API.dll}.
21587 @end enumerate
21589 @noindent
21590 Once you have all the above, to compile an Ada application that uses the
21591 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
21592 you simply issue the command
21594 @smallexample
21595 $ gnatmake my_ada_app -largs -lAPI
21596 @end smallexample
21598 @noindent
21599 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
21600 tells the GNAT linker to look first for a library named @file{API.lib}
21601 (Microsoft-style name) and if not found for a library named @file{libAPI.a}
21602 (GNAT-style name). Note that if the Ada package spec for @file{API.dll}
21603 contains the following pragma
21605 @smallexample
21606 @b{pragma} Linker_Options ("-lAPI");
21607 @end smallexample
21609 @noindent
21610 you do not have to add @code{-largs -lAPI} at the end of the @code{gnatmake}
21611 command.
21613 If any one of the items above is missing you will have to create it
21614 yourself. The following sections explain how to do so using as an
21615 example a fictitious DLL called @file{API.dll}.
21617 @node Creating an Ada Spec for the DLL Services
21618 @subsection Creating an Ada Spec for the DLL Services
21620 @noindent
21621 A DLL typically comes with a C/C++ header file which provides the
21622 definitions of the routines and variables exported by the DLL. The Ada
21623 equivalent of this header file is a package spec that contains definitions
21624 for the imported entities. If the DLL you intend to use does not come with
21625 an Ada spec you have to generate one such spec yourself. For example if
21626 the header file of @file{API.dll} is a file @file{api.h} containing the
21627 following two definitions:
21629 @smallexample
21630 @group
21631 @cartouche
21632 int some_var;
21633 int get (char *);
21634 @end cartouche
21635 @end group
21636 @end smallexample
21638 @noindent
21639 then the equivalent Ada spec could be:
21641 @smallexample
21642 @group
21643 @cartouche
21644 @b{with} Interfaces.C.Strings;
21645 @b{package} API @b{is}
21646    @b{use} Interfaces;
21648    Some_Var : C.int;
21649    @b{function} Get (Str : C.Strings.Chars_Ptr) @b{return} C.int;
21651 @b{private}
21652    @b{pragma} Import (C, Get);
21653    @b{pragma} Import (DLL, Some_Var);
21654 @b{end} API;
21655 @end cartouche
21656 @end group
21657 @end smallexample
21659 @noindent
21660 Note that a variable is @strong{always imported with a DLL convention}. A
21661 function can have @code{C}, @code{Stdcall} or @code{DLL} convention. For
21662 subprograms, the @code{DLL} convention is a synonym of @code{Stdcall}
21663 (@pxref{Windows Calling Conventions}).
21665 @node Creating an Import Library
21666 @subsection Creating an Import Library
21667 @cindex Import library
21669 @menu
21670 * The Definition File::
21671 * GNAT-Style Import Library::
21672 * Microsoft-Style Import Library::
21673 @end menu
21675 @noindent
21676 If a Microsoft-style import library @file{API.lib} or a GNAT-style
21677 import library @file{libAPI.a} is available with @file{API.dll} you
21678 can skip this section. Otherwise read on.
21680 @node The Definition File
21681 @subsubsection The Definition File
21682 @cindex Definition file
21683 @findex .def
21685 @noindent
21686 As previously mentioned, and unlike Unix systems, the list of symbols
21687 that are exported from a DLL must be provided explicitly in Windows.
21688 The main goal of a definition file is precisely that: list the symbols
21689 exported by a DLL. A definition file (usually a file with a @code{.def}
21690 suffix) has the following structure:
21692 @smallexample
21693 @group
21694 @cartouche
21695 [LIBRARY @i{name}]
21696 [DESCRIPTION @i{string}]
21697 EXPORTS
21698    @i{symbol1}
21699    @i{symbol2}
21700    ...
21701 @end cartouche
21702 @end group
21703 @end smallexample
21705 @table @code
21706 @item LIBRARY @i{name}
21707 This section, which is optional, gives the name of the DLL.
21709 @item DESCRIPTION @i{string}
21710 This section, which is optional, gives a description string that will be
21711 embedded in the import library.
21713 @item EXPORTS
21714 This section gives the list of exported symbols (procedures, functions or
21715 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
21716 section of @file{API.def} looks like:
21718 @smallexample
21719 @group
21720 @cartouche
21721 EXPORTS
21722    some_var
21723    get
21724 @end cartouche
21725 @end group
21726 @end smallexample
21727 @end table
21729 @noindent
21730 Note that you must specify the correct suffix (@code{@@}@code{@i{nn}})
21731 (@pxref{Windows Calling Conventions}) for a Stdcall
21732 calling convention function in the exported symbols list.
21734 @noindent
21735 There can actually be other sections in a definition file, but these
21736 sections are not relevant to the discussion at hand.
21738 @node GNAT-Style Import Library
21739 @subsubsection GNAT-Style Import Library
21741 @noindent
21742 To create a static import library from @file{API.dll} with the GNAT tools
21743 you should proceed as follows:
21745 @enumerate
21746 @item
21747 Create the definition file @file{API.def} (@pxref{The Definition File}).
21748 For that use the @code{dll2def} tool as follows:
21750 @smallexample
21751 $ dll2def API.dll > API.def
21752 @end smallexample
21754 @noindent
21755 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
21756 to standard output the list of entry points in the DLL. Note that if
21757 some routines in the DLL have the @code{Stdcall} convention
21758 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@i{nn}
21759 suffix then you'll have to edit @file{api.def} to add it.
21761 @noindent
21762 Here are some hints to find the right @code{@@}@i{nn} suffix.
21764 @enumerate
21765 @item
21766 If you have the Microsoft import library (.lib), it is possible to get
21767 the right symbols by using Microsoft @code{dumpbin} tool (see the
21768 corresponding Microsoft documentation for further details).
21770 @smallexample
21771 $ dumpbin /exports api.lib
21772 @end smallexample
21774 @item
21775 If you have a message about a missing symbol at link time the compiler
21776 tells you what symbol is expected. You just have to go back to the
21777 definition file and add the right suffix.
21778 @end enumerate
21780 @item
21781 Build the import library @code{libAPI.a}, using @code{gnatdll}
21782 (@pxref{Using gnatdll}) as follows:
21784 @smallexample
21785 $ gnatdll -e API.def -d API.dll
21786 @end smallexample
21788 @noindent
21789 @code{gnatdll} takes as input a definition file @file{API.def} and the
21790 name of the DLL containing the services listed in the definition file
21791 @file{API.dll}. The name of the static import library generated is
21792 computed from the name of the definition file as follows: if the
21793 definition file name is @i{xyz}@code{.def}, the import library name will
21794 be @code{lib}@i{xyz}@code{.a}. Note that in the previous example option
21795 @code{-e} could have been removed because the name of the definition
21796 file (before the "@code{.def}" suffix) is the same as the name of the
21797 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
21798 @end enumerate
21800 @node Microsoft-Style Import Library
21801 @subsubsection Microsoft-Style Import Library
21803 @noindent
21804 With GNAT you can either use a GNAT-style or Microsoft-style import
21805 library. A Microsoft import library is needed only if you plan to make an
21806 Ada DLL available to applications developed with Microsoft
21807 tools (@pxref{Mixed-Language Programming on Windows}).
21809 To create a Microsoft-style import library for @file{API.dll} you
21810 should proceed as follows:
21812 @enumerate
21813 @item
21814 Create the definition file @file{API.def} from the DLL. For this use either
21815 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
21816 tool (see the corresponding Microsoft documentation for further details).
21818 @item
21819 Build the actual import library using Microsoft's @code{lib} utility:
21821 @smallexample
21822 $ lib -machine:IX86 -def:API.def -out:API.lib
21823 @end smallexample
21825 @noindent
21826 If you use the above command the definition file @file{API.def} must
21827 contain a line giving the name of the DLL:
21829 @smallexample
21830 LIBRARY      "API"
21831 @end smallexample
21833 @noindent
21834 See the Microsoft documentation for further details about the usage of
21835 @code{lib}.
21836 @end enumerate
21838 @node Building DLLs with GNAT
21839 @section Building DLLs with GNAT
21840 @cindex DLLs, building
21842 @menu
21843 * Limitations When Using Ada DLLs from Ada::
21844 * Exporting Ada Entities::
21845 * Ada DLLs and Elaboration::
21846 * Ada DLLs and Finalization::
21847 * Creating a Spec for Ada DLLs::
21848 * Creating the Definition File::
21849 * Using gnatdll::
21850 @end menu
21852 @noindent
21853 This section explains how to build DLLs containing Ada code. These DLLs
21854 will be referred to as Ada DLLs in the remainder of this section.
21856 The steps required to build an Ada DLL that is to be used by Ada as well as
21857 non-Ada applications are as follows:
21859 @enumerate
21860 @item
21861 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
21862 @code{Stdcall} calling convention to avoid any Ada name mangling for the
21863 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
21864 skip this step if you plan to use the Ada DLL only from Ada applications.
21866 @item
21867 Your Ada code must export an initialization routine which calls the routine
21868 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
21869 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
21870 routine exported by the Ada DLL must be invoked by the clients of the DLL
21871 to initialize the DLL.
21873 @item
21874 When useful, the DLL should also export a finalization routine which calls
21875 routine @code{adafinal} generated by @code{gnatbind} to perform the
21876 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
21877 The finalization routine exported by the Ada DLL must be invoked by the
21878 clients of the DLL when the DLL services are no further needed.
21880 @item
21881 You must provide a spec for the services exported by the Ada DLL in each
21882 of the programming languages to which you plan to make the DLL available.
21884 @item
21885 You must provide a definition file listing the exported entities
21886 (@pxref{The Definition File}).
21888 @item
21889 Finally you must use @code{gnatdll} to produce the DLL and the import
21890 library (@pxref{Using gnatdll}).
21891 @end enumerate
21893 @node Limitations When Using Ada DLLs from Ada
21894 @subsection Limitations When Using Ada DLLs from Ada
21896 @noindent
21897 When using Ada DLLs from Ada applications there is a limitation users
21898 should be aware of. Because on Windows the GNAT run time is not in a DLL of
21899 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
21900 each Ada DLL includes the services of the GNAT run time that are necessary
21901 to the Ada code inside the DLL. As a result, when an Ada program uses an
21902 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
21903 one in the main program.
21905 It is therefore not possible to exchange GNAT run-time objects between the
21906 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
21907 handles (e.g. @code{Text_IO.File_Type}), tasks types, protected objects
21908 types, etc.
21910 It is completely safe to exchange plain elementary, array or record types,
21911 Windows object handles, etc.
21913 @node Exporting Ada Entities
21914 @subsection Exporting Ada Entities
21915 @cindex Export table
21917 @noindent
21918 Building a DLL is a way to encapsulate a set of services usable from any
21919 application. As a result, the Ada entities exported by a DLL should be
21920 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
21921 any Ada name mangling. Please note that the @code{Stdcall} convention
21922 should only be used for subprograms, not for variables. As an example here
21923 is an Ada package @code{API}, spec and body, exporting two procedures, a
21924 function, and a variable:
21926 @smallexample
21927 @group
21928 @cartouche
21929 @b{with} Interfaces.C; @b{use} Interfaces;
21930 @b{package} API @b{is}
21931    Count : C.int := 0;
21932    @b{function} Factorial (Val : C.int) @b{return} C.int;
21934    @b{procedure} Initialize_API;
21935    @b{procedure} Finalize_API;
21936    --  @i{Initialization & Finalization routines. More in the next section.}
21937 @b{private}
21938    @b{pragma} Export (C, Initialize_API);
21939    @b{pragma} Export (C, Finalize_API);
21940    @b{pragma} Export (C, Count);
21941    @b{pragma} Export (C, Factorial);
21942 @b{end} API;
21943 @end cartouche
21944 @end group
21945 @end smallexample
21947 @smallexample
21948 @group
21949 @cartouche
21950 @b{package body} API @b{is}
21951    @b{function} Factorial (Val : C.int) @b{return} C.int @b{is}
21952       Fact : C.int := 1;
21953    @b{begin}
21954       Count := Count + 1;
21955       @b{for} K @b{in} 1 .. Val @b{loop}
21956          Fact := Fact * K;
21957       @b{end loop};
21958       @b{return} Fact;
21959    @b{end} Factorial;
21961    @b{procedure} Initialize_API @b{is}
21962       @b{procedure} Adainit;
21963       @b{pragma} Import (C, Adainit);
21964    @b{begin}
21965       Adainit;
21966    @b{end} Initialize_API;
21968    @b{procedure} Finalize_API @b{is}
21969       @b{procedure} Adafinal;
21970       @b{pragma} Import (C, Adafinal);
21971    @b{begin}
21972       Adafinal;
21973    @b{end} Finalize_API;
21974 @b{end} API;
21975 @end cartouche
21976 @end group
21977 @end smallexample
21979 @noindent
21980 If the Ada DLL you are building will only be used by Ada applications
21981 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
21982 convention. As an example, the previous package could be written as
21983 follows:
21985 @smallexample
21986 @group
21987 @cartouche
21988 @b{package} API @b{is}
21989    Count : Integer := 0;
21990    @b{function} Factorial (Val : Integer) @b{return} Integer;
21992    @b{procedure} Initialize_API;
21993    @b{procedure} Finalize_API;
21994    --  @i{Initialization and Finalization routines.}
21995 @b{end} API;
21996 @end cartouche
21997 @end group
21998 @end smallexample
22000 @smallexample
22001 @group
22002 @cartouche
22003 @b{package body} API @b{is}
22004    @b{function} Factorial (Val : Integer) @b{return} Integer @b{is}
22005       Fact : Integer := 1;
22006    @b{begin}
22007       Count := Count + 1;
22008       @b{for} K @b{in} 1 .. Val @b{loop}
22009          Fact := Fact * K;
22010       @b{end loop};
22011       @b{return} Fact;
22012       @b{end} Factorial;
22014    ...
22015    --  @i{The remainder of this package body is unchanged.}
22016 @b{end} API;
22017 @end cartouche
22018 @end group
22019 @end smallexample
22021 @noindent
22022 Note that if you do not export the Ada entities with a @code{C} or
22023 @code{Stdcall} convention you will have to provide the mangled Ada names
22024 in the definition file of the Ada DLL
22025 (@pxref{Creating the Definition File}).
22027 @node Ada DLLs and Elaboration
22028 @subsection Ada DLLs and Elaboration
22029 @cindex DLLs and elaboration
22031 @noindent
22032 The DLL that you are building contains your Ada code as well as all the
22033 routines in the Ada library that are needed by it. The first thing a
22034 user of your DLL must do is elaborate the Ada code
22035 (@pxref{Elaboration Order Handling in GNAT}).
22037 To achieve this you must export an initialization routine
22038 (@code{Initialize_API} in the previous example), which must be invoked
22039 before using any of the DLL services. This elaboration routine must call
22040 the Ada elaboration routine @code{adainit} generated by the GNAT binder
22041 (@pxref{Binding with Non-Ada Main Programs}). See the body of
22042 @code{Initialize_Api} for an example. Note that the GNAT binder is
22043 automatically invoked during the DLL build process by the @code{gnatdll}
22044 tool (@pxref{Using gnatdll}).
22046 When a DLL is loaded, Windows systematically invokes a routine called
22047 @code{DllMain}. It would therefore be possible to call @code{adainit}
22048 directly from @code{DllMain} without having to provide an explicit
22049 initialization routine. Unfortunately, it is not possible to call
22050 @code{adainit} from the @code{DllMain} if your program has library level
22051 tasks because access to the @code{DllMain} entry point is serialized by
22052 the system (that is, only a single thread can execute "through" it at a
22053 time), which means that the GNAT run time will deadlock waiting for the
22054 newly created task to complete its initialization.
22056 @node Ada DLLs and Finalization
22057 @subsection Ada DLLs and Finalization
22058 @cindex DLLs and finalization
22060 @noindent
22061 When the services of an Ada DLL are no longer needed, the client code should
22062 invoke the DLL finalization routine, if available. The DLL finalization
22063 routine is in charge of releasing all resources acquired by the DLL. In the
22064 case of the Ada code contained in the DLL, this is achieved by calling
22065 routine @code{adafinal} generated by the GNAT binder
22066 (@pxref{Binding with Non-Ada Main Programs}).
22067 See the body of @code{Finalize_Api} for an
22068 example. As already pointed out the GNAT binder is automatically invoked
22069 during the DLL build process by the @code{gnatdll} tool
22070 (@pxref{Using gnatdll}).
22072 @code{-g}
22073 @cindex @code{-g} (@code{gnatdll})
22075 Generate debugging information. This information is stored in the object
22076 file and copied from there to the final DLL file by the linker,
22077 where it can be read by the debugger. You must use the
22078 @code{-g} switch if you plan on using the debugger or the symbolic
22079 stack traceback.
22081 @node Creating a Spec for Ada DLLs
22082 @subsection Creating a Spec for Ada DLLs
22084 @noindent
22085 To use the services exported by the Ada DLL from another programming
22086 language (e.g. C), you have to translate the specs of the exported Ada
22087 entities in that language. For instance in the case of @code{API.dll},
22088 the corresponding C header file could look like:
22090 @smallexample
22091 @group
22092 @cartouche
22093 extern int *__imp__count;
22094 #define count (*__imp__count)
22095 int factorial (int);
22096 @end cartouche
22097 @end group
22098 @end smallexample
22100 @noindent
22101 It is important to understand that when building an Ada DLL to be used by
22102 other Ada applications, you need two different specs for the packages
22103 contained in the DLL: one for building the DLL and the other for using
22104 the DLL. This is because the @code{DLL} calling convention is needed to
22105 use a variable defined in a DLL, but when building the DLL, the variable
22106 must have either the @code{Ada} or @code{C} calling convention. As an
22107 example consider a DLL comprising the following package @code{API}:
22109 @smallexample
22110 @group
22111 @cartouche
22112 @b{package} API @b{is}
22113    Count : Integer := 0;
22114    ...
22115    --  @i{Remainder of the package omitted.}
22116 @b{end} API;
22117 @end cartouche
22118 @end group
22119 @end smallexample
22121 @noindent
22122 After producing a DLL containing package @code{API}, the spec that
22123 must be used to import @code{API.Count} from Ada code outside of the
22124 DLL is:
22126 @smallexample
22127 @group
22128 @cartouche
22129 @b{package} API @b{is}
22130    Count : Integer;
22131    @b{pragma} Import (DLL, Count);
22132 @b{end} API;
22133 @end cartouche
22134 @end group
22135 @end smallexample
22137 @node Creating the Definition File
22138 @subsection Creating the Definition File
22140 @noindent
22141 The definition file is the last file needed to build the DLL. It lists
22142 the exported symbols. As an example, the definition file for a DLL
22143 containing only package @code{API} (where all the entities are exported
22144 with a @code{C} calling convention) is:
22146 @smallexample
22147 @group
22148 @cartouche
22149 EXPORTS
22150     count
22151     factorial
22152     finalize_api
22153     initialize_api
22154 @end cartouche
22155 @end group
22156 @end smallexample
22158 @noindent
22159 If the @code{C} calling convention is missing from package @code{API},
22160 then the definition file contains the mangled Ada names of the above
22161 entities, which in this case are:
22163 @smallexample
22164 @group
22165 @cartouche
22166 EXPORTS
22167     api__count
22168     api__factorial
22169     api__finalize_api
22170     api__initialize_api
22171 @end cartouche
22172 @end group
22173 @end smallexample
22175 @node Using gnatdll
22176 @subsection Using @code{gnatdll}
22177 @findex gnatdll
22179 @menu
22180 * gnatdll Example::
22181 * gnatdll behind the Scenes::
22182 * Using dlltool::
22183 @end menu
22185 @noindent
22186 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
22187 and non-Ada sources that make up your DLL have been compiled.
22188 @code{gnatdll} is actually in charge of two distinct tasks: build the
22189 static import library for the DLL and the actual DLL. The form of the
22190 @code{gnatdll} command is
22192 @smallexample
22193 @cartouche
22194 $ gnatdll [@var{switches}] @var{list-of-files} [-largs @var{opts}]
22195 @end cartouche
22196 @end smallexample
22198 @noindent
22199 where @i{list-of-files} is a list of ALI and object files. The object
22200 file list must be the exact list of objects corresponding to the non-Ada
22201 sources whose services are to be included in the DLL. The ALI file list
22202 must be the exact list of ALI files for the corresponding Ada sources
22203 whose services are to be included in the DLL. If @i{list-of-files} is
22204 missing, only the static import library is generated.
22206 @noindent
22207 You may specify any of the following switches to @code{gnatdll}:
22209 @table @code
22210 @item -a[@var{address}]
22211 @cindex @code{-a} (@code{gnatdll})
22212 Build a non-relocatable DLL at @var{address}. If @var{address} is not
22213 specified the default address @var{0x11000000} will be used. By default,
22214 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
22215 advise the reader to build relocatable DLL.
22217 @item -b @var{address}
22218 @cindex @code{-b} (@code{gnatdll})
22219 Set the relocatable DLL base address. By default the address is
22220 @var{0x11000000}.
22222 @item -d @var{dllfile}
22223 @cindex @code{-d} (@code{gnatdll})
22224 @var{dllfile} is the name of the DLL. This switch must be present for
22225 @code{gnatdll} to do anything. The name of the generated import library is
22226 obtained algorithmically from @var{dllfile} as shown in the following
22227 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
22228 @code{libxyz.a}. The name of the definition file to use (if not specified
22229 by option @code{-e}) is obtained algorithmically from @var{dllfile} as shown in
22230 the following example: if @var{dllfile} is @code{xyz.dll}, the definition
22231 file used is @code{xyz.def}.
22233 @item -e @var{deffile}
22234 @cindex @code{-e} (@code{gnatdll})
22235 @var{deffile} is the name of the definition file.
22237 @item -h
22238 @cindex @code{-h} (@code{gnatdll})
22239 Help mode. Displays @code{gnatdll} switch usage information.
22241 @item -Idir
22242 Direct @code{gnatdll} to search the @var{dir} directory for source and
22243 object files needed to build the DLL.
22244 (@pxref{Search Paths and the Run-Time Library (RTL)}).
22246 @item -k
22247 Removes the @code{@@}@i{nn} suffix from the import library's exported
22248 names. You must specified this option if you want to use a
22249 @code{Stdcall} function in a DLL for which the @code{@@}@i{nn} suffix
22250 has been removed. This is the case for most of the Windows NT DLL for
22251 example. This option has no effect when @code{-n} option is specified.
22253 @item -l @var{file}
22254 @cindex @code{-l} (@code{gnatdll})
22255 The list of ALI and object files used to build the DLL are listed in
22256 @var{file}, instead of being given in the command line. Each line in
22257 @var{file} contains the name of an ALI or object file.
22259 @item -n
22260 @cindex @code{-n} (@code{gnatdll})
22261 No Import. Do not create the import library.
22263 @item -q
22264 @cindex @code{-q} (@code{gnatdll})
22265 Quiet mode. Do not display unnecessary messages.
22267 @item -v
22268 @cindex @code{-v} (@code{gnatdll})
22269 Verbose mode. Display extra information.
22271 @item -largs @var{opts}
22272 @cindex @code{-largs} (@code{gnatdll})
22273 Linker options. Pass @var{opts} to the linker.
22274 @end table
22276 @node gnatdll Example
22277 @subsubsection @code{gnatdll} Example
22279 @noindent
22280 As an example the command to build a relocatable DLL from @file{api.adb}
22281 once @file{api.adb} has been compiled and @file{api.def} created is
22283 @smallexample
22284 $ gnatdll -d api.dll api.ali
22285 @end smallexample
22287 @noindent
22288 The above command creates two files: @file{libapi.a} (the import
22289 library) and @file{api.dll} (the actual DLL). If you want to create
22290 only the DLL, just type:
22292 @smallexample
22293 $ gnatdll -d api.dll -n api.ali
22294 @end smallexample
22296 @noindent
22297 Alternatively if you want to create just the import library, type:
22299 @smallexample
22300 $ gnatdll -d api.dll
22301 @end smallexample
22303 @node gnatdll behind the Scenes
22304 @subsubsection @code{gnatdll} behind the Scenes
22306 @noindent
22307 This section details the steps involved in creating a DLL. @code{gnatdll}
22308 does these steps for you. Unless you are interested in understanding what
22309 goes on behind the scenes, you should skip this section.
22311 We use the previous example of a DLL containing the Ada package @code{API},
22312 to illustrate the steps necessary to build a DLL. The starting point is a
22313 set of objects that will make up the DLL and the corresponding ALI
22314 files. In the case of this example this means that @file{api.o} and
22315 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
22316 the following:
22318 @enumerate
22319 @item
22320 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
22321 the information necessary to generate relocation information for the
22322 DLL.
22324 @smallexample
22325 @group
22326 $ gnatbind -n api
22327 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
22328 @end group
22329 @end smallexample
22331 @noindent
22332 In addition to the base file, the @code{gnatlink} command generates an
22333 output file @file{api.jnk} which can be discarded. The @code{-mdll} switch
22334 asks @code{gnatlink} to generate the routines @code{DllMain} and
22335 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
22336 is loaded into memory.
22338 @item
22339 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
22340 export table (@file{api.exp}). The export table contains the relocation
22341 information in a form which can be used during the final link to ensure
22342 that the Windows loader is able to place the DLL anywhere in memory.
22344 @smallexample
22345 @group
22346 $ dlltool --dllname api.dll --def api.def --base-file api.base \
22347           --output-exp api.exp
22348 @end group
22349 @end smallexample
22351 @item
22352 @code{gnatdll} builds the base file using the new export table. Note that
22353 @code{gnatbind} must be called once again since the binder generated file
22354 has been deleted during the previous call to @code{gnatlink}.
22356 @smallexample
22357 @group
22358 $ gnatbind -n api
22359 $ gnatlink api -o api.jnk api.exp -mdll
22360       -Wl,--base-file,api.base
22361 @end group
22362 @end smallexample
22364 @item
22365 @code{gnatdll} builds the new export table using the new base file and
22366 generates the DLL import library @file{libAPI.a}.
22368 @smallexample
22369 @group
22370 $ dlltool --dllname api.dll --def api.def --base-file api.base \
22371           --output-exp api.exp --output-lib libAPI.a
22372 @end group
22373 @end smallexample
22375 @item
22376 Finally @code{gnatdll} builds the relocatable DLL using the final export
22377 table.
22379 @smallexample
22380 @group
22381 $ gnatbind -n api
22382 $ gnatlink api api.exp -o api.dll -mdll
22383 @end group
22384 @end smallexample
22385 @end enumerate
22387 @node Using dlltool
22388 @subsubsection Using @code{dlltool}
22390 @noindent
22391 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
22392 DLLs and static import libraries. This section summarizes the most
22393 common @code{dlltool} switches. The form of the @code{dlltool} command
22396 @smallexample
22397 $ dlltool [@var{switches}]
22398 @end smallexample
22400 @noindent
22401 @code{dlltool} switches include:
22403 @table @code
22404 @item --base-file @var{basefile}
22405 Read the base file @var{basefile} generated by the linker. This switch
22406 is used to create a relocatable DLL.
22408 @item --def @var{deffile}
22409 Read the definition file.
22411 @item --dllname @var{name}
22412 Gives the name of the DLL. This switch is used to embed the name of the
22413 DLL in the static import library generated by @code{dlltool} with switch
22414 @code{--output-lib}.
22416 @item -k
22417 Kill @code{@@}@i{nn} from exported names
22418 (@pxref{Windows Calling Conventions}
22419 for a discussion about @code{Stdcall}-style symbols.
22421 @item --help
22422 Prints the @code{dlltool} switches with a concise description.
22424 @item --output-exp @var{exportfile}
22425 Generate an export file @var{exportfile}. The export file contains the
22426 export table (list of symbols in the DLL) and is used to create the DLL.
22428 @item --output-lib @i{libfile}
22429 Generate a static import library @var{libfile}.
22431 @item -v
22432 Verbose mode.
22434 @item --as @i{assembler-name}
22435 Use @i{assembler-name} as the assembler. The default is @code{as}.
22436 @end table
22438 @node GNAT and Windows Resources
22439 @section GNAT and Windows Resources
22440 @cindex Resources, windows
22442 @menu
22443 * Building Resources::
22444 * Compiling Resources::
22445 * Using Resources::
22446 * Limitations::
22447 @end menu
22449 @noindent
22450 Resources are an easy way to add Windows specific objects to your
22451 application. The objects that can be added as resources include:
22453 @itemize @bullet
22454 @item
22455 menus
22457 @item
22458 accelerators
22460 @item
22461 dialog boxes
22463 @item
22464 string tables
22466 @item
22467 bitmaps
22469 @item
22470 cursors
22472 @item
22473 icons
22475 @item
22476 fonts
22477 @end itemize
22479 @noindent
22480 This section explains how to build, compile and use resources.
22482 @node Building Resources
22483 @subsection Building Resources
22484 @cindex Resources, building
22486 @noindent
22487 A resource file is an ASCII file. By convention resource files have an
22488 @file{.rc} extension.
22489 The easiest way to build a resource file is to use Microsoft tools
22490 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
22491 @code{dlgedit.exe} to build dialogs.
22492 It is always possible to build an @file{.rc} file yourself by writing a
22493 resource script.
22495 It is not our objective to explain how to write a resource file. A
22496 complete description of the resource script language can be found in the
22497 Microsoft documentation.
22499 @node Compiling Resources
22500 @subsection Compiling Resources
22501 @findex rc
22502 @findex rcl
22503 @findex res2coff
22504 @cindex Resources, compiling
22506 @noindent
22507 This section describes how to build a GNAT-compatible (COFF) object file
22508 containing the resources. This is done using the Resource Compiler
22509 @code{rcl} as follows:
22511 @smallexample
22512 $ rcl -i myres.rc -o myres.o
22513 @end smallexample
22515 @noindent
22516 By default @code{rcl} will run @code{gcc} to preprocess the @file{.rc}
22517 file. You can specify an alternate preprocessor (usually named
22518 @file{cpp.exe}) using the @code{rcl} @code{-cpp} parameter. A list of
22519 all possible options may be obtained by entering the command @code{rcl}
22520 with no parameters.
22522 It is also possible to use the Microsoft resource compiler @code{rc.exe}
22523 to produce a @file{.res} file (binary resource file). See the
22524 corresponding Microsoft documentation for further details. In this case
22525 you need to use @code{res2coff} to translate the @file{.res} file to a
22526 GNAT-compatible object file as follows:
22528 @smallexample
22529 $ res2coff -i myres.res -o myres.o
22530 @end smallexample
22532 @node Using Resources
22533 @subsection Using Resources
22534 @cindex Resources, using
22536 @noindent
22537 To include the resource file in your program just add the
22538 GNAT-compatible object file for the resource(s) to the linker
22539 arguments. With @code{gnatmake} this is done by using the @code{-largs}
22540 option:
22542 @smallexample
22543 $ gnatmake myprog -largs myres.o
22544 @end smallexample
22546 @node Limitations
22547 @subsection Limitations
22548 @cindex Resources, limitations
22550 @noindent
22551 In this section we describe the current limitations together with
22552 suggestions for workarounds.
22554 @itemize @bullet
22555 @item
22556 @code{rcl} does not handle the @code{RCINCLUDE} directive.
22558 Workaround: replace @code{RCINCLUDE} by an @code{#include} directive.
22560 @item
22561 @code{rcl} does not handle the brackets as block delimiters.
22563 Workaround: replace character '@{' by @code{BEGIN} and '@}' by
22564 @code{END}. Note that Microsoft's @code{rc} handles both forms of block
22565 delimiters.
22567 @item
22568 @code{rcl} does not handle @code{TypeLib} resources. This type of
22569 resource is used to build COM, DCOM or ActiveX objects.
22571 Workaround: use @code{rc}, the Microsoft resource compiler.
22573 @item
22574 It is not possible to use @code{strip} to remove the debugging symbols
22575 from a program with resources.
22577 Workaround: use linker option @code{-s} to strip debugging symbols from
22578 the final executable.
22579 @end itemize
22581 @node Debugging a DLL
22582 @section Debugging a DLL
22583 @cindex DLL debugging
22585 @menu
22586 * The Program and the DLL Are Built with GCC/GNAT::
22587 * The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT::
22588 @end menu
22590 @noindent
22591 Debugging a DLL is similar to debugging a standard program. But
22592 we have to deal with two different executable parts: the DLL and the
22593 program that uses it. We have the following four possibilities:
22595 @enumerate 1
22596 @item
22597 The program and the DLL are built with @code{GCC/GNAT}.
22598 @item
22599 The program is built with foreign tools and the DLL is built with
22600 @code{GCC/GNAT}.
22601 @item
22602 The program is built with @code{GCC/GNAT} and the DLL is built with
22603 foreign tools.
22604 @item
22605 @end enumerate
22607 @noindent
22608 In this section we address only cases one and two above.
22609 There is no point in trying to debug
22610 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
22611 information in it. To do so you must use a debugger compatible with the
22612 tools suite used to build the DLL.
22614 @node The Program and the DLL Are Built with GCC/GNAT
22615 @subsection The Program and the DLL Are Built with GCC/GNAT
22617 @noindent
22618 This is the simplest case. Both the DLL and the program have @code{GDB}
22619 compatible debugging information. It is then possible to break anywhere in
22620 the process. Let's suppose here that the main procedure is named
22621 @code{ada_main} and that in the DLL there is an entry point named
22622 @code{ada_dll}.
22624 @noindent
22625 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
22626 program must have been built with the debugging information (see GNAT -g
22627 switch). Here are the step-by-step instructions for debugging it:
22629 @enumerate 1
22630 @item Launch @code{GDB} on the main program.
22632 @smallexample
22633 $ gdb -nw ada_main
22634 @end smallexample
22636 @item Break on the main procedure and run the program.
22638 @smallexample
22639 (gdb) break ada_main
22640 (gdb) run
22641 @end smallexample
22643 @noindent
22644 This step is required to be able to set a breakpoint inside the DLL. As long
22645 as the program is not run, the DLL is not loaded. This has the
22646 consequence that the DLL debugging information is also not loaded, so it is not
22647 possible to set a breakpoint in the DLL.
22649 @item Set a breakpoint inside the DLL
22651 @smallexample
22652 (gdb) break ada_dll
22653 (gdb) run
22654 @end smallexample
22656 @end enumerate
22658 @noindent
22659 At this stage a breakpoint is set inside the DLL. From there on
22660 you can use the standard approach to debug the whole program
22661 (@pxref{Running and Debugging Ada Programs}).
22663 @node The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
22664 @subsection The Program Is Built with Some Foreign Tools and the DLL Is Built with GCC/GNAT
22666 @menu
22667 * Debugging the DLL Directly::
22668 * Attaching to a Running Process::
22669 @end menu
22671 @noindent
22672 In this case things are slightly more complex because it is not possible to
22673 start the main program and then break at the beginning to load the DLL and the
22674 associated DLL debugging information. It is not possible to break at the
22675 beginning of the program because there is no @code{GDB} debugging information,
22676 and therefore there is no direct way of getting initial control. This
22677 section addresses this issue by describing some methods that can be used
22678 to break somewhere in the DLL to debug it.
22680 @noindent
22681 First suppose that the main procedure is named @code{main} (this is for
22682 example some C code built with Microsoft Visual C) and that there is a
22683 DLL named @code{test.dll} containing an Ada entry point named
22684 @code{ada_dll}.
22686 @noindent
22687 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
22688 been built with debugging information (see GNAT -g option).
22690 @node Debugging the DLL Directly
22691 @subsubsection Debugging the DLL Directly
22693 @enumerate 1
22694 @item
22695 Launch the debugger on the DLL.
22697 @smallexample
22698 $ gdb -nw test.dll
22699 @end smallexample
22701 @item Set a breakpoint on a DLL subroutine.
22703 @smallexample
22704 (gdb) break ada_dll
22705 @end smallexample
22707 @item
22708 Specify the executable file to @code{GDB}.
22710 @smallexample
22711 (gdb) exec-file main.exe
22712 @end smallexample
22714 @item
22715 Run the program.
22717 @smallexample
22718 (gdb) run
22719 @end smallexample
22721 @noindent
22722 This will run the program until it reaches the breakpoint that has been
22723 set. From that point you can use the standard way to debug a program
22724 as described in (@pxref{Running and Debugging Ada Programs}).
22726 @end enumerate
22728 @noindent
22729 It is also possible to debug the DLL by attaching to a running process.
22731 @node Attaching to a Running Process
22732 @subsubsection Attaching to a Running Process
22733 @cindex DLL debugging, attach to process
22735 @noindent
22736 With @code{GDB} it is always possible to debug a running process by
22737 attaching to it. It is possible to debug a DLL this way. The limitation
22738 of this approach is that the DLL must run long enough to perform the
22739 attach operation. It may be useful for instance to insert a time wasting
22740 loop in the code of the DLL to meet this criterion.
22742 @enumerate 1
22744 @item Launch the main program @file{main.exe}.
22746 @smallexample
22747 $ main
22748 @end smallexample
22750 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
22751 that the process PID for @file{main.exe} is 208.
22753 @item Launch gdb.
22755 @smallexample
22756 $ gdb -nw
22757 @end smallexample
22759 @item Attach to the running process to be debugged.
22761 @smallexample
22762 (gdb) attach 208
22763 @end smallexample
22765 @item Load the process debugging information.
22767 @smallexample
22768 (gdb) symbol-file main.exe
22769 @end smallexample
22771 @item Break somewhere in the DLL.
22773 @smallexample
22774 (gdb) break ada_dll
22775 @end smallexample
22777 @item Continue process execution.
22779 @smallexample
22780 (gdb) continue
22781 @end smallexample
22783 @end enumerate
22785 @noindent
22786 This last step will resume the process execution, and stop at
22787 the breakpoint we have set. From there you can use the standard
22788 approach to debug a program as described in
22789 (@pxref{Running and Debugging Ada Programs}).
22791 @node GNAT and COM/DCOM Objects
22792 @section GNAT and COM/DCOM Objects
22793 @findex COM
22794 @findex DCOM
22796 @noindent
22797 This section is temporarily left blank.
22799 @ignore
22800 @reread
22801 ???????????? WE NEED TO DECIDE WHETHER TO DISTRIBUTE IT ??????????????????????
22803 @node gnatreg : Registry Tool for NT
22804 @section @code{gnatreg} : Registry Tool for NT
22805 @findex gnatreg
22806 @cindex Registry
22808 @menu
22809 * Changing the GNAT compiler to Use::
22810 * Adding/Changing a Library Path::
22811 * Removing a Library Path::
22812 * List Current Configuration::
22813 @end menu
22815 @noindent
22816 This tool can be used to switch from one compiler to another and to manage
22817 the list of directories where GNAT must look to find packages. It is
22818 also a convenient way to do network installation of GNAT.
22820 The form of the @code{gnatreg} command is
22822 @smallexample
22823 $ gnatreg [@var{-hqcarf}] parameter
22824 @end smallexample
22826 @noindent
22827 Commons options are
22829 @table @code
22831 @item -h
22832 print a usage message.
22834 @item -q
22835 quiet/terse - display nothing, just do the job.
22837 @item -f
22838 force mode - create the registry keys if they do not
22839 exist. @code{gnatreg} will exit with an error if this option is omitted
22840 and some registry keys are not setup correctly.
22842 @end table
22844 @subsection Changing the GNAT compiler to use
22846 @smallexample
22847 $ gnatreg c:\gnatpro
22848 @end smallexample
22850 @noindent
22851 This will setup the registry to use the GNAT compiler that has been
22852 installed under c:\gnatpro. @code{gnatreg} check that this directory contain
22853 effectively a GNAT compiler. If you want to setup a network installation
22854 and if GNAT has never been installed on this computer you'll have to use
22855 the -f option.
22857 @subsection Adding/Changing a library path
22859 @smallexample
22860 $ gnatreg -a COMPNT=c:\ada\components
22861 @end smallexample
22863 @noindent
22864 Add the directory c:\ada\components to the list of standards libraries. When
22865 running gnatmake the option -Ic:\ada\components is added automatically to the
22866 command line.
22868 The directory c:\ada\components is associated with the name COMPNT. This
22869 name will be used to remove the library path.
22871 @subsection Removing a library path
22873 @smallexample
22874 $ gnatreg -r COMPNT
22875 @end smallexample
22877 @noindent
22878 Remove the library path named COMPNT.
22880 @subsection List current configuration
22882 @smallexample
22883 $ gnatreg -c
22884 @end smallexample
22886 @noindent
22887 @code{gnatreg} will display the GNAT and AdaGIDE path used and
22888 all the standards libraries and their associated names that have been set.
22890 @end ignore
22891 @end ifset
22893 @ifset vxworks
22894 @node VxWorks Topics
22895 @chapter VxWorks Topics
22897 @noindent
22898 This chapter describes topics that are specific to the GNAT for VxWorks
22899 configurations.
22901 @menu
22902 * Kernel Configuration for VxWorks::
22903 * Kernel Compilation Issues for VxWorks::
22904 * Handling Relocation Issues for PowerPc Targets::
22905 * Support for Software Floating Point on PowerPC Processors::
22906 * Interrupt Handling for VxWorks::
22907 * Simulating Command Line Arguments for VxWorks::
22908 * Debugging Issues for VxWorks::
22909 * Using GNAT from the Tornado 2 Project Facility::
22910 * Frequently Asked Questions for VxWorks::
22911 @end menu
22913 @node Kernel Configuration for VxWorks
22914 @section Kernel Configuration for VxWorks
22916 @noindent
22917 When configuring your VxWorks kernel we recommend including the target
22918 shell. If you omit it from the configuration, you may get undefined
22919 symbols at load time, e.g.
22921 @smallexample
22922 -> ld < hello.exe
22923 Loading hello.exe
22924 Undefined symbols:
22925 mkdir
22926 @end smallexample
22928 @noindent
22929 Generally, such undefined symbols are harmless since these are used by
22930 optional parts of the GNAT run time. However if running your application
22931 generates a VxWorks exception or illegal instruction, you should reconfigure
22932 your kernel to resolve these symbols.
22934 @node Kernel Compilation Issues for VxWorks
22935 @section Kernel Compilation Issues for VxWorks
22937 @noindent
22938 If you plan to link an Ada module with a Tornado 2 Kernel, follow these steps.
22939 (Note that these recommendations apply to @file{cygnus-2.7.2-960126},
22940 shipped with Tornado 2 as the C compiler toolchain.)
22942 @itemize @bullet
22943 @item
22944 Compile your Ada module without linking it with the VxWorks Library:
22945 @smallexample
22946 gnatmake foo.adb -largs -nostdlib
22947 @end smallexample
22949 @item
22950 Edit your makefile and add on the @code{LIBS} line the exact path and name
22951 of the GCC library file provided with GNAT.
22952 @smallexample
22953 LIBS             = $(WIND_BASE)/target/lib/libPPC604gnuvx.a \
22954 /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a
22955 @end smallexample
22957 @noindent
22958 To know the exact name and location of this file, type
22959 @code{<arch>-gcc -print-libgcc-file-name} in a console. Note that this version of GCC is the
22960 one provided with GNAT.
22961 @smallexample
22962 ~ >powerpc-wrs-vxworks-gcc -print-libgcc-file-name
22963 /opt/gnu/gnat/lib/gcc-lib/powerpc-wrs-vxworks/2.8.1/libgcc.a
22964 @end smallexample
22965 @end itemize
22968 @node Handling Relocation Issues for PowerPc Targets
22969 @section Handling Relocation Issues for PowerPc Targets
22970 @cindex Relocation issues for PowerPc VxWorks targets
22971 @cindex PowerPc VxWorks, relocation issues
22972 @cindex VxWorks PowerPc, relocation issues
22974 @noindent
22975 Under certain circumstances, loading a program onto a PowerPC
22976 board will fail with the message
22977 @emph{Relocation value does not fit in 24 bits}.
22979 For some background on this issue, please refer to WRS' SPRs
22980 6040, 20257, and 22767.
22981 In summary,
22982 VxWorks on the PowerPC follows the variation of the SVR4 ABI known
22983 as the Embedded ABI (@emph{EABI}).
22984 @cindex Embedded ABI (for VxWorks on PowerPc)
22985 @cindex EABI (for VxWorks on PowerPc)
22986 In order to save space and time in
22987 embedded applications, the EABI specifies that the default for
22988 subprogram calls should be the branch instruction with relative
22989 addressing using an immediate operand.  The immediate operand
22990 to this instruction (relative address) is 24 bits wide.  It
22991 is sign extended and 2#00# is appended for the last 2 bits (all
22992 instructions must be on a 4 byte boundary).
22993 The resulting
22994 26 bit offset means that the target of the branch must be within
22995 +/- 32 Mbytes of the relative branch instruction.  When VxWorks
22996 is loading a program it completes the linking phase by
22997 resolving all of the unresolved references in the object being
22998 loaded.  When one of those references is a relative address in
22999 a branch instruction, and the linker determines that the target
23000 is more than 32 Mbytes away from the branch, the error occurs.
23002 This only happens when the BSP is configured to use
23003 more than 32 MBytes of memory.  The VxWorks kernel is loaded into
23004 low memory addresses, and the error usually occurs when the target
23005 loader is used (because it loads objects into high memory, and thus
23006 calls from the program to the VxWorks kernel can be too far).
23007 @cindex VxWorks kernel (relocation issues on PowerPc)
23009 One way to solve this problem is to use the Tornado
23010 host loader; this will place programs in low memory, close to the kernel.
23012 Another approach is to make use of the @code{-mlongcall} option to the
23013 compiler;
23014 @cindex @code{-mlongcall} (gcc)
23015 GNAT has incorporated WRS'
23016 gcc modification that implements this option.
23017 If a subprogram call is
23018 compiled with the @code{-mlongcall} option, then the generated code
23019 constructs an absolute address in a register and uses a branch
23020 instruction with absolute addressing mode.
23022 Starting with release 3.15, the GNAT runtime libraries that are
23023 distributed are compiled with the @code{-mlongcall} option.  In many
23024 cases the use of these libraries is sufficient to avoid the
23025 relocation problem, since it is the runtime library that contains
23026 calls to the VxWorks kernel that need to span the address space gap.
23027 If you are using an earlier GNAT release or a manually-built runtime,
23028 you should recompile the GNAT runtime library with @code{-mlongcall};
23029 you can use the
23030 @file{Makefile.adalib} file from the @file{adalib} directory.
23032 Application code may need to be compiled with @code{-mlongcall} if there
23033 are calls directly to the kernel, the application is very large,
23034 or in some specialized linking/loading scenarios.
23036 You can compile individual files with @code{-mlongcall} by placing this
23037 option on the @code{gcc} command line (for brevity we are omitting the
23038 @code{powerpc-wrs-vxworks-} prefix on the commands shown in this
23039 paragraph).
23040 If you provide @code{-mlongcall} as an option for @code{gnatmake}, it will be
23041 passed to all invocations of @code{gcc} that @code{gnatmake} directly performs.
23042 Note that one other compilation is made by @code{gnatlink}, on the file created
23043 by @code{gnatbind} for the elaboration package body
23044 (see @ref{Binding Using gnatbind}).
23045 Passing @code{-mlongcall} to @code{gnatlink}, either directly
23046 on the @code{gnatlink} command line or by including @code{-mlongcall} in the
23047 @code{-largs} list of @code{gnatmake}, will direct @code{gnatlink} to compile the
23048 binder file with the @code{-mlongcall} option.
23050 To see the effect of @code{-mlongcall}, consider the following small example:
23052 @smallexample
23053    procedure Proc is
23054       procedure Imported_Proc;
23055       pragma Import (Ada, Imported_Proc);
23056    begin
23057       Imported_Proc;
23058    end;
23059 @end smallexample
23061 @noindent
23062 If you compile @code{Proc} with the default options (no @code{-mlongcall}), the following code is generated:
23064 @smallexample
23065    _ada_proc:
23066            ...
23067            bl imported_proc
23068            ...
23069 @end smallexample
23071 @noindent
23072 In contrast, here is the result with the @code{-mlongcall} option:
23074 @smallexample
23075    _ada_proc:
23076            ...
23077            addis 9,0,imported_proc@@ha
23078            addi 0,9,imported_proc@@l
23079            mtlr 0
23080            blrl
23081            ...
23082 @end smallexample
23085 @node Support for Software Floating Point on PowerPC Processors
23086 @section Support for Software Floating Point on PowerPC Processors
23088 @noindent
23089 The PowerPC 860 processor does not have hardware floating-point support.
23090 In order to build and run GNAT modules properly, you need to install and
23091 invoke software-emulated floating-point support as follows:
23093 @itemize @bullet
23094 @item
23095 At installation time:
23096 @itemize @bullet
23097 @item
23098 Create a file @file{ada_object_path} under the directory
23099 @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1}
23100 (by default @file{BASE}=@file{c:\gnatpro})
23101 containing the following line:
23102 @smallexample
23103 rts-soft-float\adalib
23104 @end smallexample
23106 @item
23107 Create a file @file{ada_source_path} under the directory
23108 @file{BASE\lib\gcc-lib\powerpc-wrs-vxworks\2.8.1}
23109 (by default @file{BASE}=@file{c:\gnatpro})
23110 containing the following line:
23111 @smallexample
23112 rts-soft-float\adainclude
23113 @end smallexample
23114 @end itemize
23116 @item
23117 When using the compiler, specify @option{-msoft-float}
23118 as a compiler and a linker option, e.g.:
23119 @smallexample
23120 $powerpc-wrs-vxworks-gnatmake -msoft-float module -largs -msoft-float
23121 @end smallexample
23122 @end itemize
23125 @node Interrupt Handling for VxWorks
23126 @section Interrupt Handling for VxWorks
23128 @noindent
23129 GNAT offers a range of options for hardware interrupt handling. In rough
23130 order of latency and lack of restrictions:
23132 @itemize @bullet
23133 @item Directly vectored interrupt procedure handlers
23134 @item Directly vectored interrupt procedures that signal a task using
23135 a suspension object
23136 @item Ada 95 protected procedure handlers for interrupts
23137 @item Ada 83 style interrupt entry handlers for interrupts
23138 @end itemize
23140 @noindent
23141 In general, the range of possible solutions trades off latency versus
23142 restrictions in the handler code.  Restrictions in direct vectored
23143 interrupt handlers  are documented in the @cite{VxWorks Programmer's Guide}.
23144 Protected procedure handlers have only the
23145 restriction that no potentially blocking operations are performed within
23146 the handler.  Interrupt entries have no restrictions.  We recommend the
23147 use of the protected procedure mechanism as providing the best balance
23148 of these considerations for most applications.
23150 All handler types must explicitly perform any required hardware cleanups,
23151 such as issuing an end-of-interrupt if necessary.
23153 For VxWorks/AE, applications that handle interrupts must be loaded into
23154 the kernel protection domain.
23156 @itemize @bullet
23157 @item Direct Vectored Interrupt Routines
23159 @noindent
23160 This approach provides the lowest interrupt latency, but has the most
23161 restrictions on what VxWorks and Ada runtime calls can be made, as well
23162 as on what Ada entities are accessible to the handler code.  Such handlers
23163 are most useful when there are stringent latency requirements, and very
23164 little processing is to be performed in the handler.   Access to the
23165 necessary VxWorks routines for setting up such handlers is provided in
23166 the package @code{Interfaces.VxWorks}.
23168 VxWorks restrictions are described in the @cite{VxWorks Programmer's Manual}.
23169 Note in particular that floating point context is not automatically saved and
23170 restored when interrupts are vectored to the handler.  If the handler is
23171 to execute floating point instructions, the statements involved must be
23172 bracketed by a pair of calls to @code{fppSave} and @code{fppRestore} defined
23173 in @code{Interfaces.VxWorks}.
23175 In general, it is a good idea to save and restore the handler that was
23176 installed prior to application startup.  The routines @code{intVecGet}
23177 and @code{intVecSet} are used for this purpose.  The Ada handler code
23178 is installed into the vector table using routine @code{intConnect},
23179 which generates wrapper code to save and restore registers.
23181 Example:
23183 @smallexample
23184 with Interfaces.VxWorks; use Interfaces.VxWorks;
23185 with System;
23187 package P is
23189    Count : Natural := 0;
23190    pragma Atomic (Count);
23192    --  Interrupt level used by this example
23193    Level : constant := 1;
23195    --  Be sure to use a reasonable interrupt number for the target
23196    --  board!  Refer to the BSP for details.
23197    Interrupt : constant := 16#14#;
23199    procedure Handler (Parameter : System.Address);
23201 end P;
23203 package body P is
23205    procedure Handler (parameter : System.Address) is
23206       S : Status;
23207    begin
23208       Count := Count + 1;
23209       --  Acknowledge interrupt.  Not necessary for all interrupts.
23210       S := sysBusIntAck (intLevel => Level);
23211    end Handler;
23212 end P;
23214 with Interfaces.VxWorks; use Interfaces.VxWorks;
23215 with Ada.Text_IO; use Ada.Text_IO;
23217 with P; use P;
23218 procedure Useint is
23219    task T;
23221    S : Status;
23223    task body T is
23224    begin
23225       for I in 1 .. 10 loop
23226          Put_Line ("Generating an interrupt...");
23227          delay 1.0;
23229          --  Generate interrupt, using interrupt number
23230          S := sysBusIntGen (Level, Interrupt);
23231       end loop;
23232    end T;
23234    --  Save old handler
23235    Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt));
23236 begin
23237    S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access);
23238    S := sysIntEnable (intLevel => Level);
23240    for I in 1 .. 10 loop
23241       delay 2.0;
23242       Put_Line ("value of count:" & P.Count'Img);
23243    end loop;
23245    --  Restore previous handler
23246    S := sysIntDisable (intLevel => Level);
23247    intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler);
23248 end Useint;
23249 @end smallexample
23251 @item Direct Vectored Interrupt Routines
23253 @noindent
23254 A variation on the direct vectored routine that allows for less restrictive
23255 handler code is to separate the interrupt processing into two levels.
23257 The first level is the same as in the previous section.  Here we perform
23258 simple hardware actions and signal a task pending on a Suspension_Object
23259 (defined in @code{Ada.Synchronous_Task_Control}) to perform the more complex
23260 and time-consuming operations.  The routine @code{Set_True} signals a task
23261 whose body loops and pends on the suspension object using @code{Suspend_Until_True}.
23262 The suspension object is declared in a scope global to both the handler and
23263 the task. This approach can be thought of as a slightly higher-level
23264 application of the @code{C} example using a binary semaphore given in the
23265 VxWorks Programmer's Manual.  In fact, the implementation of
23266 @code{Ada.Synchronous_Task_Control} is a very thin wrapper around a VxWorks
23267 binary semaphore.
23269 This approach has a latency between the direct vectored approach and the
23270 protected procedure approach.  There are no restrictions in the Ada task
23271 code, while the handler code has the same restrictions as any other
23272 direct interrupt handler.
23274 Example:
23276 @smallexample
23277 with System;
23278 package Sem_Handler is
23280    Count : Natural := 0;
23281    pragma Atomic (Count);
23283    --  Interrupt level used by this example
23284    Level : constant := 1;
23285    Interrupt : constant := 16#14#;
23287    --  Interrupt handler providing "immediate" handling
23288    procedure Handler (Param : System.Address);
23290    --  Task whose body provides "deferred" handling
23291    task Receiver is
23292        pragma Interrupt_Priority
23293           (System.Interrupt_Priority'First + Level + 1);
23294     end Receiver;
23296 end Sem_Handler;
23298 with Ada.Synchronous_Task_Control; use Ada.Synchronous_Task_Control;
23299 with Interfaces.VxWorks; use Interfaces.VxWorks;
23300 package body Sema_Handler is
23302    SO : Suspension_Object;
23304    task body Receiver is
23305    begin
23306       loop
23307          --  Wait for notification from immediate handler
23308          Suspend_Until_True (SO);
23310          --  Interrupt processing
23311          Count := Count + 1;
23312       end loop;
23313    end Receiver;
23315    procedure Handler (Param : System.Address) is
23316       S : STATUS;
23317    begin
23318       --  Hardware cleanup, if necessary
23319       S := sysBusIntAck (Level);
23321       --  Signal the task
23322       Set_True (SO);
23323    end Handler;
23325 end Sem_Handler;
23327 with Interfaces.VxWorks; use Interfaces.VxWorks;
23328 with Ada.Text_IO; use Ada.Text_IO;
23329 with Sem_Handler; use Sem_Handler;
23330 procedure Useint is
23332    S : STATUS;
23334    task T;
23336    task body T is
23337    begin
23338       for I in 1 .. 10 loop
23339          Put_Line ("Generating an interrupt...");
23340          delay 1.0;
23342          --  Generate interrupt, using interrupt number
23343          S := sysBusIntGen (Level, Interrupt);
23344       end loop;
23345    end T;
23347    --  Save old handler
23348    Old_Handler : VOIDFUNCPTR := intVecGet (INUM_TO_IVEC (Interrupt));
23349 begin
23350    S := intConnect (INUM_TO_IVEC (Interrupt), Handler'Access);
23351    S := sysIntEnable (intLevel => Level);
23353    for I in 1 .. 10 loop
23354       delay 2.0;
23355       Put_Line ("value of Count:" & Sem_Handler.Count'Img);
23356    end loop;
23358    --  Restore handler
23359    S := sysIntDisable (intLevel => Level);
23360    intVecSet (INUM_TO_IVEC (Interrupt), Old_Handler);
23361    abort Receiver;
23362 end Useint;
23363 @end smallexample
23365 @item Protected Procedure Handlers for Interrupts
23367 @noindent
23368 This is the recommended default mechanism for interrupt handling.
23369 It essentially wraps the hybrid handler / task mechanism in a higher-level
23370 abstraction, and provides a good balance between latency and capability.
23372 Vectored interrupts are designated by their interrupt number, starting from
23373 0 and ranging to the number of entries in the interrupt vector table - 1.
23375 In the GNAT VxWorks implementation, the following priority mappings are used:
23376 @itemize @bullet
23377 @item Normal task priorities are in the range 0 .. 245.
23378 @item Interrupt priority 246 is used by the GNAT @code{Interrupt_Manager}
23379 task.
23380 @item Interrupt priority 247 is used for vectored interrupts
23381 that do not correspond to those generated via an interrupt controller.
23382 @item Interrupt priorities 248 .. 255 correspond to PIC interrupt levels
23383 0 .. 7.
23384 @item Priority 256 is reserved to the VxWorks kernel.
23385 @end itemize
23387 Except for reserved priorities, the above are recommendations for setting the
23388 ceiling priority of a protected object that handles interrupts, or the
23389 priority of a task with interrupt entries.  It's a very good idea to follow
23390 these recommendations for vectored interrupts that come in through the PIC
23391 as it will determine the priority of execution of the code in the protected
23392 procedure or interrupt entry.
23394 No vectored interrupt numbers are reserved in this implementation, because
23395 dedicated interrupts are determined by the board support package. Obviously,
23396 careful consideration of the hardware is necessary when handling interrupts.
23397 The VxWorks BSP for the board is the definitive reference for interrupt
23398 assignments.
23400 Example:
23402 @smallexample
23403 package PO_Handler is
23405    --  Interrupt level used by this example
23406    Level : constant := 1;
23408    Interrupt : constant := 16#14#;
23410    protected Protected_Handler is
23411       procedure Handler;
23412       pragma Attach_Handler (Handler, Interrupt);
23414       function Count return Natural;
23416       pragma Interrupt_Priority (248);
23417    private
23418       The_Count : Natural := 0;
23419    end Protected_Handler;
23421 end PO_Handler;
23423 with Interfaces.VxWorks; use Interfaces.VxWorks;
23424 package body PO_Handler is
23426    protected body Protected_Handler is
23428       procedure Handler is
23429          S : Status;
23430       begin
23431          --  Hardware cleanup if necessary
23432          S := sysBusIntAck (Level);
23434          --  Interrupt processing
23435          The_Count := The_Count + 1;
23436       end Handler;
23438       function Count return Natural is
23439       begin
23440          return The_Count;
23441       end Count;
23442    end Protected_Handler;
23444 end PO_Handler;
23446 with Interfaces.VxWorks; use Interfaces.VxWorks;
23447 with Ada.Text_IO; use Ada.Text_IO;
23449 with PO_Handler; use PO_Handler;
23450 procedure Useint is
23452    task T;
23454    S : STATUS;
23456    task body T is
23457    begin
23458       for I in 1 .. 10 loop
23459          Put_Line ("Generating an interrupt...");
23460          delay 1.0;
23462          --  Generate interrupt, using interrupt number
23463          S := sysBusIntGen (Level, Interrupt);
23464       end loop;
23465    end T;
23467 begin
23468    S := sysIntEnable (intLevel => Level);
23470    for I in 1 .. 10 loop
23471       delay 2.0;
23472       Put_Line ("value of count:" & Protected_Handler.Count'Img);
23473    end loop;
23475    S := sysIntDisable (intLevel => Level);
23476 end Useint;
23477 @end smallexample
23479 @noindent
23480 This is obviously significantly higher-level and easier to write than the
23481 previous examples.
23483 @item Ada 83 Style Interrupt Entries
23485 GNAT provides a full implementation of the Ada 83 interrupt entry mechanism
23486 for vectored interrupts.  However, due to latency issues,
23487 we only recommend using these for backward compatibility.  The comments in
23488 the previous section regarding interrupt priorities and reserved interrupts
23489 apply here.
23491 In order to associate an interrupt with an entry, GNAT provides the
23492 standard Ada convenience routine @code{Ada.Interrupts.Reference}.  It is used
23493 as follows:
23495 @smallexample
23496 Interrupt_Address : constant System.Address :=
23497    Ada.Interrupts.Reference (Int_Num);
23499 task Handler_Task is
23500    pragma Interrupt_Priority (248);  -- For instance
23501    entry Handler;
23502    for Handler'Address use Interrupt_Address;
23503 end Handler_Task;
23504 @end smallexample
23506 @noindent
23507 Since there is no restriction within an interrupt entry on blocking operations,
23508 be sure to perform any hardware interrupt controller related operations before
23509 executing a call that could block within the entry's accept statements.  It
23510 is assumed that interrupt entries are always open alternatives when they
23511 appear within a selective wait statement.  The presence of a guard gives
23512 undefined behavior.
23514 Example:
23516 @smallexample
23517 with Ada.Interrupts;
23518 with System;
23519 package Task_Handler is
23521    --  Interrupt level used by this example
23522    Level : constant := 1;
23524    Interrupt : constant := 16#14#;
23526    Interrupt_Address : constant System.Address :=
23527       Ada.Interrupts.Reference (Int_Num);
23529    task Handler_Task is
23530       pragma Interrupt_Priority (248);  -- For instance
23531       entry Handler;
23532       for Handler'Address use Interrupt_Address;
23534       entry Count (Value : out Natural);
23535    end Handler_Task;
23536 end Task_Handler;
23538 with Interfaces.VxWorks; use Interfaces.VxWorks;
23539 package body Task_Handler is
23541    task body Handler_Task is
23542       The_Count : Natural := 0;
23543       S : STATUS;
23544    begin
23545       loop
23546          select
23547             accept Handler do
23548                --  Hardware cleanup if necessary
23549                S := sysBusIntAck (Level);
23551                --  Interrupt processing
23552                The_Count := The_Count + 1;
23553             end Handler;
23554          or
23555             accept Count (Value : out Natural) do
23556                Value := The_Count;
23557             end Count;
23558          end select;
23559       end loop;
23560    end Handler_Task;
23562 end Handler_Task;
23564 with Interfaces.VxWorks; use Interfaces.VxWorks;
23565 with Ada.Text_IO; use Ada.Text_IO;
23567 with Handler_Task; use Handler_Task;
23568 procedure Useint is
23570    task T;
23572    S : STATUS;
23573    Current_Count : Natural := 0;
23575    task body T is
23576    begin
23577       for I in 1 .. 10 loop
23578          Put_Line ("Generating an interrupt...");
23579          delay 1.0;
23581          --  Generate interrupt, using interrupt number
23582          S := sysBusIntGen (Level, Interrupt);
23583       end loop;
23584    end T;
23586 begin
23587    S := sysIntEnable (intLevel => Level);
23589    for I in 1 .. 10 loop
23590       delay 2.0;
23591       Handler_Task.Count (Current_Count);
23592       Put_Line ("value of count:" & Current_Count'Img);
23593    end loop;
23595    S := sysIntDisable (intLevel => Level);
23596    abort Handler_Task;
23597 end Useint;
23598 @end smallexample
23599 @end itemize
23602 @node Simulating Command Line Arguments for VxWorks
23603 @section Simulating Command Line Arguments for VxWorks
23605 @noindent
23606 The GNAT implementation of @code{Ada.Command_Line} relies on the standard C
23607 symbols @code{argv} and @code{argc}.  The model for invoking "programs" under
23608 VxWorks does not provide these symbols.  The typical method for invoking a
23609 program under VxWorks is to call the @code{sp} function in order to spawn a
23610 thread in which to execute a designated function (in GNAT, this is the implicit
23611 main generated by gnatbind. @code{sp} provides the capability to push a variable
23612 number of arguments onto the stack when the function is invoked.  But this does
23613 not work for the implicit Ada main, because it has no way of knowing how many
23614 arguments might be required.  This eliminates the possibility to use
23615 @code{Ada.Command_Line}.
23617 One way to solve this problem is to define symbols in the VxWorks environment,
23618 then import them into the Ada application.  For example, we could define the
23619 following package that imports two symbols, one an int and the other a string:
23621 @smallexample
23622 with Interfaces.C.Strings;
23623 use Interfaces.C.Strings;
23624 package Args is
23625    --  Define and import a variable for each argument
23626    Int_Arg : Interfaces.C.Int;
23627    String_Arg : Chars_Ptr;
23628 private
23629    pragma Import (C, Int_Arg, "intarg");
23630    pragma Import (C, String_Arg, "stringarg");
23631 end Args;
23632 @end smallexample
23634 @noindent
23635 An Ada unit could then use the two imported variables @code{Int_Arg} and
23636 @code{String_Arg} as follows:
23638 @smallexample
23639 with Args; use Args;
23640 with Interfaces.C.Strings;
23641 use Interfaces.C, Interfaces.C.Strings;
23642 with Ada.Text_IO; use Ada.Text_IO;
23643 procedure Argtest is
23644 begin
23645    Put_Line (Int'Image (Int_Arg));
23646    Put_Line (Value (String_Arg));
23647 end Argtest;
23648 @end smallexample
23650 @noindent
23651 When invoking the application from the shell, one will then set the values
23652 to be imported, and spawn the application, as follows:
23654 @smallexample
23655 -> intarg=10
23656 -> stringarg="Hello"
23657 -> sp (argtest)
23658 @end smallexample
23661 @node Debugging Issues for VxWorks
23662 @section Debugging Issues for VxWorks
23664 @noindent
23665 The debugger can be launched directly from the Tornado environment or from @code{glide}
23666 through its graphical interface: @code{gvd}. It can also be used
23667 directly in text mode as shown below:
23668 @noindent
23669 The command to run @code{GDB} in text mode is
23671 @smallexample
23672 $ @i{target}-gdb
23673 @end smallexample
23675 @noindent
23676 where @i{target} is the name of target of the cross GNAT
23677 compiler. In contrast with native @code{gdb}, it is not useful to give the name of
23678 the program to debug on the command line. Before starting a debugging
23679 session, one needs to connect to the VxWorks-configured board and load
23680 the relocatable object produced by @code{gnatlink}. This can be achieved
23681 by the following commands:
23683 @smallexample
23684 (vxgdb) target wtx myboard
23685 (vxgdb) load program
23686 @end smallexample
23688 @noindent
23689 where @code{myboard} is the host name or IP number of the target board, and
23690 @code{wtx} is the name of debugging protocol used to communicate
23691 with the VxWorks board. Early versions of VxWorks, up tp 5.2, only
23692 support the @code{<vxworks>} protocol whereas starting with VxWorks 5.3
23693 and Tornado, another protocol called  @code{<wtx>} was made available. The
23694 choice of the protocol can be made when configuring the VxWorks
23695 kernel itself. When available, the @code{<wtx>} is greatly preferable
23696 and actually the only supported protocol with GNAT. When the debugger
23697 is  launched directly from Tornado, the proper @code{target} command
23698 is automatically generated by the environment.
23700 The GNAT debugger can be used for debugging multitasking programs in two
23701 different modes and some minimal understanding of these modes is
23702 necessary in order to use the debugger effectively. The two modes are:
23704 @itemize @bullet
23705 @item Monotask mode: attach to, and debug, a single task.
23706 This mode is equivalent to the capabilities offered by CrossWind. The
23707 debugger interacts with a single task, while not affecting other tasks
23708 (insofar as possible). This is the DEFAULT mode.
23710 @item Multitask mode:
23711 The debugger has control over all Ada tasks in an application. It is
23712 possible to gather information about all application tasks, and to
23713 switch from one to another within a single debugging session.
23714 @end itemize
23716 @noindent
23717 It is not advised to switch between the two modes within a debugging
23718 session. A third mode called System mode is also available and can be
23719 used in place of the Multitask mode. Consult the Tornado documentation
23720 for this.
23722 Among the criteria for selecting the appropriate mode is the effect of
23723 task synchronization on the application's behavior. Debugging a
23724 tasking application affects the timing of the application; minimizing
23725 such effects may be critical in certain situations. The two modes have
23726 different effects: monotask mode only affects the attached task:
23727 others will run normally (if possible). Multitask mode stops all tasks
23728 at each breakpoint and restarts them on single-step, next, finish or
23729 continue; this may help avoid deadlocks in the presence of task
23730 synchronization despite the inherent latency of stopping and
23731 restarting the tasks.
23733 @subsection Using the debugger in monotask mode
23735 @noindent
23736 There are two ways to begin your debugging session:
23738 @itemize @bullet
23739 @item The program is already running on the board.
23741 @noindent
23742 The sequence of commands to use this mode is:
23743 @itemize @bullet
23744 @item Launch GVD (possibly from the Tornado menu)
23746 @noindent
23747 Verify that the debugger has access to the debug information of both
23748 your program and the kernel. The Console window should have a message
23749 "Looking for all loaded modules:" followed by the names of the modules
23750 on the board and "ok". If you have some error messages here instead of
23751 "ok", the debugging session may not work as expected.
23753 @item Attach to the desired task using
23754 @smallexample
23755         File --> Attach...
23756 @end smallexample
23757 @noindent
23758 This task is stopped by the debugger. Other tasks continue to operate
23759 normally (unless they are blocked by synchronization with the stopped
23760 task). The source window should display the code on which the task has
23761 been stopped, and if the stack display is enabled, it should reflect
23762 the stack of the task.
23763 @end itemize
23765 @item The program hasn't been loaded yet on the board
23766 @itemize @bullet
23767 @item Launch GVD (possibly from the Tornado menu)
23768 @item Load your program to the board:
23769 @smallexample
23770 File --> Open Program...
23771 @end smallexample
23773 @noindent
23774 GVD should display:
23775 @smallexample
23776 Downloading your_program ...done.
23777 Reading symbols from your_program...expanding to full symbols...done.
23778 @end smallexample
23780 @item Set breakpoints in your program.
23782 @noindent
23783 WARNING: they must be set in the main task (if your program runs
23784 several tasks)
23786 @item Run your program using one of the three methods below:
23787 @itemize @bullet
23788 @item
23789 Click on button <run> or <start>
23791 @item Menu
23792 @smallexample
23793 Program --> Run/Start
23794 @end smallexample
23796 @item
23797 Type in GVD's Console window
23798 @smallexample
23799 (gdb) run your_program
23800 @end smallexample
23801 @end itemize
23802 @end itemize
23804 @item Whichever method you chose to start your debugging session,
23805 you can use the following commands at this point:
23806 @itemize @bullet
23807 @item  Browse sources and set breakpoints
23808 @item  Examine the call stack (Data --> call stack)
23809 @item  Go "up" and "down" in the call stack ("up" & "down" buttons)
23810 @item  Examine data
23811 (Data --> Display local variables, or any of the other methods for viewing data in GVD)
23812 @item Continue/finish
23813 @end itemize
23815 Next/step/finish will only work if the top frame in the call stack has
23816 debug information.  This is almost never the case when first attaching
23817 to the task since the task is usually stopped by the attach operation
23818 in the GNAT runtime. You can verify which frames of the call stack
23819 have debug information by:
23820 @smallexample
23821 Data --> call stack
23822 <right Button> (contextual menu inside the call stack window)
23823  add "file location"
23824 @end smallexample
23826 @noindent
23827 If the current frame does not have a "file location", then there is no
23828 debug information for the frame.  We strongly recommended that you set
23829 breakpoints in the source where debug information can be found and
23830 "continue" until a breakpoint is reached before using
23831 "next/step". Another convenient possibility is to use the "continue
23832 until" capability available from the contextual menu of the Source
23833 window.
23835 You can also examine the state of other tasks using
23836 @smallexample
23837 Data -> tasks
23838 @end smallexample
23840 @noindent
23841 but you can't "switch" to another task by clicking on the
23842 elements of the task list. If you try to, you will get an error
23843 message in GVD's console:
23844 @smallexample
23845 "Task switching is not allowed when multi-tasks mode is not active"
23846 @end smallexample
23848 @noindent
23849 Once you have completed your debugging session on the attached
23850 task, you can detach from the task:
23851 @smallexample
23852 File --> detach
23853 @end smallexample
23855 @noindent
23856 The task resumes normal execution at this stage.  WARNING: when you
23857 detach from a task, be sure that you are in a frame where there is
23858 debug information. Otherwise, the task won't resume properly. You can
23859 then start another attach/detach cycle if you wish.
23861 Note that it is possible to launch several GVD sessions and
23862 simultaneously attach each to a distinct task in monotask mode:
23863 @smallexample
23864 File --> New Debugger...  (uncheck the box: Replace Current Debugger)
23865 File --> Attach...     (in the new window)
23866 File --> detach
23867 @end smallexample
23868 @end itemize
23871 @subsection Using the debugger in Multitask mode
23873 @noindent
23874 The steps are as follows
23876 @itemize @bullet
23877 @item
23878 Launch GVD (possibly from the Tornado menu)
23880 @noindent
23881 There are two possibilities:
23882 @itemize @bullet
23883 @item
23884 If the program is already loaded on the target board, you need only verify
23885 that debug information has been found by the debugger as described
23886 above.
23888 @item
23889 Otherwise, load the program on the board using
23890 @smallexample
23891 File --> Open program
23892 @end smallexample
23893 @end itemize
23895 @item Set breakpoints in the desired parts of the program
23897 @item Start the program
23899 @noindent
23900 The simplest way to start the debugger in multitask mode is to use the
23901 menu
23902 @smallexample
23903 Program --> Run/Start
23904 @end smallexample
23906 @noindent
23907 and check the box "enable vxWorks multi-tasks mode".
23908 You can also use the following gdb commands in the console window
23909 @smallexample
23910         (gdb) set multi-tasks-mode on
23911         (gdb) run your_program
23912 @end smallexample
23914 @item Debug the stopped program
23916 @noindent
23917 Once stopped at a breakpoint
23918 (or if you pressed the "stop" button), you can use all the standard
23919 commands listed for monotask mode + task switching (using Data -->
23920 tasks). Using next/step under this mode is possible with the same
23921 restrictions as for monotask mode, but is not recommended because all
23922 tasks are restarted, leading to the possibility that a different task
23923 hits a breakpoint before the stepping operation has completed.  Such
23924 an occurrence can result in a confusing state for both the user and
23925 the debugger. So we strongly suggest the use of only breakpoints and
23926 "continue" in this mode.
23927 @end itemize
23929 A final reminder: whatever the mode, whether you are debugging or not,
23930 the program has to be reloaded before each new execution, so that data
23931 initialized by the loader is set correctly. For instance, if you wish
23932 to restart the same execution of the same program, you can use the
23933 following sequence of gdb commands in the console window:
23934 @smallexample
23935 (gdb) detach
23936 (gdb) unload your_program(.exe)
23937 (gdb) load your_program(.exe)
23938 (gdb) run your_program
23939 @end smallexample
23942 @node Using GNAT from the Tornado 2 Project Facility
23943 @section Using GNAT from the Tornado 2 Project Facility
23944 @cindex Tornado II Project
23946 @menu
23947 * The GNAT Toolchain as Used from the Tornado 2 Project Facility::
23948 * Building a Simple Application::
23949 * Mixing C and Ada Code in a Tornado 2 Project::
23950 * Compilation Switches::
23951 * Autoscale and Minimal Kernel Configuration::
23952 * Adapting BSPs to GNAT::
23953 * Using GNAT Project Files in a Tornado 2 Project::
23954 @end menu
23956 @noindent
23957 This section describes how to add an Ada module in a Tornado project
23958 using the Tornado 2 Project facility described in
23959 @cite{Tornado User's Guide}, Chapter 4.
23960 All recommendations apply for both 'Downloadable Modules' and 'Kernel'
23961 project types.
23964 @node The GNAT Toolchain as Used from the Tornado 2 Project Facility
23965 @subsection The GNAT Toolchain as Used from the Tornado 2 Project Facility
23967 @noindent
23968 Tornado 2 allows you to integrate third-party C toolchains.
23969 (@cite{Tornado 2 API Programmer's Guide}, Chapter 7).
23970 Thus the GNAT toolchain will be seen as a new C toolchain when used from
23971 the Tornado 2 Project Facility. For each processor you can compile for,
23972 you will find a <proc>gnat toolchain, e.g. PPC604gnat. These toolchains will
23973 allow you to include Ada modules into your projects, and simply build them.
23975 The name of the so-called C compiler is @emph{cc_gnat_<arch>}, the name
23976 of the 'linker' is @emph{ld_gnat_<arch>}, where <arch> is an architecture; e.g.,
23977 PPC. These scripts will call the correct executables during the compilation or
23978 link processes, thus the C compiler, the C linker, or the GNAT toolchain,
23979 depending on the context.
23982 @node  Building a Simple Application
23983 @subsection  Building a Simple Application
23985 @noindent
23986 First, create a new project, using one of the gnat toolchains.
23988 To add an Ada source file to the current project, just click on
23989 @code{Project -> Add/Include}, browse to the relevant file, and include it.
23990 The Ada source file included should be the Ada entry point. Only
23991 one Ada entry point is allowed in a project. Any other required Ada source
23992 files will be automatically compiled and linked by the underlying tools.
23994 You can now compile the project, @code{Build->Rebuild all}.
23995 A log of the compilation process can be found in the build directory, in
23996 @file{gnatbuild.log}. It contains all the calls executed by the scripts, and
23997 associated information.
24000 @node Mixing C and Ada Code in a Tornado 2 Project
24001 @subsection Mixing C and Ada Code in a Tornado 2 Project
24003 @noindent
24004 You can mix C and Ada code in your projects. Your source files and the build
24005 options should comply with the recommendations from the section
24006 @cite{Interfacing to C}.
24007 This means that you can have several or no C source files, and one or no Ada entry
24008 point in your Tornado 2 Project.
24011 @node Compilation Switches
24012 @subsection Compilation Switches
24013 @noindent
24014 Once you have included all your source files, you may modify some compilation
24015 and linking options.
24016 To pass specific options to the GNAT toolchain, go to the Project's build
24017 settings, on the @code{C/C++ Compiler} tab, and add your arguments in the
24018 input window.
24020 You must comply with several rules to pass arguments to GNAT.
24021 Arguments to be passed should be
24023 @itemize @bullet
24025 @item after any arguments passed to the C toolchain.
24027 @item prefixed depending on the tool that uses them, with the following syntax
24029 @itemize @bullet
24030 @item @code{-cargs @emph{gnatmake-options}} to pass arguments to gnatmake
24031 @item @code{-bargs @emph{gnatbind-options}} to pass arguments to gnatbind
24032 @item @code{-largs @emph{gnatlink-options}} to pass arguments to gnatlink
24033 @end itemize
24034 @end itemize
24036 @noindent
24037 You will find more information on the compilation process of Ada source files
24038 in the section @cite{The GNAT Compilation Model}.
24039 For a list of all available switches, refer to the sections describing
24040 @code{gnatmake}, @code{gnatbind} and @code{gnatlink}.
24042 Here is an example that passes the option @code{-v} to the GNAT compiler :
24043 @smallexample
24044 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
24045 -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
24046 -cargs -v
24047 @end smallexample
24049 @noindent
24050 Here is an example that passes the option @code{-v} to the GNAT compiler, binder and linker,
24051 and @code{-v} and @code{-g} to the compiler :
24052 @smallexample
24053 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
24054 -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
24055 -cargs -v -g -O2 -bargs -v -largs -v
24056 @end smallexample
24058 @noindent
24059 In both examples, the following arguments have been automatically added by the Project
24060 Facility, and will be used by the C compiler.
24061 @smallexample
24062 -g -mstrict-align -prjtype $(PRJ_TYPE) -ansi -nostdinc -DRW_MULTI_THREAD -D_REENTRANT
24063 -fno-builtin -fno-for-scope -I. -I/usr/windppc-2.0/target/h -DCPU=PPC604
24064 @end smallexample
24066 @noindent
24067 Note: The @code{-prjtype $(PRJ_TYPE)} option present in a few input
24068 boxes is used by the GNAT toolchain. It is required for the compilation
24069 process. You should not remove it from any input box.
24072 @node Autoscale and Minimal Kernel Configuration
24073 @subsection Autoscale and Minimal Kernel Configuration
24075 @noindent
24076 The Autoscale feature, present in the Project Facility  can be used on your
24077 VxWorks Kernel projects to determine the minimum set of components required
24078 for your kernel to work.
24079 (Please refer to the @cite{Tornado II User's Guide} Section 4.4 for more details.)
24080 This feature is also available for projects involving Ada code. Just click on
24081 @code{Project->Autoscale} to launch a check and determine the minimal kernel
24082 configuration.
24085 @node Adapting BSPs to GNAT
24086 @subsection Adapting BSPs to GNAT
24088 @noindent
24089 To use your Board Support Packages with the GNAT toolchain, you will have to adapt them,
24090 either manually or using the @code{adaptbsp4gnat} script.
24091 This procedure is described in the @cite{Tornado API Programmer's Guide},
24092 Chapter 7.
24093 Here is a summary of this setup, depending on the context.
24095 @itemize @bullet
24096 @item To do the adaptation manually:
24098 @itemize @bullet
24100 @item Copy your BSP directory contents into a new directory
24102 @item Go to this directory
24104 @item Edit the file @file{Makefile},
24106 @itemize @bullet
24107 @item Set tool to gnat, @code{TOOL=gnat}
24109 @item Reverse the order of the following lines
24110 @itemize @bullet
24111 @item @code{include $(TGT_DIR)/h/make/make.$(CPU)$(TOOL)}
24112 @item @code{include $(TGT_DIR)/h/make/defs.$(WIND_HOST_TYPE)}
24113 @end itemize
24115 @end itemize
24117 @end itemize
24119 @item To do the adaptation automatically, you may use the @code{adaptbsp4gnat}
24120 script. Its syntax is @code{adaptbsp4gnat <path_to_bsp>}.
24122 @noindent
24123 This script follows the different steps described above to perform the
24124 adaptation.
24125 The name of the new bsp is given after the modification.  By default, if
24126 @file{<bsp>} is the name of your BSP, @file{<bsp>-gnat}, will be the name of
24127 the BSP created.
24128 @end itemize
24131 @node Using GNAT Project Files in a Tornado 2 Project
24132 @subsection Using GNAT Project Files in a Tornado 2 Project
24134 @noindent
24135 You can use GNAT Project files to compile your Ada files.
24136 To do so, you need to use the @option{-Pproject_file.gpr} option from @command{gnatmake}.
24137 The path to the project file can be either absolute, or relative to the build
24138 directory, i.e. where the executable will be placed (e.g. @file{~/myproject/PPC604gnat}).
24139 Your project file should set the @code{Object_Dir} variable to a specific
24140 value.
24141 @smallexample
24142 project Sample is
24144    Target := external ("TARGET_DIR");
24145    for Object_Dir use Target;
24147 end Sample;
24148 @end smallexample
24151 @node Frequently Asked Questions for VxWorks
24152 @section Frequently Asked Questions for VxWorks
24154 @itemize @bullet
24156 @item
24157 When I run my program twice on the board, it does not work, why?
24159 @noindent
24160 Usually, Ada programs require elaboration and finalization, so the
24161 compiler creates a wrapper procedure whose name is the same as the Ada
24162 name of the main subprogram, which takes care of calling the elaboration
24163 and finalization routines before and after your program. But the static
24164 part of the elaboration is taken care of while loading the program
24165 itself and thus if you launch it twice this part of the elaboration will
24166 not be performed. This affects the proper elaboration of the
24167 GNAT runtime and thus it is mandatory to reload your program before
24168 relaunching it.
24170 @item
24171 Can I load a collection of subprograms rather than a standalone program?
24173 @noindent
24174 It is possible to write Ada programs with multiple entry points which
24175 can be called from the VxWorks shell; you just need to consider your
24176 main program as the VxWorks shell itself and generate an Ada subsystem
24177 callable from outside @xref{Binding with Non-Ada Main Programs}. If you
24178 use this method, you need to call @code{adainit} manually before calling
24179 any Ada entry point.
24181 @item
24182 When I use the @code{break exception} command, I get the message
24183 @code{"exception" is not a function}, why?
24185 You are not in the proper language mode. Issue the command:
24186 @smallexample
24187 (vxgdb) set language ada
24188 @end smallexample
24190 @item
24191 When I load a large application from the VxWorks shell using the "ld"
24192 command, the load hangs and never finishes. How can I load large
24193 executables?
24195 This is a classic VxWorks problem when using the default "rsh" communication
24196 method. Using NFS instead should work. Use the @code{nfsShowMount} command to
24197 verify that your program is in a NFS mounted directory.
24199 @item
24200 When I load a large application from the debugger using the wtx target
24201 connection, the load never finishes, why?
24203 Make sure that the memory cache size parameter of the target server is
24204 large enough. (@code{target -m big_enough_size}, or Memory cache size box in GUI.)
24205 See @cite{Tornado 1.01 API Programming Guide}, Section 3.6.2.
24207 @item
24208 When I spawn my program under the VxWorks shell, interactive input does
24209 not work, why?
24211 Only programs directly launched from the shell can have interactive
24212 input. For a program spawned with the @code{sp} or @code{taskSpawn}
24213 command, you need to have file redirection for input:
24214 @smallexample
24215 ->    # here you can have interactive input
24216 -> main
24217 ->    # here you cannot
24218 -> sp main
24219 ->    # neither here
24220 -> taskSpawn("ess",100,0,8000000,main)
24221 ->    # but you can input from a file:
24222 -> taskSpawn("Bae",100,0,8000000,main) < input_file
24223 @end smallexample
24224 @end itemize
24227 @node LynxOS Topics
24228 @chapter LynxOS Topics
24229 @noindent
24230 This chapter describes topics that are specific to the GNAT for LynxOS
24231 cross configurations.
24233 @menu
24234 * Getting Started with GNAT on LynxOS::
24235 * Kernel Configuration for LynxOS::
24236 * Patch Level Issues for LynxOS::
24237 * Debugging Issues for LynxOS::
24238 * An Example Debugging Session for LynxOS::
24239 @end menu
24241 @node Getting Started with GNAT on LynxOS
24242 @section Getting Started with GNAT on LynxOS
24244 @noindent
24245 This section is a starting point for using GNAT to develop and
24246 execute Ada 95 programs for LynuxWorks' LynxOS target environment from a
24247 Unix host environment.
24248 We assume that you know how to use GNAT in a native environment
24249 and how to start a telnet or other login session to connect to your LynxOS board.
24251 To compile code for a LynxOS system running on a PowerPC
24252 board, the basic compiler command is
24253 @command{powerpc-xcoff-lynxos-gcc}.
24255 With GNAT, the easiest way to build the basic @code{Hello World} program is
24256 with @code{gnatmake}. For the LynxOS PowerPC target this would look
24257 like:
24259 @smallexample
24260 $ powerpc-xcoff-lynxos-gnatmake hello
24261 @i{powerpc-xcoff-lynxos-gcc -c hello.adb
24262 powerpc-xcoff-lynxos-gnatbind -x hello.ali
24263 powerpc-xcoff-lynxos-gnatlink hello.ali}
24264 @end smallexample
24266 @noindent
24267 (The first line is the command entered by the user -- the subseqent three
24268 are the programs run by @code{gnatmake}.)
24270 This creates the executable @command{hello}" which you then need to load on the
24271 board (using ftp or an NFS directory for example) to run it.
24274 @node Kernel Configuration for LynxOS
24275 @section Kernel Configuration for LynxOS
24277 @noindent
24278 The appropriate configuration for your LynxOS kernel depends
24279 on the target system and the requirements of your application. GNAT itself
24280 adds no additional demands; however in some situations it may be appropriate
24281 to increase the conservative
24282 resource assumptions made by the default configuration.
24284 Kernel parameters limiting the maximum number of file descriptors,
24285 kernel and user threads, synchronization objects, etc., may be set in the
24286 file @file{uparam.h}. You may also wish to modify the file
24287 @file{/etc/starttab}, which places limits on data, stack, and core file
24288 size. See the documentation provided by LynuxWorks for more information.
24291 @node Patch Level Issues for LynxOS
24292 @section Patch Level Issues for LynxOS
24294 @noindent
24295 The GNAT runtime requires that your system run at patch level 040 or
24296 later. Please see the file @file{PatchCompatibility.txt} from the
24297 distribution for more information.
24300 @node Debugging Issues for LynxOS
24301 @section Debugging Issues for LynxOS
24303 @noindent
24304 GNAT's debugger is based on the same GNU gdb technology as the debugger
24305 provided by LynxOS, though with a great number of extensions and
24306 enhancements to support the Ada language and GNAT. The LynxOS
24307 documentation is relevant to understanding how to get the debugger
24308 started if you run into difficulties.
24310 To demonstrate a debugging session, we will use a slightly more complex
24311 program called @file{demo1.adb}, which can be found in the @file{examples}
24312 directory of the GNAT distribution. This program is compiled with
24313 debugging information as follows:
24315 @smallexample
24316 $ powerpc-xcoff-lynxos-gnatmake -g demo1
24317 powerpc-xcoff-lynxos-gcc -c -g demo1.adb
24318 powerpc-xcoff-lynxos-gcc -c -g gen_list.adb
24319 powerpc-xcoff-lynxos-gcc -c -g instr.adb
24320 powerpc-xcoff-lynxos-gnatbind -x demo1.ali
24321 powerpc-xcoff-lynxos-gnatlink -g demo1.ali
24322 @end smallexample
24324 @noindent
24325 Once the executable is created, copy it to your working directory on the
24326 board. In this directory, you will have to launch the gdb server and
24327 choose a free port number on your TCP/IP socket. Presuming the Internet
24328 hostname of the board is @file{myboard} and the port chosen is 2345,
24329 issue the following command:
24331 @smallexample
24332 myboard> gdbserver myboard:2345 demo1
24333 @end smallexample
24335 @noindent
24336 Then return to your host environment.
24338 The graphical debugger interface, @command{gvd}, supports both native
24339 and cross environments at the same time. @command{gvd} can be launched from
24340 @command{Glide} (see @file{README.Glide} for more information on customizing
24341 @command{Glide} for LynxOS) or it can be launched from the command line as
24342 follows:
24344 @smallexample
24345 $ gvd --debugger powerpc-xcoff-lynxos-gdb
24346 @end smallexample
24348 @noindent
24349 Then to attach to the target, enter in @command{gvd}'s command line window:
24351 @smallexample
24352 (gdb) target remote myboard:2345
24353 @end smallexample
24355 @noindent
24356 For more information see the GVD documentation.
24358 The comments below concern debugging directly from the command line but
24359 they also apply to @command{gvd}, though in most cases an equivalent
24360 graphical command is also available.
24362 To run the cross debugger from the command line without the visual
24363 interface use the command @code{powerpc-xcoff-lynxos-gdb}.
24365 You will see something like:
24367 @smallexample
24368 GNU gdb 4.17.gnat.3.14a1
24369 Copyright 1998 Free Software Foundation, Inc.
24370 GDB is free software, covered by the GNU General Public License, and you are
24371 welcome to change it and/or distribute copies of it under certain conditions.
24372 Type "show copying" to see the conditions.
24373 There is absolutely no warranty for GDB.  Type "show warranty" for details.
24374 This GDB was configured as "--host=sparc-sun-solaris2.5.1 --target=powerpc-xc
24375 off-lynxos".
24376 (gdb)
24377 @end smallexample
24379 @noindent
24380 Where @command{(gdb)} is the debugger's prompt. The first thing to do at the
24381 prompt from within @command{gdb} is to load the symbol table from the
24382 executable:
24384 @smallexample
24385 (gdb) file demo1
24386 Reading symbols from demo1...done.
24387 (gdb)
24388 @end smallexample
24390 @noindent
24391 You then have to attach to the server running on the board. Issue the command:
24393 @smallexample
24394 (gdb) target remote myboard:2345
24395 @end smallexample
24397 @noindent
24398 After the server has been started and attached from the host, the program is
24399 running on the target but has halted execution at the very beginning.
24400 The following commands set a breakpoint and continue execution:
24402 @smallexample
24403 (gdb) break demo1.adb:37
24404 Breakpoint 1 at 0x100064d0: file demo1.adb, line 37.
24405 (gdb) cont
24406 Continuing.
24408 Breakpoint 1, demo1 () at demo1.adb:37
24409 37         Set_Name (Fuel, "Fuel");
24410 (gdb)
24411 @end smallexample
24413 @noindent
24414 Here the execution has stopped at the breakpoint set above. Now
24415 you can use the standard @code{gdb} commands to examine the stack and
24416 program variables.
24418 Note that once execution has completed, the server on the board must be
24419 restarted before a new debugging session may begin.
24421 @node An Example Debugging Session for LynxOS
24422 @section An Example Debugging Session for LynxOS
24424 @noindent
24425 Carrying on a little further with the debugging session, the following
24426 example illustrates some of the usual debugging commands for moving
24427 around and seeing where you are:
24429 @smallexample
24430 (gdb) next
24431 38         Set_Name (Water, "Water");
24432 (gdb) bt
24433 #0  demo1 () at demo1.adb:38
24434 #1  0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at
24435 b~demo1.adb:118
24436 #2  0x10017538 in runmainthread ()
24437 #3  0x10001048 in __start ()
24438 (gdb) up
24439 #1  0x10001218 in main (argc=1, argv=2147483640, envp=2147483520) at
24440 b~demo1.adb:118
24441 118       Ada_Main_Program;
24442 (gdb) down
24443 #0  demo1 () at demo1.adb:38
24444 38         Set_Name (Water, "Water");
24445 (gdb)
24446 @end smallexample
24448 @noindent
24449 To examine and modify variables (of a tagged type here):
24451 @smallexample
24452 (gdb) print speed
24453 $1 = (name => "Speed         ", value => -286331154)
24454 (gdb) ptype speed
24455 type = new instr.instrument with record
24456     value: instr.speed;
24457 end record
24458 (gdb) speed.value := 3
24459 $2 = 3
24460 (gdb) print speed
24461 $3 = (name => "Speed         ", value => 3)
24462 (gdb) info local
24463 speed = (name => "Speed         ", value => 3)
24464 fuel = (name => "Fuel          ", value => -286331154)
24465 oil = (name => ' ' <repeats 14 times>, value => -286331154, size => 20,
24466   fill => 42 '*', empty => 46 '.')
24467 water = (name => ' ' <repeats 14 times>, value => -286331154, size => 20,
24468   fill => 42 '*', empty => 46 '.')
24469 time = (name => ' ' <repeats 14 times>, seconds => 0, minutes => 0, hours =>
24471 chrono = (name => ' ' <repeats 14 times>, seconds => 0, minutes => 0,
24472   hours => 0)
24473 db = (access demo1.dash_board.internal) 0x0
24474 (gdb)
24475 @end smallexample
24477 @noindent
24478 And finally letting the program it run to completion:
24480 @smallexample
24481 (gdb) c
24482 Continuing.
24484 Program exited normally.
24485 (gdb)
24486 @end smallexample
24487 @end ifset
24490 @node Performance Considerations
24491 @chapter Performance Considerations
24492 @cindex Performance
24494 @noindent
24495 The GNAT system provides a number of options that allow a trade-off
24496 between
24498 @itemize @bullet
24499 @item
24500 performance of the generated code
24502 @item
24503 speed of compilation
24505 @item
24506 minimization of dependences and recompilation
24508 @item
24509 the degree of run-time checking.
24510 @end itemize
24512 @noindent
24513 The defaults (if no options are selected) aim at improving the speed
24514 of compilation and minimizing dependences, at the expense of performance
24515 of the generated code:
24517 @itemize @bullet
24518 @item
24519 no optimization
24521 @item
24522 no inlining of subprogram calls
24524 @item
24525 all run-time checks enabled except overflow and elaboration checks
24526 @end itemize
24528 @noindent
24529 These options are suitable for most program development purposes. This
24530 chapter describes how you can modify these choices, and also provides
24531 some guidelines on debugging optimized code.
24533 @menu
24534 * Controlling Run-Time Checks::
24535 * Optimization Levels::
24536 * Debugging Optimized Code::
24537 * Inlining of Subprograms::
24538 @ifset vms
24539 * Coverage Analysis::
24540 @end ifset
24541 @end menu
24543 @node Controlling Run-Time Checks
24544 @section Controlling Run-Time Checks
24546 @noindent
24547 By default, GNAT generates all run-time checks, except arithmetic overflow
24548 checking for integer operations and checks for access before elaboration on
24549 subprogram calls. The latter are not required in default mode, because all
24550 necessary checking is done at compile time.
24551 @cindex @option{-gnatp} (@code{gcc})
24552 @cindex @option{-gnato} (@code{gcc})
24553 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
24554 be modified. @xref{Run-Time Checks}.
24556 Our experience is that the default is suitable for most development
24557 purposes.
24559 We treat integer overflow specially because these
24560 are quite expensive and in our experience are not as important as other
24561 run-time checks in the development process. Note that division by zero
24562 is not considered an overflow check, and divide by zero checks are
24563 generated where required by default.
24565 Elaboration checks are off by default, and also not needed by default, since
24566 GNAT uses a static elaboration analysis approach that avoids the need for
24567 run-time checking. This manual contains a full chapter discussing the issue
24568 of elaboration checks, and if the default is not satisfactory for your use,
24569 you should read this chapter.
24571 For validity checks, the minimal checks required by the Ada Reference
24572 Manual (for case statements and assignments to array elements) are on
24573 by default. These can be suppressed by use of the @option{-gnatVn} switch.
24574 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
24575 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
24576 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
24577 are also suppressed entirely if @option{-gnatp} is used.
24579 @cindex Overflow checks
24580 @cindex Checks, overflow
24581 @findex Suppress
24582 @findex Unsuppress
24583 @cindex pragma Suppress
24584 @cindex pragma Unsuppress
24585 Note that the setting of the switches controls the default setting of
24586 the checks. They may be modified using either @code{pragma Suppress} (to
24587 remove checks) or @code{pragma Unsuppress} (to add back suppressed
24588 checks) in the program source.
24590 @node Optimization Levels
24591 @section Optimization Levels
24592 @cindex @code{^-O^/OPTIMIZE^} (@code{gcc})
24594 @noindent
24595 The default is optimization off. This results in the fastest compile
24596 times, but GNAT makes absolutely no attempt to optimize, and the
24597 generated programs are considerably larger and slower than when
24598 optimization is enabled. You can use the
24599 @ifclear vms
24600 @code{-O@var{n}} switch, where @var{n} is an integer from 0 to 3,
24601 @end ifclear
24602 @ifset vms
24603 @code{/OPTIMIZE}
24604 @end ifset
24605 on the @code{gcc} command line to control the optimization level:
24607 @table @code
24608 @item -O0
24609 no optimization (the default)
24611 @item -O1
24612 medium level optimization
24614 @item -O2
24615 full optimization
24617 @item -O3
24618 full optimization, and also attempt automatic inlining of small
24619 subprograms within a unit (@pxref{Inlining of Subprograms}).
24620 @end table
24622 Higher optimization levels perform more global transformations on the
24623 program and apply more expensive analysis algorithms in order to generate
24624 faster and more compact code. The price in compilation time, and the
24625 resulting improvement in execution time,
24626 both depend on the particular application and the hardware environment.
24627 You should experiment to find the best level for your application.
24629 Note: Unlike some other compilation systems, @code{gcc} has
24630 been tested extensively at all optimization levels. There are some bugs
24631 which appear only with optimization turned on, but there have also been
24632 bugs which show up only in @emph{unoptimized} code. Selecting a lower
24633 level of optimization does not improve the reliability of the code
24634 generator, which in practice is highly reliable at all optimization
24635 levels.
24637 Note regarding the use of @code{-O3}: The use of this optimization level
24638 is generally discouraged with GNAT, since it often results in larger
24639 executables which run more slowly. See further discussion of this point
24640 in @pxref{Inlining of Subprograms}.
24642 @node Debugging Optimized Code
24643 @section Debugging Optimized Code
24645 @noindent
24646 Since the compiler generates debugging tables for a compilation unit before
24647 it performs optimizations, the optimizing transformations may invalidate some
24648 of the debugging data.  You therefore need to anticipate certain
24649 anomalous situations that may arise while debugging optimized code.  This
24650 section describes the most common cases.
24652 @enumerate
24653 @item
24654 @i{The "hopping Program Counter":}  Repeated 'step' or 'next' commands show the PC
24655 bouncing back and forth in the code.  This may result from any of the following
24656 optimizations:
24658 @itemize @bullet
24659 @item
24660 @i{Common subexpression elimination:} using a single instance of code for a
24661 quantity that the source computes several times.  As a result you
24662 may not be able to stop on what looks like a statement.
24664 @item
24665 @i{Invariant code motion:} moving an expression that does not change within a
24666 loop, to the beginning of the loop.
24668 @item
24669 @i{Instruction scheduling:} moving instructions so as to
24670 overlap loads and stores (typically) with other code, or in
24671 general to move computations of values closer to their uses. Often
24672 this causes you to pass an assignment statement without the assignment
24673 happening and then later bounce back to the statement when the
24674 value is actually needed.  Placing a breakpoint on a line of code
24675 and then stepping over it may, therefore, not always cause all the
24676 expected side-effects.
24677 @end itemize
24679 @item
24680 @i{The "big leap":} More commonly known as @i{cross-jumping}, in which two
24681 identical pieces of code are merged and the program counter suddenly
24682 jumps to a statement that is not supposed to be executed, simply because
24683 it (and the code following) translates to the same thing as the code
24684 that @emph{was} supposed to be executed.  This effect is typically seen in
24685 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
24686 a @code{break} in a C @code{switch} statement.
24688 @item
24689 @i{The "roving variable":} The symptom is an unexpected value in a variable.
24690 There are various reasons for this effect:
24692 @itemize @bullet
24693 @item
24694 In a subprogram prologue, a parameter may not yet have been moved to its
24695 "home".
24697 @item
24698 A variable may be dead, and its register re-used.  This is
24699 probably the most common cause.
24701 @item
24702 As mentioned above, the assignment of a value to a variable may
24703 have been moved.
24705 @item
24706 A variable may be eliminated entirely by value propagation or
24707 other means.  In this case, GCC may incorrectly generate debugging
24708 information for the variable
24709 @end itemize
24711 @noindent
24712 In general, when an unexpected value appears for a local variable or parameter
24713 you should first ascertain if that value was actually computed by
24714 your program, as opposed to being incorrectly reported by the debugger.
24715 Record fields or
24716 array elements in an object designated by an access value
24717 are generally less of a problem, once you have ascertained that the access value
24718 is sensible.
24719 Typically, this means checking variables in the preceding code and in the
24720 calling subprogram to verify that the value observed is explainable from other
24721 values (one must apply the procedure recursively to those
24722 other values); or re-running the code and stopping a little earlier
24723 (perhaps before the call) and stepping to better see how the variable obtained
24724 the value in question; or continuing to step @emph{from} the point of the
24725 strange value to see if code motion had simply moved the variable's
24726 assignments later.
24727 @end enumerate
24729 @node Inlining of Subprograms
24730 @section Inlining of Subprograms
24732 @noindent
24733 A call to a subprogram in the current unit is inlined if all the
24734 following conditions are met:
24736 @itemize @bullet
24737 @item
24738 The optimization level is at least @code{-O1}.
24740 @item
24741 The called subprogram is suitable for inlining: It must be small enough
24742 and not contain nested subprograms or anything else that @code{gcc}
24743 cannot support in inlined subprograms.
24745 @item
24746 The call occurs after the definition of the body of the subprogram.
24748 @item
24749 @cindex pragma Inline
24750 @findex Inline
24751 Either @code{pragma Inline} applies to the subprogram or it is
24752 small and automatic inlining (optimization level @code{-O3}) is
24753 specified.
24754 @end itemize
24756 @noindent
24757 Calls to subprograms in @code{with}'ed units are normally not inlined.
24758 To achieve this level of inlining, the following conditions must all be
24759 true:
24761 @itemize @bullet
24762 @item
24763 The optimization level is at least @code{-O1}.
24765 @item
24766 The called subprogram is suitable for inlining: It must be small enough
24767 and not contain nested subprograms or anything else @code{gcc} cannot
24768 support in inlined subprograms.
24770 @item
24771 The call appears in a body (not in a package spec).
24773 @item
24774 There is a @code{pragma Inline} for the subprogram.
24776 @item
24777 @cindex @option{-gnatn} (@code{gcc})
24778 The @code{^-gnatn^/INLINE^} switch
24779 is used in the @code{gcc} command line
24780 @end itemize
24782 Note that specifying the @option{-gnatn} switch causes additional
24783 compilation dependencies. Consider the following:
24785 @smallexample
24786 @group
24787 @cartouche
24788 @b{package} R @b{is}
24789    @b{procedure} Q;
24790    @b{pragma} Inline (Q);
24791 @b{end} R;
24792 @b{package body} R @b{is}
24793    ...
24794 @b{end} R;
24796 @b{with} R;
24797 @b{procedure} Main @b{is}
24798 @b{begin}
24799    ...
24800    R.Q;
24801 @b{end} Main;
24802 @end cartouche
24803 @end group
24804 @end smallexample
24806 @noindent
24807 With the default behavior (no @option{-gnatn} switch specified), the
24808 compilation of the @code{Main} procedure depends only on its own source,
24809 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
24810 means that editing the body of @code{R} does not require recompiling
24811 @code{Main}.
24813 On the other hand, the call @code{R.Q} is not inlined under these
24814 circumstances. If the @option{-gnatn} switch is present when @code{Main}
24815 is compiled, the call will be inlined if the body of @code{Q} is small
24816 enough, but now @code{Main} depends on the body of @code{R} in
24817 @file{r.adb} as well as on the spec. This means that if this body is edited,
24818 the main program must be recompiled. Note that this extra dependency
24819 occurs whether or not the call is in fact inlined by @code{gcc}.
24821 The use of front end inlining with @option{-gnatN} generates similar
24822 additional dependencies.
24824 @cindex @code{^-fno-inline^/INLINE=SUPPRESS^} (@code{gcc})
24825 Note: The @code{^-fno-inline^/INLINE=SUPPRESS^} switch
24826 can be used to prevent
24827 all inlining. This switch overrides all other conditions and ensures
24828 that no inlining occurs. The extra dependences resulting from
24829 @option{-gnatn} will still be active, even if
24830 this switch is used to suppress the resulting inlining actions.
24832 Note regarding the use of @code{-O3}: There is no difference in inlining
24833 behavior between @code{-O2} and @code{-O3} for subprograms with an explicit
24834 pragma @code{Inline} assuming the use of @option{-gnatn}
24835 or @option{-gnatN} (the switches that activate inlining). If you have used
24836 pragma @code{Inline} in appropriate cases, then it is usually much better
24837 to use @code{-O2} and @option{-gnatn} and avoid the use of @code{-O3} which
24838 in this case only has the effect of inlining subprograms you did not
24839 think should be inlined. We often find that the use of @code{-O3} slows
24840 down code by performing excessive inlining, leading to increased instruction
24841 cache pressure from the increased code size. So the bottom line here is
24842 that you should not automatically assume that @code{-O3} is better than
24843 @code{-O2}, and indeed you should use @code{-O3} only if tests show that
24844 it actually improves performance.
24846 @ifset vms
24847 @node Coverage Analysis
24848 @section Coverage Analysis
24850 @noindent
24851 GNAT supports the Digital Performance Coverage Analyzer (PCA), which allows
24852 the user to determine the distribution of execution time across a program,
24853 @pxref{Profiling} for details of usage.
24854 @end ifset
24856 @include fdl.texi
24857 @c GNU Free Documentation License
24859 @node Index,,GNU Free Documentation License, Top
24860 @unnumbered Index
24862 @printindex cp
24864 @contents
24866 @bye